text
stringlengths
37
1.41M
def collapseDuplicates(a): output = "" last_char = None for char in a: if char == last_char: continue output += char last_char = char return output print collapseDuplicates("a"), "Should be", "a" print collapseDuplicates("aa"), "Should be", "a" print collapseDuplicates("abbbbcc"), "Should be", "abc"
#! /usr/bin/python from JackToken import JackToken class Node(object): """docstring for Node""" def __init__(self, value, depth=0): super(Node, self).__init__() self.elementName = None; self.elementVal = None; if type(value) is JackToken: self.elementName = value.getTokenType() self.elementVal = value.getToken() elif type(value) is str: self.elementName = value self.elementVal = None; self.value = value # is a Token class | value is a string self.depth = depth self.children = [] # Array<Node> (order is important) def isLeaf(self): return len(self.children) == 0 and self.elementName != None and self.elementVal != None def addChild(self, nodeVal): node = Node(nodeVal, self.depth + 1) self.children.append(node) def addChildTree(self, node): """IMPORTANT: Caller must make sure node.depth is correct """ self.children.append(node) def setElementName(self, name): self.elementName = name def walkAndPrint(self): indent = " " * self.depth currentTokenValue = indent + self.elementName + " (" + str(self.elementVal) + ")" if self.isLeaf(): print currentTokenValue else: print currentTokenValue for child in self.children: child.walkAndPrint()
def lastjump(a,n): i=0 while i<n: i+=a[i] try: if i==a[i]: return True except: return False def main(): a=[] n=int(input()) for i in range(n): a.append(int(input())) print(lastjump(a,n)) main()
def circle(a): area=3.14*a*a print("Area :", area) def rectangle(l,b): area=l*b print("Area :",area) def triangle(b,h): area=0.5*b*h print("Area :",area) def main(): try: a=int(input("Enter radius for circle :\n")) circle(a) print("\n ----Rectangle----\n") l=int(input("Enter length :\n")) b=int(input("Enter breadth :\n")) rectangle(l,b) print("\n----Triangle---- \n") b=int(input("\nEnter Breadth :\n")) h=int(input("Enter Height :\n")) triangle(b,h) except: print('invalid') main()
num1 = raw_input ("> ") num2 = raw_input ("> ") if num1 > num2: print "naimenshee chislo" + num2 else: print "naimenshee chislo" + num2
# @author Daphne Barretto # 12/01/2019 # AoC-2019-01 Part 1 # import miscellaneous operating system interfaces import os # get filename input.txt assuming it is in the same folder as the script filename = os.path.dirname(os.path.abspath(__file__)) + "/input.txt" # open the file in read mode file = open(filename, "r") fuel = 0 for mass in file: fuel += int(int(mass) / 3) - 2 print("Total fuel requirement: " + str(fuel)) # Answer: 3452245
"""The progress bar.""" import sys from collections.abc import Iterable, Sized from typing import TextIO, Tuple, Union from unicodedata import east_asian_width as eaw BAR_SYMBOLS = ("", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█") BAR_PREFIX = " |" BAR_SUFFIX = "| " class JabBar: """Just Another Beautiful progress BAR.""" def __init__( self, iterable: Iterable = None, total: int = None, comment: str = "", width: int = 24, file: TextIO = sys.stdout, enable: bool = True, keep: bool = True, symbols: Union[Tuple[str], str] = BAR_SYMBOLS, ): """Initialize the bar. :param iterable: An iterable to show the progress for while iterating :param total: The expected number of items :param comment: A comment to append to each line :param width: The width of the progress bar in characters :param file: The target where to write the progress bar to :param enable: Whether to actually show the progress bar :param keep: Whether to keep or remove the bar afterwards :param symbols: Bar symbols to use, with increasing fill degree """ self.iterable = iterable self.total: int = total self.comment: str = comment self.width: int = width self.file: TextIO = file self.enable: bool = enable self.keep: bool = keep if isinstance(symbols, str): symbols = (symbols,) symbols = tuple(symbols) if "" not in symbols: # add empty element symbols = ("",) + symbols self.symbols = symbols self.n_done: int = 0 self.len: int = 0 if isinstance(iterable, Sized) and total is None: total = len(iterable) self.total = total if self.total is None: raise ValueError( "Either must the iterable have a length attribute, " "or a total been specified.", ) def __enter__(self): """Prepare upon entering a context manager.""" return self def __exit__(self, exc_type, exc_value, traceback): """Tidy up Upon exiting a context manager.""" self.finish() def write(self, line: str, end="") -> None: """Write a line. :param line: The line to write, will be prefixed by a carriage return :param end: Symbol for the end of the line """ """Write a line in-place.""" self.len = len(line) print(line, end=end, file=self.file) self.file.flush() def update(self, n_done: int) -> None: """Update the output. :param n_done: The number of finished tasks. """ if not self.enable: return self.n_done = n_done line = self.get_line() self.write(line) def get_line(self) -> str: """Create the line containing the progress bar. :returns line: The line """ # fraction of done vs total r_done = self.n_done / self.total str_r_done = f"{int(r_done * 100):3}%" # width of the filled bar width_full = self.width * min(r_done, 1) # number of full bar fields is the integer below n_full = int(width_full) # number of full symbols n_symbol_full = int(n_full / nchar(self.symbols[-1])) bar_full = self.symbols[-1] * n_symbol_full # which of the bar symbols to select for the current symbol phase = int((width_full - n_full) * len(self.symbols)) # number of current symbols n_symbol_phase = 0 if len(self.symbols[phase]): n_symbol_phase = int(1 / nchar(self.symbols[phase])) bar_current = self.symbols[phase] * n_symbol_phase # number of empty symbols n_empty = self.width - nchar(bar_full) - nchar(bar_current) bar_empty = " " * n_empty str_done = f"{self.n_done}/{self.total}" line = ( "\r" + str_r_done + BAR_PREFIX + bar_full + bar_current + bar_empty + BAR_SUFFIX + str_done + " " + self.comment ) return line def inc(self, n: int = 1) -> None: """Update / increment by `n`. :param n: Number to increment by """ self.update(self.n_done + n) def finish(self) -> None: """Finish the line by a line break.""" if not self.enable: return if self.keep: self.write("", end="\n") else: self.write("\r" + " " * self.len + "\r") def __iter__(self): """Iterate over the iterable.""" if self.iterable is None: raise ValueError("To use jabbar in iterable mode, pass an iterable.") for val in self.iterable: yield val self.inc() self.finish() def nchar(symbol: str) -> int: """Calculate number of unit-width characters for a symbol. This may not work on all systems and for all symbols. :param symbol: The symbol (single character or string). :returns: A guess of the number of unit-width characters. """ return len(symbol) + sum(1 for char in symbol if eaw(char) in ["F", "W"]) # convenience alias jabbar = JabBar
import sys def decryptRailFence(cipher, key): rail = [[None for c in xrange(len(cipher))] for r in xrange(key)] row = 0 col = 0 for i in xrange(len(cipher)): if row == 0: down = True if row == key-1: down = False rail[row][col] = 'X' col+=1 if down: row+=1 else: row-=1 index = 0 i=0 while i<key and index<len(cipher): j=0 while j<len(cipher) and index<len(cipher): if rail[i][j] == 'X': rail[i][j] = cipher[index] index+=1 j+=1 i+=1 result = '' row = 0 col = 0 for i in xrange(len(cipher)): if row == 0: down = True if row == key-1: down = False if rail[row][col] != 'X': result += rail[row][col] col+=1 if down: row+=1 else: row-=1 return result if __name__ == '__main__': try: depth = input() if depth>10: raise ValueError except ValueError: sys.exit() cipher = raw_input() print decryptRailFence(cipher, depth)
from dataclasses import dataclass @dataclass class Position: x:int = 0 y:int = 0 def __iadd__(self,other): self.x+=other.x self.y+=other.y return self def checkSlope(areaMap,slope):#Check the amount of trees in your trajectory descending areaMap with given slope. pos = Position(0,0) trees = 0 while pos.x < len(areaMap): pos.y%= len(areaMap[pos.x]) if areaMap[pos.x][pos.y]=='#': trees+=1 pos+= slope return trees def part1(areaMap):#checkSlope with slope (1,3) return checkSlope(areaMap,Position(1,3)) def part2(areaMap):#checks trees encountered for each of the requested slopes and returns its product slopes = [(1,1),(1,3),(1,5),(1,7),(2,1)] res = 1 for x,y in slopes: res*=checkSlope(areaMap,Position(x,y)) return res with open('3.in') as inputFile: inputLines = inputFile.read().splitlines() print('Solutions:') print('Trees encountered with slope 1,3:', part1(inputLines)) print('Product of Trees encountered with each slope:', part2(inputLines))
import time as t import numpy as np import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv', 'nyc': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(city, month, day): """ Asks users to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print ('Hello! Let\'s explore major US bikeshare data!') print ('') #Get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs t.sleep(1) while True: print ("Which city bikeshare data would you like to explore?\n") city = input("Chicago, NYC or Washington?\n").lower() if city not in ("chicago", "nyc", "washington"): print("\nInvalid answer\n") continue else: break print("\nNow how do you want to filter your data?\n") #Get user input for month (all, january, february, ... , june) data_filter = input("Month, day, or both?\n").lower() while True: if data_filter not in ("month", "day", "both", "none"): print("\nInvalid answer\n") data_filter = input("Month, day, both, or none?\n") elif data_filter == "month": print("Which month do you want to explore?\n") month = input("January, february, march, april, may, june or all?\n").lower() day = 'all' while True: if month not in ['january', 'february', 'march', 'april', 'may', 'june', 'all']: print("\nInvalid answer\n") month = input("January, february, march, april, may, june or all?\n").lower() else: break break elif data_filter == "day": print("Which day do you want to explore?\n") day = input("Monday, tuesday, wednesday, thursday, friday, saturday, sunday or all?\n").lower() month = 'all' while True: if day not in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday','all']: print("\nInvalid answer\n") day = input("Monday, tuesday, wednesday, thursday, friday, saturday, sunday or all?\n").lower() else: break break elif data_filter == "both": print("Which month do you want to explore?\n") month = input("January, february, march, april, may, june or all?\n").lower() while True: if month not in ['january', 'february', 'march', 'april', 'may', 'june', 'all']: print("\nInvalid answer\n") month = input("January, february, march, april, may, june or all?\n").lower() else: break print("Now which day do you want to explore?\n") day = input("Monday, tuesday, wednesday, thursday, friday, saturday, sunday or all?\n").lower() while True: if day not in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday','all']: print("\nInvalid answer\n") day = input("Monday, tuesday, wednesday, thursday, friday, saturday, sunday or all?\n").lower() else: break break print("---> ", city) print("---> ", month) print("---> ", day) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ df = pd.read_csv(CITY_DATA[city]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month and day of week from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name # filter by month if applicable if month != 'all': months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': #filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" start_time = t.time() print('\nCalculating The Most Frequent Times of Travel...\n') print('') #display the most common month df['month'] = df['Start Time'].dt.month common_month = df['month'].mode()[0] print('Most Common Month:', common_month) print('') #display the most common day of week df['week'] = df['Start Time'].dt.week common_week = df['week'].mode()[0] print('Most Common day of week:', common_week) print('') #display the most common start hour df['hour'] = df['Start Time'].dt.hour common_hour = df['hour'].mode()[0] print('Most Common Start Hour:', common_hour) print('') print("\nThis took %s seconds." % (t.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') print('') start_time = t.time() #display most commonly used start station common_start_station = df['Start Station'].mode()[0] print('Most Common Start Station:', common_start_station) print('') #display most commonly used end station common_end_station = df['End Station'].mode()[0] print('Most Common End Station:', common_end_station) print('') #display most frequent combination of start station and end station trip df['combo'] = df['Start Station'] + ' to ' + df['End Station'] common_station_combo = df['combo'].mode()[0] print('Most common Combination:', common_station_combo) print('') print("\nThis took %s seconds." % (t.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = t.time() #display total travel time total_travel_time = df['Trip Duration'].sum() print('Total Travel Time:', total_travel_time) print('') #display mean travel time average = df['Trip Duration'].mean() print('Mean/Average Travel Time:', average) print('') print("\nThis took %s seconds." % (t.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = t.time() #Display counts of user types user_types = df['User Type'].value_counts() print('Counts of user types:', user_types) print('') #Display counts of gender if 'Gender' in df: gender = df['Gender'].value_counts() print('Counts of gender:', gender) print('') else: print("Gender information is not available for this city!") #Display earliest, most recent, and most common year of birth if 'Birth_Year' in df: earliest_birth_year = df['Birth_Year'].min() print('Earliest Birth Year:', earliest_birth_year) print('') recent_birth_year = df['Birth Year'].max() print('Recent Birth Year:', recent_birth_year) print('') common_birth_year = df['Birth Year'].mode()[0] print('Most Popular Birth Year:', common_birth_year) print('') else: print("Birth year information is not available for this city!") print("\nThis took %s seconds." % (t.time() - start_time)) print('-'*40) def data(df): """ Displays 5 rows of raw data at a time """ line_number = 0 print("\nDo you want to see raw data?\n") answer = input("Yes or no?\n").lower() if answer not in ['yes', 'no']: print("\nInvalid answer\n") answer = input("Yes or no?\n").lower() elif answer == 'yes': while True: line_number += 5 print(df.iloc[line_number : line_number + 5]) print("\nDo you want to see more raw data?\n") continues = input("Yes or no?\n").strip().lower() if continues == 'no': break elif answer == 'no': return def main(): city = "" month = 0 day = 0 while True: city, month, day = get_filters(city, month, day) df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
""" Clase Abstracta que define los metodos claves de la especificacion """ class BaseEspecificacion: def __init__(self, objeto): self._objeto = objeto return def es_satifecho_por(self, objeto): pass def y(self, especificacion): pass def o(self, especificacion): pass def no(self, especificacion): pass """ Clases Abstracta que implementan y(), o(), no() """ class BaseEspecificacionCompuesta(BaseEspecificacion): def y(self, especificacion): return Yespecificacion(self, especificacion) def o(self, especificacion): return Oespecificacion(self, especificacion) def no(self, especificacion): return NOespecificacion(especificacion) class Yespecificacion(BaseEspecificacionCompuesta): def __init__(self, espec_izquierda, espec_derecha): self._espec_izquierda = espec_izquierda self._espec_derecha = espec_derecha return def es_satifecho_por(self, objeto): return self._espec_izquierda.es_satisfecho_por(objeto) and\ self._espec_derecha.es_satisfecha_por(objeto) class Oespecificacion(BaseEspecificacionCompuesta): def __init__(self, espec_izquierda, espec_derecha): self._espec_izquierda = espec_izquierda self._espec_derecha = espec_derecha return def es_satifecho_por(self, objeto): return self._espec_izquierda.es_satisfecho_por(objeto) or\ self._espec_derecha.es_satisfecha_por(objeto) class NOespecificacion(BaseEspecificacionCompuesta): def __init__(self, espec): self._espec = espec return def es_satifecho_por(self, objeto): return not(self._espec.es_satisfecho_por(objeto)) """ Aplica el patron Specification a una Entidad """ from abc import * class BaseEspecificacion(metaclass=ABCMeta): """ Define la interfaz para el uso del patron """ @abstractmethod def es_satisfecho_por(self, candidata): """ Define el criterio con que se debe satifacer el requerimiento sobre la entidad candidata :param candidata: Entidad sobre la que se evalua :return: Booleano si cumple o no el requerimiento """ def y(self, otra): """ Define el conjuncion Y para determinar especificaciones compuestas :param otra: La otra especificacion con la que se requiere componer y cumplir :return: Especificacion """ return YEspecificacion(self, otra) def o(self, otra): """ Define el conjuncion O para determinar especificaciones compuestas :param otra: La otra especificacion con la que se requiere componer y cumplir :return: Especificacion """ return OEspecificacion(self, otra) def no(self): """ Define y no cumplimiento de la especificacion :return: Especificacion """ return NOEspecificacion(self) class EspecificacionCompuesta(BaseEspecificacion): """ Define la estrucura interna con dos especificaciones para evaluar ambas """ def __init__(self, espec_izquierda, espec_derecha): """ Inicializa la instancia de especificacion :param espec_izquierda: :param espec_derecha: """ self._izquierda = espec_izquierda self._derecha = espec_derecha return class YEspecificacion(EspecificacionCompuesta): """ Define la Especificacion Compuesta Y """ def __init__(self, espec_izquierda, espec_derecha): super().__init__(espec_izquierda, espec_derecha) def es_satisfecho_por(self, candidata): """ Determina si la especficacion es satifecha, ejecuta una validacion que las dos especificaciones sean verdaderas :param candidata: :return: booleano """ return self._izquierda.es_satisfecho_por(candidata) and\ self._derecha.es_satisfecho_por(candidata) class OEspecificacion(EspecificacionCompuesta): """ Define la Especificacion Compuesta O """ def __init__(self, espec_izquierda, espec_derecha): super().__init__(espec_izquierda, espec_derecha) def es_satisfecho_por(self, candidata): """ Determina si la especficacion es satifecha, ejecuta una validacion que alguna de las dos especificaciones sean verdaderas :param candidata: :return: booleano """ return self._izquierda.es_satisfecho_por(candidata) or\ self._derecha.es_satisfecho_por(candidata) class NOEspecificacion(BaseEspecificacion): """ Define la Especificacion No """ def __init__(self, especificacion): self._especificacion = especificacion def es_satisfecho_por(self, candidata): """ Determina si la especficacion es satifecha cuando no cumple con el requerimiento :param candidata: :return: booleano """ return not self._especificacion.es_satisfecho_por(candidata)
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder, their colleagues and Austin Strozier. """ ######################################################################## # Done: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. ######################################################################## ######################################################################## # DONE: 2. # # You should have RUN the PREVIOUS module and READ its code. # (Do so now if you have not already done so.) # # Below this comment, add ANY CODE THAT YOUR WANT, as long as: # 1. You construct at least 2 rg.SimpleTurtle objects. # 2. Each rg.SimpleTurtle object draws something # (by moving, using its rg.Pen). ANYTHING is fine! # 3. Each rg.SimpleTurtle moves inside a LOOP. # # Be creative! Strive for way-cool pictures! Abstract pictures rule! # # If you make syntax (notational) errors, no worries -- get help # fixing them at either this session OR at the NEXT session. # # Don't forget to COMMIT your work by using VCS ~ Commit and Push. import rosegraphics as rg window = rg.TurtleWindow boy = rg.SimpleTurtle('turtle') bill = rg.SimpleTurtle('turtle') bill.speed = 20 boy.speed = 10 boy.pen = rg.Pen('midnight blue', 3) bill.pen = rg.Pen('midnight blue', 3) size = 288 for d in range(10): boy.draw_square(size) bill.draw_square(size) bill.pen_up boy. pen_up bill.right(45) bill.forward(12) bill.left(45) boy.left(45) boy.forward(50) boy.right(45) bill.pen_down boy.pen_down size = size-10
# list part 1 subjects = ['python', 'java', 'car'] print(subjects) print(subjects[0]) print(subjects[1:]) print(subjects[-1]) # in / not in print("java" in subjects) print("ada" in subjects) print("ada" not in subjects) # add anything print(subjects + [' rubi ' ,89] ) print(subjects * 3)
#!/usr/bin/env python # coding: utf-8 # # 口コミ(食べログ) # we will try to find about "When I visit Japan (or particular town in Japan) what kind of food that is recomended by Japanese that should I try?" # # This code will contain of the data scraping and data cleaning part # # Data Scraping # In[ ]: #import the library import requests from bs4 import BeautifulSoup import pandas as pd import re import string # In[ ]: #define the scraping path #put your own User-Agent headers = {'User-Agent': '...'} rstlst_all=[] def getRstlst(town,page): url = f'https://tabelog.com/{town}/rstLst/{page}/' page = requests.get(url, headers=headers) soup = BeautifulSoup(page.text, 'html.parser') rstlsts = soup.find_all('div', {'class':'list-rst__contents'}) for item in rstlsts: rstlst = { 'town' : town, 'rst_kind' : item.find('div', {'class':'list-rst__area-genre cpy-area-genre'}).text, 'rst_star' : item.find('span', {'class':'c-rating__val c-rating__val--strong list-rst__rating-val'}), 'rst_rvwcnt' : item.find('em',{'class':'list-rst__rvw-count-num cpy-review-count'}).text } rstlst_all.append(rstlst) return # In[ ]: ##try the function for 1 town at first ##here, we want to obtain the data for Tokyo in the page 1 to 50 for n in range (1,50): getRstlst('tokyo',n) print(len(rstlst_all)) # In[ ]: ##apply to multiple town towns = ['tokyo','osaka','kyoto'] for town in towns: n in range(1,50) getRstlst(town,n) print(len(rstlst_all)) # In[ ]: ##store the data into Pandas dataframe for easiness ##you can export the data first as well data = pd.DataFrame(rstlst_all) print(data.head()) #data.to_excel('ロコミ_Q1.xlsx') #print('done') # # Data Cleaning # in this case, data cleaning only necessary for the 'rst_kind' part # In[ ]: #read the data #data = pd.read_excel('ロコミ_Q1.xlsx') # In[ ]: def clean_kind(text): text = re.sub('その他','',text) text = re.sub('\n','',text) text = re.sub('・',' ',text) text = re.sub('、',' ',text) text = re.sub('[()]','', text) return text data['rst_kind'] = data['rst_kind'].apply(clean_kind) new = data['rst_kind'].str.split('/', n = 1,expand=True) data['rst_loc'] = new[0] data['rst_kind'] = new[1] print(data.head()) # In[ ]: # Saving your data for further analysis data.to_excel('ロコミ_Q1_clean.xlsx') print('done') # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
# To find biggest of given two numbers from the key board #!/usr/bin/python #x=int(input("Enter The 1st Number:")) #y=int(input("Enter The 2nd Number:")) #z=int(input("Enter The 3rd Number:")) #if x>y and x>z: #print("The Bigger Number is:",x) #else: # print("The Smaler Number is:",y) #print("The Smalest Number is:",z) #if x<y: # print("The Smalest Number is:",x) #elif y>z: #print("The Smalest Value is:",z)
#!/usr/bin/python ########## Right Triangle Shape ########## x=int(input("Enter The Number Of Rows:")) for y in range(1,x+1): for z in range(1,y+1): print("*",end="") print()
#!/usr/bin/python n=int(input('Enter The N Rows:')) #for i in range(0,n): #for j in range(0,n-i-1): #print(end=" ") #for j in range(0,2*2*i+1): #print("*",end="") #print() ########## Using for loop ########### def pyramid(rows): for i in range(rows): print(''*(rows-i-1)+'*'*(2*i+1)) #pyramid(5)
class Person: def __init__(self): print("Init the class") if __name__=="__main__": print("111") a=0 person1 = Person() print("2222") a=1 print(2+3)
from PointT import* from Ships import* from Board import* # Tyler Philips #April 1 the work being submitted is your own individual work #ASSUME: there are 2 real players. No cpu ## @brief this class has functinos that bring the other classes together and create a game ## @param boardsP1 is board abject for player 1. it keeps track of their state ## @param boardsP2 is board abject for player 2. it keeps track of their state ## @param shipsP1 is a list of ship objects for player 1 ## @param shipsP2 is a list of ship objects for player 2 ## The constructor PointT is called for each abstract object before any other access routine is called for that object. The constructor cannot be called on an existing object. class BattleShip: #start up #give each player a board and a list of ships #they will have to decide the locations for the ship global boardsP1,boardsP2,shipsP1,shipsP2 boardsP1= Board() boardsP2= Board() shipsP1=[None]*5 shipsP2 = [None] *5 ## @brief this function runs one turn for player 1 ## @param word is a string input of the players shot ## @param shot is a pointT object of the shot ## @param x is string used to split word ## @param y is string used to split word ## @param hit is a boolean value that keeps track if the shot hit a ship ## @param shipsP2 is a list of ship objects for player 2 ## @param boardsP1 is board abject for player 1. it keeps track of their state def turnP1(self): #take input point maybe check for validity if it has already been done print"\nP1's turn:" print "P1: upper board " boardsP1.printUpper() print "P1: lower board " boardsP1.printLower() #TAKE SHOT INPUT word = raw_input('P1 enter your shot: ') x, y = word.split(",") shot = PointT(ord(x)-65, int(y)-1) hit=False#keeps track of hit, used for output to screen if(shot.isValid(boardsP1.upper())):#if valid shot #add mark to upperboard 1 boardsP1.markUpper(shot) #if its a hit mark lowerboard 2 adn to the ship that got hit for x in shipsP2: if(x.isHit(shot)): boardsP2.hitShip(shot)#mark player 2s game board if their ship is hit hit=True break if(hit):print"Direct Hit!" else:print"Missed!" ## @brief this function runs one turn for player 2 ## @param word is a string input of the players shot ## @param shot is a pointT object of the shot ## @param x is string used to split word ## @param y is string used to split word ## @param hit is a boolean value that keeps track if the shot hit a ship ## @param shipsP1 is a list of ship objects for player 1 ## @param boardsP2 is board abject for player 2. it keeps track of their state def turnP2(self): #take input point maybe check for validity if it has already been done print"\nP2's turn:" print "P2: upper board " boardsP2.printUpper() print "P2: lower board " boardsP2.printLower() #TAKE SHOT INPUT word = raw_input('P2 enter your shot: ') x, y = word.split(",") shot = PointT(ord(x)-65, int(y)-1) hit = False # keeps track of hit, used for output to screen if(shot.isValid(boardsP2.upper())):#if valid shot #add mark to upperboard 1 boardsP2.markUpper(shot) #if its a hit mark lowerboard 2 adn to the ship that got hit for x in shipsP1: if(x.isHit(shot)): boardsP1.hitShip(shot)#mark player 2s game board if their ship is hit hit = True break if (hit): print"Direct Hit!" else: print"Missed!" ## @brief this function creates the ships for each player ## @param word is a string input of the players shot ## @param p1 is a pointT object that is start of ship ## @param p2 is a pointT object that is end of ship ## @param x is string used to split word ## @param y is string used to split word ## @param x2 is string used to split word ## @param y2 is string used to split word ## @param ship is ship object ## @param shipLengths isan array that stores the length of the 5 ships for each user ## @param shipsP1 is a list of ship objects for player 1 ## @param shipsP2 is a list of ship objects for player 2 ## @param boardsP1 is board abject for player 1. it keeps track of their state ## @param boardsP2 is board abject for player 2. it keeps track of their state def setup(self): print"BATTLESHIP\n____________________________________________________________" shipLengths=[2,3,3,4,5] #get ships ##get SHIPS FOR P1 print"Player 1..." for i in range(0,5): word = raw_input("Enter the starting point and end point of ship (eg.A,1,A,3):") x,y,x2,y2=word.split(",") p1,p2=PointT(ord(x)-65,int(y)-1),PointT(ord(x2)-65,int(y2)-1)#MAKE START AND END POINT OF SHIP ship=Ships(shipLengths[i],p1,p2)#MAKE SHIP boardsP1.placeShip(ship.getCoords())#MARK SHIP LOCATION ON GAMEBOARD shipsP1[i]=ship print "P1: lower" boardsP1.printLower() print"Player 2..." for i in range(0, 5): word = raw_input("Enter the starting point and end point of ship (eg.A,1,A,3):") x, y, x2, y2 = word.split(",") p1, p2 = PointT(ord(x) - 65, int(y) - 1), PointT(ord(x2) - 65,int(y2) - 1) # MAKE START AND END POINT OF SHIP ship = Ships(shipLengths[i], p1, p2) # MAKE SHIP boardsP2.placeShip(ship.getCoords()) # MARK SHIP LOCATION ON GAMEBOARD shipsP2[i] = ship print "P2: lower" boardsP2.printLower() ## @brief this function returns a boolean based on if someone has one the game or not ## @param p2Won is a boolean value used to keep track of whether p2 won the game of not ## @param p1Won is a boolean value used to keep track of whether p1 won the game of not ## @param p1 is a pointT object that is start of ship ## @param shipsP1 is a list of ship objects for player 1 ## @param shipsP2 is a list of ship objects for player 2 ## @return boolean on if game is over or not def finished(self): p2Won=False p1Won=False #check if p2 won for ship in shipsP1:#check each of p1's ships to see if they are all sunk if(ship.isSunk()): p2Won=True else: p2Won=False break # check if p1 won for ship in shipsP2: if(ship.isSunk()):#check each of p2's ships to see if they are all sunk p1Won=True else: p1Won=False break #return boolean value and print output based on if statements if(p1Won): print "P1 has won!" return True elif(p2Won): print "P2 has won!" return True else: return False # @brief this function builds the game together, it calls all the other functions in BattleShip.py to setup and continue #the game until finished returns True def play(): game = BattleShip() game.setup() while (not game.finished()): # continue game until there is a victor game.turnP1() if (game.finished()): break # if player one just defeated p2 end game game.turnP2() #this will be the main function for this class. it will call all the other functions to play the game def main(): play() if __name__=='__main__': main()
# coding: utf-8 import sys, re def flip_dict(dict_to_flip): ''' flip a dict. Parameters ---------- dict_to_flip : dict Examples -------- >>> flip_dict({'a': 2, 'b': 3, 'c': 4}) {2: 'a', 3: 'b', 4: 'c'} Notes that duplicated data will be automaticly dropped >>> flip_dict({'a': 3, 'b': 3, 'c': 4}) {3: 'a', 4: 'c'} See Also -------- flip_dict_full ''' return dict([i[::-1] for i in dict_to_flip.items()]) def split_wrd(string,sep,rep=None,ignore_space=False,kind='split'): ''' split a string with given condition Parameters ---------- string : str string to process sep : str or iterable for each item in sep, call string.split() method rep : None or str or iterable, default None - None : return a list containing all items seprated by sep - str : return a string with all items in sep replaced by rep - iterable : return a string with all sep[i] replaced by rep[i] ignore_space : bool - whether to call strip() at each element kind : str - `split` : call str.split() method - `re` : call re.split() method See Also -------- split_at ''' if kind not in ['split','re']: raise ValueError('kind passed should be `split` or `re`') if type(sep) == str: sep = [sep] if rep == None: string = [string] for j in sep: ts = [] for i in string: if kind == 'split': ts += i.split(j) elif kind == 're': ts += re.split(j,i) string = ts if ignore_space: return [i.strip() for i in string if i.strip()] else: return [i for i in string if i] else: if type(rep)==str: for i in sep: if kind == 'split': string = rep.join(string.split(i)) elif kind == 're': string = rep.join(re.split(i,string)) return string else: for i,j in zip(sep,rep): if kind == 'split': string = j.join(string.split(i)) elif kind == 're': string = j.join(re.split(i,string)) return string def split_at(string,sep,ignore_space=False,kind='split'): ''' split a string at given condition Parameters ---------- string : str string to process sep : str or iterable for each item in sep, call string.split() method ignore_space : bool - whether to call strip() at each element kind : str - `split` : call str.split() method - `re` : call re.split() method See Also -------- split_wrd ''' if kind not in ['split','re']: raise ValueError('kind passed should be `split` or `re`') if type(sep) == str: sep = [sep] string = [string] for i in sep: ts = [] for j in string: if kind == 'split': ts += [s+i for s in j.split(i)] elif kind == 're': ts += [s+i for s in re.split(i,j)] ts[-1] = ts[-1][:-1] if ignore_space: string = [s for s in ts if s.strip()] else: string = ts return string def flip_dict_full(dict_to_flip): ''' flip a dict with no data loss Parameters ---------- dict_to_flip : dict See Also -------- flit_dict Examples -------- >>> flip_dict_full({'a': 1, 'b': 2, 'c': 3}) {1: ['a'], 2: ['b'], 3: ['c']} >>> flip_dict_full({'a': 3, 'b': 3, 'c': 4}) {3: ['a', 'b'], 4: ['c']} ''' t = [i[::-1] for i in dict_to_flip.items()] tp = dict() for i in t: if i[0] in tp: tp[i[0]] = tp[i[0]] + [i[1]] if type(tp[i[0]])==list else [tp[i[0]]] + [i[1]] else: tp[i[0]] = [i[1]] return tp def transfer_datatype(data): ''' call eval(data) if data is valid ''' if type(data) == list or not data: return data else: try: return eval(data) except: return data def _in_list(x,ls,how='find'): ''' check if x match rules in ls parameters: x : str-like or numeric variable ls : iterable containing rules how : str functions only if type of x is str - 'find' : call x.find(rule) - 're' : call re.find(rule,x) - 'fullmatch' : x == rule ''' if type(x) == str: if how == 'find': for item in ls: if x.find(item) >= 0: return True elif how == 're': for item in ls: if re.findall(item,x): return True elif how == 'fullmatch': for item in ls: item = str(item).strip() if item == x: return True return False else: x = int(x) ls = [int(i) for i in ls] for item in ls: if x == item: return True return False def be_subset(sub,main): ''' return True if sub is a subset of main. ''' res = True for i in sub: res &= (i in main) return res class InteractiveAnswer(): ''' an enhanced version for input. Parameters ---------- hint : str hint string that will be printed before reading an input. verify : list-like a list that confines the user's input. serializer : function serialize function that will preprocess user's input. encode : dict (experimental) replace exact input in keys by values. suggest using it only if `verify` is set. yes_or_no : bool a preset value that will get yes or no questions. Examples -------- >>> InteractiveAnswer('Continue?',yes_or_no=True).get() Continue?(y/n) Continue?(y/n)y True >>> InteractiveAnswer("What's your name?",serializer=lambda x:x.title()).get() What's your name?eric xie 'Eric Xie' >>> InteractiveAnswer("Which level to choose?",verify='12345',serializer=lambda x:x.split()).get() Which level to choose?(1-5)1 2 ['1', '2'] >>> InteractiveAnswer('How old are you?',verify=range(1,126),serializer=int).get() How old are you?(1-125)120 120 ''' def __init__(self,hint='',verify=None,serializer=lambda x:x,encode=None,yes_or_no=False,accept_empty=False): if yes_or_no: self._verify = 'yn' self._serializer = lambda x: x.lower()[0] self._encode = {'y':True,'n':False} self._accept_empty = False else: self._verify = verify self._serializer = serializer self._encode = encode self._accept_empty = accept_empty self._hint = hint if self._verify: try: self._hint += '(' + squeeze_numlist(self._verify) + ')' except: self._hint += '('+'/'.join([i for i in list(self._verify)])+')' def process(self,get): if not self._accept_empty: if not get: return try: get = self._serializer(get) get_is_list = type(get) == list if self._verify: get = get if get_is_list else [get] if not be_subset(get,self._verify): return if self._encode: get = [self._encode[i] for i in get] return get[0] if not get_is_list and len(get) == 1 else get except: return def get(self): while 1: get = self.process(input(self._hint).strip()) if get != None: return get def space_fill(string,length,align='c',uwidth=2,spcwidth=1): ''' fill spaces to a certain length. Parameters ---------- string : str length : int align : char - `c` : centered - 'l' : left-aligned - 'r' : right-aligned uwidth : int relative width of utf8 characters with latin characters ''' string = str(string) delta = uwidth - 1 ulen = (len(string.encode('utf-8')) - len(string))//2 strlen = int(len(string) + delta * ulen) if length < strlen: length = strlen if align[0] == 'c': leftspc = (length-strlen)//2 rightspc = length-strlen-leftspc elif align[0] == 'l': leftspc = 0 rightspc = length-strlen elif align[0] == 'r': rightspc = 0 leftspc = length-strlen else: raise ValueError('align not in [`c`,`l`,`r`]') leftspc = int(leftspc/spcwidth) rightspc = int(rightspc/spcwidth) return ' '*leftspc+string+' '*rightspc def cstrcmp(str1, str2): ''' compare two strings (or iterables). returns the index where str1 is different from str2 Examples -------- >>> cstrcmp('compare','compulsory') -4 >>> cstrcmp('compulsory','compare') 4 >>> cstrcmp('compute','computer') -7 >>> cstrcmp([1,2,3,4,5],[1,2,4,5,6]) -2 ''' i = 0 while i < min(len(str1),len(str2)): try: diff = str1[i] - str2[i] # numeric data support except: diff = ord(str(str1[i])) - ord(str(str2[i])) if diff: return diff // abs(diff) * i i += 1 return (len(str1) - len(str2)) * min(len(str1),len(str2)) def squeeze_numlist(numlist,sort=False): ''' squeeze a numlist. ''' if sort: numlist = sorted([int(i) for i in numlist]) length = len(numlist) out = [] while length > 1: comp = range(int(numlist[0]),int(numlist[0])+length) ind = abs(cstrcmp(numlist,comp)) if ind == 1: out.append(comp[0]) else: out.append('%d-%d'%(comp[0],comp[ind-1])) if ind == 0: break numlist = numlist[ind:] length = len(numlist) return ','.join(out) def unsqueeze_numlist(numlist): ''' unsqueeze a numlist squeezed by function squeeze_numlist(). ''' numlist = [i.split('-') for i in split_wrd(numlist,',')] out = [] for i in numlist: if len(i)==1: out.append([int(i[0])]) else: out.append(list(range(int(i[0]),int(i[1])+1))) return sum(out,[]) def colorit(string,color): colors = ['black','red','green','yellow','blue','magenta',\ 'cyan','white','gray','lightred','lightgreen','lightyellow',\ 'lightblue','lightmagenta','lightcyan'] if type(color) == str: if color not in colors: raise ValueError('Given color',color,'not supported') color = colors.index(color) else: if color not in range(256): raise ValueError(color,'is not a 256-color index') return '\033[38;5;%dm%s\033[0m'%(color,string) def auto_newline(string, thresh=78, combine=True, remove_spaces=False, auto_indent=True): ''' autometically change the linebreaks. PARAMETERS ---------- string : str thresh : int max line broadth combine : bool whether to regard an exact `\n` as a linebreak or the end of a passage. remove_spaces : bool whether to remove spaces in the head and tail. ''' if combine: string = re.sub(r' *([^\n]) *\n *([^\n]) *',r'\1 \2',string) strls = split_at(string,'\n') if remove_spaces: strls = [re.sub(r'^ *(.*) *(\n+)',r'\1\2',i) for i in strls] if auto_indent: indents = [re.findall('^ +\(?\d*\.?\)?\+?-?\*?>? *',i) for i in strls] indents = [len(i[0]) if len(i)>0 else 0 for i in indents] else: indents = [0]*len(strls) for l in range(len(strls)): line = strls[l] length = len(line) if length < thresh: continue preferred_sep = sorted(set(i.end()-1 for i in re.finditer(r'[;,. ]+[^\n]',line)))+[length] th = thresh prev = th for s in preferred_sep: if s > th: strls[l] = strls[l][:prev-length]+'\n'+(not combine)*'\t'\ +indents[l]*' '+strls[l][prev-length:] th += thresh prev = th else: prev = s return ''.join(strls)
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def min_node(self): if self.left is not None: return self.left.min_node() return self class BinaryTree: def __init__(self, root=None): if not root: self.root = root else: self.root = Node(root) @staticmethod def find_min(node): node = node.min_node() return node def insert(self, value): if not self.root: self.root = Node(value) else: self._insert(self.root, value) def _insert(self, node, value): new_node = Node(value) if value < node.data: if not node.left: node.left = new_node else: self._insert(node.left, value) else: if not node.right: node.right = new_node else: self._insert(node.right, value) def remove(self, value): self.root = self._remove(self.root, value) def _remove(self, node, value): if not node: print(f'{value} is not in the tree.') elif value < node.data: node.left = self._remove(node.left, value) elif value > node.data: node.right = self._remove(node.right, value) else: if not node.left and not node.right: node = None return node elif not node.left: node = node.right return node elif not node.right: node = node.left return node else: min_right = self.find_min(node.right) node.data = min_right.data node.right = self._remove(node.right, node.data) return node def contains(self, value): if not self.root: return False return self._contains(self.root, value) def _contains(self, node, value): if value == node.data: return True elif value < node.data and node.left: return self._contains(node.left, value) elif value > node.data and node.right: return self._contains(node.right, value) else: return False def print_in_order(self): self._print_in_order(self.root) print() def _print_in_order(self, node): if node: self._print_in_order(node.left) print(node.data, end=" ") self._print_in_order(node.right) def print_post_order(self): self._print_post_order(self.root) print() def _print_post_order(self, node): if node: self._print_post_order(node.left) self._print_post_order(node.right) print(node.data, end=" ") def print_pre_order(self): self._print_pre_order(self.root) print() def _print_pre_order(self, node): if node: print(node.data, end=" ") self._print_pre_order(node.left) self._print_pre_order(node.right)
"""Write two modules pytasks.py and runner.py. Module pytasks contains definition for functions from previous tasks. Separate module runner contains runner() function. runner module can be imported or started from command line as script. generate_numbers() count_characters() fizzbuzz() – returns list with values is_palindrome() - returns True or False. runner() function can be called as: runner() – all functions will be called with default values and result printed to screen runner(‘generate_numbers’) – print result only for generate_numbers() runner(‘generate_numbers’, ‘happy_numbers’) – print results for generate_numbers() and happy_numbers(). Any combination of functions can be specified.""" import pytasks def runner(*functions): """Функция импорта из pytasks.py""" if not functions: for func in dir (pytasks): if callable(getattr(pytasks, func)): print(getattr(pytasks, func)()) else: for function_name in functions: if hasattr(pytasks, function_name) and ( callable(getattr(pytasks, function_name))): print(getattr(pytasks, function_name)()) runner() runner('generate_numbers') runner('generate_numbers', 'is_palindrome', 'count_characters', )
dolar=float(input("Insira o valor em reais que possui: ")) reais=float(input("Insira o valor da cotação do dolar: ")) print("O valor em dolares é ",dolar*reais)
x = int(input('Insira o primeiro valor: ')) y = int(input('Insira o segundo valor: ')) print('A soma destes valores é: ',x+y)
data = int(input('Digite a data do seu aniversário: ')) DD = data//10000 MM = data//100 - DD*100 AA = data - DD*10000 - MM*100 print(AA,MM,DD)
Compare two list and return matches, without using for loop a = [1, 2, 3, 4, 5] b = [9, 5, 7, 6, 8] Common element = 5 a = [1, 2, 3, 4, 5] b = [9, 5, 7, 6, 8] sa = set(a) print(sa.intersection(b))
# Foizni topish dasturi # a sonni P foizni topish progi print("A sonni P foizini topish") a = int(input("a sonni kiritin: ")) p = int(input("P foizni kiritin: ")) x = a * p / 100 print("a sonni P foizi shu: ",x)
login = input('Yangi login tanlang:') if len(login) <= 5: # agar login 5 harifdan kichik bulsa 1 print('Login 5 harfdan kup bulishi kerak') else: print('login qabul qilindi')
son = input('ixtiyoriy son kiritin:') if int(son) <=50: print('kiiritilgan son 50 teng yoki kichik ') else: print('kiritilgan son 50 dan katta')
ism = input('Ismingiz nima:\n') if ism.lower() != 'valijon': print(f"uzur {ism.title()} biz Valijon ni kutyapmiz") else: print("salom Valijon")
from policy import Policy from board import Board class AI: def __init__(self, Computer): self.shape = Computer self.computer = Policy(self.shape) def Opponent(self): if self.shape == "X": return "O" return "X" # Check if there is any spaces left on board def moveLeft(self, board): for i in range(15): for j in range(15): if board.config[i][j] == 0: return True return False # Check if the maxPlayer or minPlayer win or not def Evaluate(self, board, maxPlayer, x, y): if maxPlayer: if self.computer.checkWin(board, x, y): return 10 else: if self.computer.checkWin(board, x, y): return -10 return 0 def MiniMax(self, board, depth, maxPlayer, x, y): score = self.Evaluate(board, maxPlayer, x, y) # print(score) if score == 10: # print("The maxPlayer has won") # checking cast if the computer won return score - depth elif score == -10: # checking the cast if the player won #print("The minPlayer has won") return score + depth if self.moveLeft(board): # #print("The board is full") return 0 if maxPlayer: best = -1000000 for x in range(15): for y in range(15): # if board.config[x][y] == 0: if self.computer.CheckLegal(board, x, y): board.config[x][y] = self.shape score = self.MiniMax( board, depth + 1, not(maxPlayer), x, y) if score > best: best = score board.config[x][y] = 0 return best else: best = 10000000 for i in range(15): for j in range(15): # if board.config[i][j] == 0: if self.computer.CheckLegal(board, x, y): board.config[i][j] = self.Opponent() score = self.MiniMax( board, depth + 1, not(maxPlayer), i, j) if score < best: best = score board.config[i][j] = 0 return best # Finding the best move def findBestMove(self, board): bestVal = -10000 bestCol = -1 bestRow = -1 for x in range(15): for y in range(15): currentVal = self.MiniMax(board, 0, True, x, y) if currentVal > bestVal: bestVal = currentVal bestRow = x bestCol = y #print("the best value: " + str(bestVal)) #print("computer choose the row: " + str(bestRow)) #print("computer choose the column: " + str(bestCol)) return [bestRow, bestCol] # Computer makes a move def computerMove(self, board): move = self.findBestMove(board) x, y = move[0], move[1] # Check if the computer win def isWin(self, board, x, y): return self.computer.checkWin(board, x, y)
""" p6_linear_regression.py Author: Jagrut Gala Date: 28-08-2021 Practical: 6 Objective: Predict the price of a house using Linear Regression. """ import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model import pandas as pd import io from pathlib import Path p= Path(__file__).parent/ "Housing.xlsx" fio= io.open(p, "rb") df = pd.read_excel(fio) print(df) Y = np.array(df['price']).reshape(1, -1) X = np.array(df['tsft']).reshape(1, -1) # print(f"Shapes: {X.shape} {Y.shape}") # # Plot outputs plt.scatter(X, Y) plt.title('Test Data') plt.xlabel('Size') plt.ylabel('Price') plt.xticks(()) plt.yticks(()) # # Create linear regression object regr = linear_model.LinearRegression() # # Train the model using the training sets regr.fit(X, Y) # # Plot outputs plt.plot(X, regr.predict(X), color='red',linewidth=3) plt.show()
#!/usr/bin/env python # coding: utf-8 # In[1]: def hanoi(n, P1, P2, P3): """ Move n discs from pole P1 to pole P3. """ if n == 0: # No more discs to move in this step return global count count += 1 # move n-1 discs from P1 to P2 hanoi(n-1, P1, P3, P2) if P1: # move disc from P1 to P3 P3.append(P1.pop()) print(A, B, C) # move n-1 discs from P2 to P3 hanoi(n-1, P2, P1, P3) # Initialize the poles: all n discs are on pole A. n = 3 A = list(range(n,0,-1)) B, C = [], [] print(A, B, C) count = 0 hanoi(n, A, B, C) print(count)
from random import randint secret = randint(1, 10) guess = 0 count = 0 print('Guess the secret number between 1 and 10') while guess != secret: guess = int(input()) count += 1 if guess == secret: print('You got it! Nice job.') elif abs(guess - secret) == 1: print('You are really close! Try again.') elif guess < secret: print('Too low. Try again.') else: print('Too high. Try again.') print('It took you {0} time(s) to guess.'.format(count))
#print all colors from the list1 not contained in list2 color_list1=set(["white","black","yellow"]) color_list2=set(["green","blue","red"]) print(color_list1.difference(color_list2))
# https://leetcode-cn.com/problems/copy-list-with-random-pointer/ class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random class Solution: def __init__(self): self.visited = {} def copyRandomList(self, head: 'Node') -> 'Node': if not head: return None if head in self.visited.keys(): return self.visited[head] newnode = Node(head.val) self.visited[head] = newnode newnode.next = self.copyRandomList(head.next) newnode.random = self.copyRandomList(head.random) return newnode a = Node(1) b = Node(2) c = Node(3) a.next = b a.random = c b.next = a b.random = None c.next = b c.random = a print(Solution().copyRandomList(a).next.val)
import copy class BinaryTree: # define and init a binary tree def __init__(self, data): self.data = data self.left = None self.right = None # preorder traversal def preorder_traversal(self, tree) -> None: if tree: self.preorder_traversal(tree.left) print(tree.data) self.preorder_traversal(tree.right) # preorder non-recursive def preorder_non_recursive(self, tree) -> None: if tree: data_store = [] ctree = copy.deepcopy(tree) data_store.append(ctree.right) data_store.append(ctree.data) ctree = ctree.left while data_store or ctree: while ctree: data_store.append(ctree.right) data_store.append(ctree.data) ctree = ctree.left print(data_store[-1]) data_store.pop(-1) ctree = data_store[-1] data_store.pop(-1) # To judge a tree if is a full tree def isfulltree(self, tree) -> bool: if not tree: return True elif tree.right and tree.left: return self.isfulltree(tree.left) and self.isfulltree(tree.right) else: return False def depth_of_tree(self, tree) -> int: return 1 + max(self.depth_of_tree(tree.left), self.depth_of_tree(tree.right)) if tree else 0 if __name__ == '__main__': bitree = BinaryTree(1) bitree.left = BinaryTree(2) bitree.right = BinaryTree(3) bitree.left.left = BinaryTree(4) bitree.preorder_traversal(bitree) bitree.preorder_non_recursive(bitree) if bitree.isfulltree(bitree): print("This is a full tree") else: print("This is not a full tree") print("The depth of tree is {}".format(bitree.depth_of_tree(bitree)))
# https://leetcode-cn.com/problems/binary-tree-level-order-traversal/ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrder(self, root: TreeNode) -> list: tree = [[root]] visited = [[root.val]] while tree: stack = [] stack_val = [] for r in tree[0]: if r.left: stack.append(r.left) stack_val.append(r.left.val) if r.right: stack.append(r.right) stack_val.append(r.right.val) tree.pop(0) if stack: tree.append(stack) visited.append(stack_val) return visited a = TreeNode(3) b = TreeNode(9) c = TreeNode(20) d = TreeNode(15) e = TreeNode(7) a.left = b a.right = c c.left = d c.right = e print(Solution().levelOrder(a))
""" input:target = [9,3,5] output:true explanation:start from [1, 1, 1] [1, 1, 1], sum is 3 ,location is 1 [1, 3, 1], sum is 5, location is 2 [1, 3, 5], sum is 9, location is 0 [9, 3, 5] successful """ def ispossible(target: list) -> bool: m = max(target) m_l = target.index(m) s = sum(target) - m if m > s and m != 1: if s == 1: target[m_l] = 1 elif s == 0: if len(target) == 1 and target[0] == 1: return True else: return False else: target[m_l] = m % s return ispossible(target) elif m == 1 and 0 not in target: return True else: return False if __name__ == '__main__': assert ispossible([9, 3, 5]) assert ispossible([8, 5]) assert ispossible([1, 1000000000]) is True assert ispossible([9, 9, 9]) is False assert ispossible([2, 900000002]) is False assert ispossible([2]) is False
""" Giving a set of coins, and their value are c1,c2...cn How to choose coins to achieve that the summary of selected coins is the largest where any location of coins are not adjoining? F(n)=max(cn+F(n-2),F(n-1)) """ """ there are n oranges,you have three choices to eat them: 1. eat 1 2. if n%2 == 0, eat n/2 3. if n%3 == 0, eat 2n/3 return the least day """ def min_days(n: int) -> int: if n < 3: return n else: return min(n % 2 + 1 + min_days(int(n/2)), n % 3 + 1 + min_days(int(n/3))) if __name__ == '__main__': assert min_days(10) == 4 assert min_days(6) == 3 assert min_days(1) == 1 assert min_days(56) == 6
# -*- coding: utf8 -*- """ Using the Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (ie. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18. """ def first_factorial(num): try: num = int(num) except ValueError: return 'Please enter an integer' if num < 1 or num > 18: return 'This number is not between 1 and 18' else: r = range(1, num + 1) return reduce(lambda x, y: x*y, r) print(first_factorial(raw_input()))
# 참과 거짓 boolean # if # True, False # and, or, not # a = True # b = False # # A가 참이고 그리고 B가 참이라면 (A와 B가 둘다 참이여야 된다) # print(a and b) # # A가 참이거나 혹은 B가 참이라면 (A나 B 둘 중에 하나라도 참이면 된다) # print(a or b) # # # # = & == # # a = true a라는 값에 true를 넣어준다는 의미 # # a == ture a 와 true가 동일하냐 라는 뜻 equal의 의미 # c = True # print(a == True) # print(a is True) # if (<= 작거나 같다의 순서가 헛갈리면 입으로 해보면 된다. ) d = int(input("숫자를 입력해주세요.")) if d > 10: print("숫자는 10보다 큽니다.") elif d > 5 and d <= 10: #구간을 나누고 싶을 때, 예외사항으로 조건을 넣고 싶을때 print("숫자는 10보다 작거나 같고, 5보다는 큽니다.") else: # else는 조건을 넣지 못한다. print("숫자는 5보다 작거나 같습니다.")
def calculate(m, i, y): original_mortgage = m for year in range (0, y): print(m) amt = (m/(y - year))/12.0 print('Year '+str(year + 1)+': $%.2f per month' % amt) m -= (amt * 12) m += (original_mortgage * i) original_mortgage *= (1.0 + i) total_mortgage = int(input('Enter the amount of your mortgage: $')) interest = float(input('Enter your interest rate (decimal): ')) years = int(input('Enter number of years of payment: ')) calculate(total_mortgage, interest, years)
def calculate_tax(amt, tax): return amt * (1.0 + tax) amt = float(input('Enter a dollar amount: $')) tax = float(input('Enter the tax amount (decimal): ')) print('Your total is $' + str(calculate_tax(amt, tax)))
""" Generate vocabulary for a tokenized text file. """ import sys import argparse import collections import logging import os def get_vocab(infile, max_vocab_size=None, delimiter=" ", downcase=False, min_frequency=0, to_file=True): # Counter for all tokens in the vocabulary cnt = collections.Counter() with open(infile, 'r') as f: lines = f.read().splitlines() for line in lines: if downcase: line = line.lower() if delimiter == "": tokens = list(line.strip()) else: tokens = line.strip().split(delimiter) tokens = [_ for _ in tokens if len(_) > 0] cnt.update(tokens) # Filter tokens below the frequency threshold if min_frequency > 0: filtered_tokens = [(w, c) for w, c in cnt.most_common() if c > min_frequency] cnt = collections.Counter(dict(filtered_tokens)) logging.info("Found %d unique tokens with frequency > %d.", len(cnt), min_frequency) # Sort tokens by 1. frequency 2. lexically to break ties word_with_counts = cnt.most_common() word_with_counts = sorted( word_with_counts, key=lambda x: (x[1], x[0]), reverse=True) # Take only max-vocab if max_vocab_size is not None: word_with_counts = word_with_counts[:max_vocab_size] path, filename = os.path.split(infile) filename, extension = os.path.splitext(filename) if to_file: with open(os.path.join(path, "vocab" + extension), 'w') as outfile: print("<unk>", file=outfile) print("<s>", file=outfile) print("</s>", file=outfile) for word, count in word_with_counts: print("{}".format(word), file=outfile) return word_with_counts def main(): get_vocab(args.infile, args.max_vocab_size, args.delimiter, args.downcase, args.min_frequency) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generate vocabulary for a tokenized text file.") parser.add_argument( "--min_frequency", dest="min_frequency", type=int, default=0, help="Minimum frequency of a word to be included in the vocabulary.") parser.add_argument( "--max_vocab_size", dest="max_vocab_size", type=int, help="Maximum number of tokens in the vocabulary") parser.add_argument( "--downcase", dest="downcase", type=bool, help="If set to true, downcase all text before processing.", default=False) parser.add_argument( "infile", type=str, help="Input tokenized text file to be processed.") parser.add_argument( "--delimiter", dest="delimiter", type=str, default=" ", help="""Delimiter character for tokenizing. Use \" \" and \"\" for word and char level respectively.""" ) args = parser.parse_args() main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of the PyBGL project. # https://github.com/nokia/pybgl import sys from collections import defaultdict from .algebra import BinaryRelation, BinaryOperator, Less, ClosedPlus from .breadth_first_search import DefaultBreadthFirstSearchVisitor from .graph import Graph, EdgeDescriptor from .graph_traversal import WHITE, GRAY, BLACK from .heap import Comparable, Heap from .property_map import ( ReadPropertyMap, ReadWritePropertyMap, make_assoc_property_map ) class DijkstraVisitor: """ The :py:class:`DijkstraVisitor` class is the base class for any visitor that can be passed to the :py:func:`dijkstra_shortest_path` and :py:func:`dijkstra_shortest_paths` functions. """ def initialize_vertex(self, u: int, g: Graph): """ Method invoked on each vertex in the graph before the start of the algorithm. Args: u (int): The initialized vertex. g (Graph): The considered graph. """ pass def examine_vertex(self, u: int, g: Graph): """ Method invoked on a vertex as it is removed from the priority queue and added to set of vertices to process. At this point, we know that (pred[u], u) is a shortest-paths tree edge so d[u] = d(s, u) = d[pred[u]] + w(pred[u], u). Also, the distances of the examined vertices is monotonically increasing d[u1] <= d[u2] <= d[un]. Args: u (int): The examined vertex. g (Graph): The considered graph. """ pass def examine_edge(self, e: EdgeDescriptor, g: Graph): """ Method invoked on each out-edge of a vertex immediately after it has been added to set of vertices to process. Args: e (EdgeDescriptor): The examined edge. g (Graph): The considered graph. """ pass def discover_vertex(self, u: int, g: Graph): """ Method invoked on vertex ``v`` when an edge ``(u, v)`` is examined and ``v`` is :py:data:`WHITE`. Since a vertex is colored :py:data:`GRAY` when it is discovered, each reacable vertex is discovered exactly once. This is also when the vertex is inserted into the priority queue. Args: u (int): The discovered vertex. g (Graph): The considered graph. """ pass def edge_relaxed(self, e: EdgeDescriptor, g: Graph): """ Method invoked on edge (u, v) if d[u] + w(u,v) < d[v]. The edge (u, v) that participated in the last relaxation for vertex v is an edge in the shortest paths tree. Args: e (EdgeDescriptor): The relaxed edge. g (Graph): The considered graph. """ pass def edge_not_relaxed(self, e: EdgeDescriptor, g: Graph): """ Method invoked if the edge is not relaxed (see above). Args: e (EdgeDescriptor): The not-relaxed edge. g (Graph): The considered graph. """ pass def finish_vertex(self, u: int, g: Graph): """ Method invoked on a vertex after all of its out edges have been examined. Args: u (int): The discovered vertex. g (Graph): The considered graph. """ pass def dijkstra_shortest_paths_initialization( g: Graph, s: int, pmap_vcolor: ReadWritePropertyMap, pmap_vdist: ReadWritePropertyMap, zero: int, infty: int, vis: DijkstraVisitor = None ): if vis is None: vis = DijkstraVisitor() # WHITE: not yet processed, GRAY: under process, BLACK: processed. pmap_vcolor[s] = WHITE for u in g.vertices(): pmap_vdist[u] = zero if u == s else infty vis.initialize_vertex(u, g) # Remark: # Contrary to BGL implementation, we map each vertex with its incident arc*s* # in the shortest path "tree". This allows to manage parallel arcs and equally # cost shortest path. def dijkstra_shortest_paths_iteration( heap: Heap, g: Graph, pmap_eweight: ReadPropertyMap, pmap_vpreds: ReadWritePropertyMap, pmap_vdist: ReadWritePropertyMap, pmap_vcolor: ReadWritePropertyMap, compare: BinaryRelation = Less(), # TODO Ignored, see Heap class. combine: BinaryOperator = ClosedPlus(), vis: DijkstraVisitor = DijkstraVisitor() ): """ Implementation function. See the :py:func:`dijkstra_shortest_paths` function. """ if vis is None: vis = DijkstraVisitor() u = heap.pop() w_su = pmap_vdist[u] vis.examine_vertex(u, g) # Update weight and predecessors of each successor of u for e in g.out_edges(u): vis.examine_edge(e, g) v = g.target(e) w_sv = pmap_vdist[v] w_uv = pmap_eweight[e] w = combine(w_su, w_uv) if compare(w, w_sv): # Traversing u is worth! pmap_vdist[v] = w pmap_vpreds[v] = {e} if pmap_vcolor[v] == WHITE: heap.push(v) # As v is WHITE, v cannot be in the heap. pmap_vcolor[v] = GRAY vis.discover_vertex(v, g) elif pmap_vcolor[v] == GRAY: heap.decrease_key(v) vis.edge_relaxed(e, g) elif w == w_sv: # Hence we discover equally-cost shortest paths preds_v = pmap_vpreds[v] preds_v.add(e) pmap_vpreds[v] = preds_v vis.edge_relaxed(e, g) else: vis.edge_not_relaxed(e, g) pmap_vcolor[u] = BLACK vis.finish_vertex(u, g) return w_su INFINITY = sys.maxsize def dijkstra_shortest_paths( g: Graph, s: int, pmap_eweight: ReadPropertyMap, pmap_vpreds: ReadWritePropertyMap, pmap_vdist: ReadWritePropertyMap, pmap_vcolor: ReadWritePropertyMap = None, compare: BinaryRelation = None, # TODO Ignored, see Heap class. combine: BinaryOperator = ClosedPlus(), zero: int = 0, infty: int = INFINITY, vis: DijkstraVisitor = None ): """ Computes the shortest path in a graph from a given source node and according to the `(Distance, compare, combine)` semi-ring using the `Dijkstra algorithm <https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm>`__. Args: g (Graph): The input graph. s (int): The vertex descriptor of the source node. pmap_eweight (ReadPropertyMap): A ``ReadPropertyMap{EdgeDescriptor: Distance}`` which map each edge with its weight. pmap_vpreds (ReadWritePropertyMap): A ``ReadWritePropertyMap{VertexDescriptor: EdgeDescriptor}`` which will map each vertex with its incident arcs in the shortest path Directed Acyclic Graph. Each element must be initially mapped with ``set()``. pmap_vdist (ReadWritePropertyMap): A ``ReadWritePropertyMap{VertexDescriptor: Distance}`` which will map each vertex with the weight of its shortest path(s) from ``s``. Each element must be initialized to `zero`. pmap_vcolor (ReadWritePropertyMap): A ``ReadWritePropertyMap{VertexDescriptor: Distance}`` which will map each vertex with the weight of its color. Each element must be initialized to `WHITE`. compare (BinaryRelation): The binary relation that compares two weight. This corresponds to the oplus operator in the semi-ring (e.g, min). combine (BinaryOperator): The binary relation that combines two weight. This corresponds to the otimes operator in the semi-ring (e.g, +). zero (float): The null distance (e.g., ``0``). infty (float): The infinite distance` (e.g., ``INFINITY``). vis (DijkstraVisitor): An optional visitor. Example: >>> g = Graph(2) >>> e, _ = add_edge(0, 1, g) >>> map_eweight[e] = 10 >>> map_vpreds = defaultdict(set) >>> map_vdist = dict() >>> dijkstra_shortest_paths( ... g, u, ... make_assoc_property_map(map_eweight), ... make_assoc_property_map(map_vpreds), ... make_assoc_property_map(map_vdist) ... ) """ if vis is None: vis = DijkstraVisitor() if pmap_vcolor is None: color = defaultdict(int) pmap_vcolor = make_assoc_property_map(color) # Initialization dijkstra_shortest_paths_initialization( g, s, pmap_vcolor, pmap_vdist, zero, infty, vis ) # Iteration if not compare: compare = Less() heap = Heap([s], to_comparable = lambda u: pmap_vdist[u]) else: heap = Heap( [s], to_comparable = lambda u: Comparable(pmap_vdist[u], compare) ) while heap: dijkstra_shortest_paths_iteration( heap, g, pmap_eweight, pmap_vpreds, pmap_vdist, pmap_vcolor, compare, combine, vis ) #-------------------------------------------------------------------- # Utilities to get the Shortest-Paths-DAG or an arbitary shortest # path towards an arbitrary node t. #-------------------------------------------------------------------- # TODO rename to make_shortest_paths_dag def make_dag( g: Graph, s: int, t: int, pmap_vpreds: ReadPropertyMap, single_path: bool = False ) -> set: """ Extracts the set of arcs related to shortest paths from ``s`` to ``t`` in a graph ``g`` given the predecessors map computed using :py:func:`dijkstra_shortest_paths` from ``s``. The corresponding subgraph is a DAG where the source is ``s`` and the sink is ``t``. Args: g (Graph): The input graph. s (int): The source vertex descriptor. t (int): The target vertex descriptor. pmap_vpreds (ReadPropertyMap): The ``ReadPropertyMap{int: set(int)}`` mapping each vertex with its set of (direct) predecessors. single_path (bool): Pass ``True`` to extract an arbitrary single shortest path, ``False`` to extrac of all them. Note that if ``single_path is True`` and if multiple paths exist from ``s`` to ``t``, :py:func:`make_dag` extracts an arbitrary shortest path instead of all of them. Returns: The corresponding set of arcs. """ kept_edges = set() n_prev = -1 n = 0 to_process = {t} done = set() while to_process: es = {e for u in to_process if pmap_vpreds[u] for e in pmap_vpreds[u]} if single_path and es: es = {es.pop()} kept_edges |= es predecessors = {g.source(e) for e in es if e not in done} done |= to_process to_process = predecessors - done return kept_edges # TODO rename to make_shortest_path def make_path( g: Graph, s: int, t: int, pmap_vpreds: ReadPropertyMap ) -> list: """ Extracts the path from ``s`` to ``t`` in a graph ``g`` given the predecessors map computed using :py:func`dijkstra_shortest_paths` from ``s``. Args: g (Graph): The input graph. s (int): The target's vertex descriptor. t (int): The target's vertex descriptor. pmap_vpreds (ReadPropertyMap): A ``ReadPropertyMap{int: set(int)}`` mapping each vertex with its set of (direct) predecessors. Returns: A list of consecutive arcs forming a shortest path from ``s`` of ``t``. If several shortest paths exist from ``s`` to ``t``, this function returns an arbitrary shortest path. """ arcs = make_dag(g, s, t, pmap_vpreds, single_path=True) u = t path = list() while u != s: e = list(pmap_vpreds[u])[0] path.insert(0, e) u = g.source(e) return path #-------------------------------------------------------------------- # Optimization to stop Dijkstra iteration once distance from s to t #-------------------------------------------------------------------- from .aggregated_visitor import AggregatedVisitor class DijkstraStopException(Exception): pass class DijkstraTowardsVisitor(DijkstraVisitor): """ The :py:class:`DijkstraTowardsVisitor` may be passed to the :py:func:`dijkstra_shortest_paths` function to abort computation once the cost of the shortest path to ``t`` is definitely known. Important notes: - stopping when discovering ``t`` (the first time) does not guarantee that we have find the shortest path towards ``t``. We must wait the :py:meth:`DijkstraVisitor.examine_vertex` method to be triggered. - stopping when discovering a vertex ``u`` farther than ``t`` from ``s`` always occurs after finishing vertex ``t``. As a sequel, we must wait that ``t`` is examined to guarantee that a a shortest path to t has been explored. """ def __init__(self, t: int): self.t = t def examine_vertex(self, u: int, g: Graph): if u == self.t: raise DijkstraStopException(self.t) def dijkstra_shortest_path( g: Graph, s: int, t: int, pmap_eweight: ReadPropertyMap, pmap_vpreds: ReadWritePropertyMap, pmap_vdist: ReadWritePropertyMap, pmap_vcolor: ReadWritePropertyMap = None, compare: BinaryRelation = Less(), # TODO Ignored, see Heap class. combine: BinaryOperator = ClosedPlus(), zero: int = 0, infty: int = sys.maxsize, vis: DijkstraVisitor = None ) -> list: """ Helper to find a single shortest path from s to t. Args: g (Graph): The input graph. s (int): The vertex descriptor of the source node. t (int): The target descriptor of the source node. pmap_eweight (ReadPropertyMap): A ``ReadPropertyMap{EdgeDescriptor: Distance}`` which map each edge with its weight. pmap_vpreds (ReadWritePropertyMap): A ``ReadWritePropertyMap{VertexDescriptor: EdgeDescriptor}`` which will map each vertex with its incident arcs in the shortest path Directed Acyclic Graph. Each element must be initially mapped with ``set()``. pmap_vdist (ReadWritePropertyMap): A ``ReadWritePropertyMap{VertexDescriptor: Distance}`` which will map each vertex with the weight of its shortest path(s) from ``s``. Each element must be initialized to `zero`. pmap_vcolor (ReadWritePropertyMap): A ``ReadWritePropertyMap{VertexDescriptor: Distance}`` which will map each vertex with the weight of its color. Each element must be initialized to `WHITE`. compare (BinaryRelation): The binary relation that compares two weight. This corresponds to the oplus operator in the semi-ring (e.g, min). combine (BinaryOperator): The binary relation that combines two weight. This corresponds to the otimes operator in the semi-ring (e.g, +). zero (float): The null distance (e.g., ``0``). infty (float): The infinite distance` (e.g., ``INFINITY``). vis (DijkstraVisitor): An optional visitor. """ vis_towards = DijkstraTowardsVisitor(t) vis = AggregatedVisitor([vis, vis_towards]) if vis else vis_towards try: dijkstra_shortest_paths( g, s, pmap_eweight, pmap_vpreds, pmap_vdist, pmap_vcolor, compare, combine, zero, infty, vis=vis ) except DijkstraStopException: return make_path(g, s, t, pmap_vpreds) return None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of the pybgl project. # https://github.com/nokia/pybgl import heapq class Comparable(object): """ Wrapper used to define a custom pre-order for a given object. This class is inspired from ``functools.cmp_to_key`` and `this discussion <https://stackoverflow.com/questions/8875706/heapq-with-custom-compare-predicate>`__. The objects to be sorted are wrapped in an instance that implements the ``<`` operator called by the sorting function. """ def __init__(self, obj: object, preorder: callable = None): """ Constructor. Example: >>> x = Comparable(5, lambda a, b: a >= b) Args: obj: An `Element` instance. preorder: A `callable` acting as a preorder. """ self.obj = obj assert preorder self.preorder = preorder def __lt__(self, other: object) -> bool: """ Implements the `<` comparison according to the chosen preorder. Args: other (object): The object compared to ``self``. Returns: ``True`` if ``self < other`` according to the chosen preorder. """ return not self.preorder(other.obj, self.obj) def __le__(self, other: object) -> bool: """ Implements the `<=` comparison according to the chosen preorder. Args: other (object): The object compared to ``self``. Returns: ``True`` if ``self <= other`` according to the chosen preorder. """ return self.preorder(self.obj, other.obj) def __eq__(self, other: object) -> bool: """ Implements the `==` comparison according to the chosen preorder. Args: other (object): The object compared to ``self``. Returns: ``True`` if ``self == other`` according to the chosen preorder. """ return ( self.preorder(self.obj, other.obj) and self.preorder(other.obj, self.obj) ) def __ne__(self, other: object) -> bool: """ Implements the `!=` comparison according to the chosen preorder. Args: other (object): The object compared to ``self``. Returns: ``True`` if ``self != other`` according to the chosen preorder. """ return not self.__eq__(other) def __gt__(self, other: object) -> bool: """ Implements the `>` comparison according to the chosen preorder. Args: other (object): The object compared to ``self``. Returns: ``True`` if ``self > other`` according to the chosen preorder. """ return not self.preorder(self.obj, other.obj) def __ge__(self, other: object) -> bool: """ Implements the `>=` comparison according to the chosen preorder. Args: other (object): The object compared to ``self``. Returns: ``True`` if ``self >= other`` according to the chosen preorder. """ return self.preorder(other.obj, self.obj) def __str__(self) -> str: """ Exports this :py:class:`Comparable` to its string representation. Returns: The corresponding string. """ return "Comparable(%s)" % self.obj def __repr__(self) -> str: """ Exports this :py:class:`Comparable` to its string representation. Returns: The corresponding string. """ return "Comparable(%r)" % self.obj def compare_to_key(preorder: callable): """ Convert a preorder to a key callback (used e.g. by sort functions in python). Example: >>> key = compare_to_key(lambda a, b: a >= b) Args: preorder: A `callable(Element, Element)` that is preorder over the space of Elements. """ return lambda x: Comparable(x, preorder) class Heap: """ The :py:class:`Heap` class implements a heap using an arbitrary preorder. It answers the limitation of :py:func:``heappop`` and :py:func:`heappush` which assume that the heap is ordered according to ``<=``. """ def __init__(self, elements: iter = None, to_comparable: callable = None): """ Constructor. Example: >>> heap = Heap( ... [4, 2, 2, 1, 3], ... to_comparable=lambda x: Comparable(x, lambda a, b: a >= b) ... ) >>> heap Heap([4, 3, 2, 2, 1]) Args: elements (iter): The elements used to initialize this `Heap`. to_comparable (callable): A `callable` used to define the preorder used to sort elements pushed in this `Heap`. """ self.to_comparable = ( to_comparable if to_comparable is not None else (lambda x: x) ) self.index = 0 if elements: # We could use this heapsort as defined in this link, but sorted() is stable # https://docs.python.org/3/library/heapq.html self._data = list( (self.to_comparable(element), i, element) for (i, element) in enumerate(elements) ) # Note that self._data is not sorted. # https://stackoverflow.com/questions/1046683/does-pythons-heapify-not-play-well-with-list-comprehension-and-slicing heapq.heapify(self._data) # Or self._data = sorted(self._data) self.index = len(self._data) # Tie-break on insertion order. else: self._data = list() def push(self, element: object): """ Pushes an element to this :py:class:`Heap` instance. Args: element (object): The object to be pushed. """ heapq.heappush(self._data, (self.to_comparable(element), self.index, element)) self.index += 1 def decrease_key(self, element: object): for (i, (_, index, x)) in enumerate(self._data): if element == x: self._data[i] = (self.to_comparable(element), index, element) heapq.heapify(self._data) def pop(self) -> tuple: """ Pops an element to this :py:class:`Heap` instance. Returns: The popped element. """ return heapq.heappop(self._data)[2] def __iter__(self) -> iter: """ Retrieves an iterator over the stored objects. Returns: An iterator over the stored objects. """ return (x[2] for x in heapq.nsmallest(len(self), self._data)) def __str__(self) -> str: """ Converts this :py:class:`Heap` instance to its string representation. Returns: The corresponding string representation. """ return self.__repr__() def __repr__(self) -> str: """ Converts this :py:class:`Heap` instance to its string representation. Returns: The corresponding string representation. """ return f"Heap({(list(self))})" def __bool__(self) -> bool: """ Implements the :py:func:`bool` cast operation, typically used to check whether this :py:class:`Heap` instance is empty or not. Returns: ``True`` if this :py:class:`Heap` is not empty, ``False`` otherwise. """ return bool(self._data) def __len__(self) -> int: """ Implements the :py:func:`len` operation, used to count the number of elements stored in this :py:class:`Heap` instance. Returns: The number of stored elements. """ return len(self._data)
#!/usr/bin/env python3 """ Basic Python generator examples. The yield statement halts the function and saves it state. The function continues from its halted state on successive calls. """ def all_even(max): n = 0 while n < max: yield n n += 2 def fib_generator(nth): n = 0 p = 1 q = 1 while n < nth: yield p old_q = q q = p + q p = old_q n += 1 if __name__ == "__main__": print("All even") out = "" for n in all_even(10): out += str(n) + ", " print(out[0:len(out)-2]) print("Fib generator") out = "" for n in fib_generator(12): out += str(n) + ", " print(out[0:len(out)-2])
#String Compression def string_compression(s): if len(s) <= 1: return s compressed_string = "" count = 1 for i in range(len(s)-1): if s[i] == s[i+1]: count += 1 else: compressed_string = compressed_string + s[i]+ str(count) count = 1 i += 1 compressed_string = compressed_string + s[-1] + str(count) if len(s) < len(compressed_string): return s else: return compressed_string
#Given a circular linked list, return node at the beginning of the loop class Node: def __init__(self, value): self.value = value self.next = None def loop_detection(node): fast = node slow = node while fast and fast.next and slow: slow = slow.next fast = fast.next.next if slow == fast: #if there is a loop, this means that slow and fast will eventually intersect break if slow == None and fast == None: #if there isn't a loop, both slow and fast will be None return None slow = node #set slow back to the start of the node while slow != fast: slow = slow.next fast = fast.next return slow.value # A > B > C > D > E > C a = Node('A') b = Node('B') c = Node('C') d = Node('D') e = Node('E') a.next = b b.next = c c.next = d d.next = e e.next = c loop_detection(a) #output: C
#Import the os module & #Module for reading CSV files import os import csv #assign variables total_votes = 0 candidates = [] winning_count = 0 election_winner = "" #Dictionary for candidate and votes each candidate_votes = {} #Set path for the CSV file csvpath = os.path.join('.', 'PyPoll', 'Resources', 'election_data.csv') #Open the CSV file and Read it with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #skips over the headers header = next(csvreader) for row in csvreader: total_votes += 1 candidate_name = row[2] if candidate_name not in candidates: candidates.append(candidate_name) candidate_votes[candidate_name] = 0 candidate_votes[candidate_name] += 1 print("Election Results") print("------------------------") print("Total Votes: ", total_votes) print("------------------------") for candidate in candidate_votes: votes = candidate_votes.get(candidate) vote_percent = float(votes)/(total_votes)*100 if (votes > winning_count): winning_count = votes election_winner = candidate voter_output = f"{candidate}: {vote_percent:.3f}% ({votes})\n" print(voter_output, end="") print("-------------------------------") print("Winner: ", election_winner) #Export a text file with the results csvpath_out = os.path.join('.','PyPoll','analysis','Analysis.txt') with open(csvpath_out, 'w') as Analysis: Analysis.write("Election Results") Analysis.write("\n") Analysis.write("------------------------") Analysis.write("\n") Analysis.write(f"Total Votes: {str(total_votes)}") Analysis.write("\n") Analysis.write("------------------------") Analysis.write("\n") Analysis.write(f"{voter_output}") Analysis.write("\n") Analysis.write("------------------------") Analysis.write("\n") Analysis.write(f"Winner: {election_winner}")
from datetime import datetime def fun(): print("done") print("begin time:",datetime.now()) fun() print("end time:",datetime.now()) def callfun(func): print("begin time:", datetime.now()) func print("end time:", datetime.now()) def test(): print("test") callfun(test) ########################排序函数sorted############################ #Python内置的sorted()函数就可以对list进行排序: age = [1, 3, 5, 6, 7, 2, 0, -2, 4] print(sorted(age)) print(sorted(age, key = abs)) # 求绝对值后再排序 def below(n): return n * n print(sorted(age, key = below)) # 求平方后再排序 print(sorted(age, key = lambda n:n * n )) age = {'0': 1, '1': 3, '2': 5, '3': 6, '4': 7, '5': 2, '6': 0, '7': -2, '8': 4} print(age) print(age.items()) print(sorted(age.items())) print(sorted(age.items(), reverse = True)) print(sorted(age.items(), key = lambda x:x[1])) #######################匿名函数lambda############################ #通俗的讲就是没有名字的函数,有个好处,因为函数没有名字,不必担心函数名冲突 def is_odd(n): return n % 2 == 1 L = list(filter(is_odd, range(1, 20))) print(L) L = list(filter(lambda n:n % 2 == 1, range(1, 20))) print(L) #######################修饰器Decorator########################### #无参数函数装饰器 import functools def log(func): def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2015-3-25') print(now()) print(now.__name__) def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2015-3-25') print(now()) print(now.__name__) #有参数函数装饰器 import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator @log('start') def now(): print('2015-3-25') print(now()) print(now.__name__) import time, functools def metric(func): if callable(func): @functools.wraps(func) def wrapper(*args, **kw): start = time.time() print("%s start" % (func.__name__)) rts = func(*args, **kw) print("%s end" % (func.__name__)) end = time.time() print('%s executed in %.4f ms' % (func.__name__, end - start)) return rts return wrapper else: def decorator(fn): @functools.wraps(fn) def wrapper(*args, **kw): start = time.time() print("%s start" % (fn.__name__)) rts = fn(*args, **kw) print("%s end" % (fn.__name__)) end = time.time() print('%s %s executed in %.4f ms' % (func, fn.__name__, end - start)) return rts return wrapper return decorator # 测试 @metric def fast(x, y): time.sleep(0.0012) return x + y; @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z; @metric('start') def test(x, y, z): time.sleep(0.3456) return x * y * z; f = fast(11, 22) s = slow(11, 22, 33) t = test(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!') elif t != 7986: print('测试失败!') #######################练习########################### #一个字符串中字母出现的次数,出现前三的字幕 str = "dsffsd lksjdflkjsdalje[p weolds sdjfsdkljfj[peow-0w0w9eurerhfgkmn;xalsd;aoierp9483-730lkdsla" L = {} for char in str: if char == ' ': continue L[char] = L.get(char,0) + 1 print(L) print(sorted(L.items(), key=lambda x:x[1], reverse=True)[:3])
""" On the whiteboard, please write a version of the unix utility "wc" in the language of your choice. This is a rudimentary programming question, but it tests many things: Working under stress. It requires the candidate to actually get up to the whiteboard and write some code under observation. This tests how well they work under pressure, and how well they can "think on their feet", literally. :-) I make sure to not speak at all while they're writing code, unless they ask me a question. It's best to let them sweat it out in total silence. Basic programming abilities. Any competent programmer should be able to bang this out with very little difficulty. if they can't do this, then you have to wonder how well they know these languages that they say they know. If they try to write pseudo-code, you can press them to actually write real syntax. However, if they forget the exact name of a specific java method call in a specific class, that's no big deal. Understanding requirements and following instructions. See how well they can reverse-engineer the feature set of wc. If they aren't familiar with wc, then you can describe it to them. See how easily they pick up on your instructions. Once they've written it one way, I usually ask them how they can implement it a different way. This forces them to "think outside the box" and be creative. Another variation: once they've solved it, you can add a requirement that the program should report the number of distinct words in the file. In addition to introducing a different data structure, this will also test their ability to refactor their code, even if it is just a little. WC Description: wc -l print line count wc -c print character count wc -w print word count f(text, l=False, w=False, c=False) """ import sys def word_count(text, l=False, w=False, c=False): l, w, c = 0, 0, 0 for line in text.splitlines(): line = line.strip() l += 1 words = line.split() w += len(words) for word in words: c += len([ char for char in word if bool(char.strip()) ]) return l, w, c def word_count(text, l=False, w=False, c=False): l, w, c = 0, 0, 0 unique = set() for line in text.splitlines(): line = line.strip() l += 1 words = line.split() w += len(words) for word in words: word = word.strip() c += len([char for char in word if bool(char.strip())]) unique.add(word) return l, w, c, len(unique) def wc_cli(): assert len(sys.argv) > 1 flags = sys.argv[1] assert flags.startswith('-') lc = 'l' in flags wc = 'w' in flags cc = 'c' in flags text = sys.stdin.read() l, w, c, u = word_count(text, lc, wc, cc) if lc: print('Lines :', l) if wc: print('Words :', w) if cc: print('Chars :', c) print('Unique :', u) if __name__ == '__main__': l, w, c, u = word_count('hello world!\nhow are you?', True, True, True) assert l == 2 assert w == 5 assert c == 21 assert u == 5 wc_cli()
""" Find the height of a binary tree. Recusion f(b, c) Another solution: store branch height in each node :) """ # Expected height: 3 tree = { 'children' : [ { 'children' : [] }, { 'children' : [ { 'children' : [] }, { 'children' : [] } ] }, { 'children': [] } ] } def btree_height(branch, count=1): if branch['children']: return max( btree_height(b, count + 1) for b in branch['children'] ) else: return count if __name__ == '__main__': print(f'BTree height: {btree_height(tree)}')
""" This problem was asked by Google. Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical. For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8. In this example, assume nodes with the same value are the exact same node objects. Do this in O(M + N) time (where M and N are the lengths of the lists) and constant space. """ def intersect(m, n): m = set(m) # O(n) for i in n: # O(n) if i in m: return i r = intersect( [3, 7, 8, 10], [99, 1, 8, 10] ) print(r)
""" This problem was asked by Palantir. Write a program that checks whether an integer is a palindrome. For example, 121 is a palindrome, as well as 888. 678 is not a palindrome. Do not convert the integer into a string. """ # This solution is O(N * 1.5) def get_digits(num): digits = [] while num >= 10: digits.append(num - (num // 10) * 10) num //= 10 return digits + [num] def is_palindrome(num): digits = get_digits(num) for i in range(len(digits) // 2): front = digits[i] back = digits[len(digits) - i - 1] if front != back: return False return True if __name__ == '__main__': assert is_palindrome(1001) # assert is_palindrome(101) # assert not is_palindrome(1012) # assert is_palindrome(45654)
""" This problem was asked by Microsoft. Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. """ def findall(string, key): found = [] start = 0 end = len(key) - 1 while end != len(string): sub = string[start:end + 1] if sub == key: found.append(start) start += 1; end += 1 return found def sent(the_words, string): words = dict() for word in the_words: if word in string: indexes = findall(string, word) for i in indexes: words[word] = (i, i + len(word)) # start, end new = words.copy() for word in words: for other in words: if word != other: if words[word][0] >= words[other][0] and words[word][1] <= words[other][1]: del new[word] return [i for i in sorted(new, key=lambda x: new[x][0])] print(sent('bed bath bedbath and beyond'.split(), 'bedbathandbeyond')) print(sent('quick brown the fox'.split(), 'thequickbrownfox')) print(sent('thing throne one you and should'.split(), 'onethingyoushouldthroneandone'))
print('Binary translator') sentence = input('input a sentence to be translated in : ') sentence_ascii, sentence_char,rtn = [], [],'' for i in range(len(sentence)): sentence_char.append(sentence[i]) sentence_ascii.append(ord(sentence[i])) def to_binary(n): binary,binary_val = [0,0,0,0,0,0,0,0],[128,64,32,16,8,4,2,1] for i in range(len(binary)): if (binary_val[i] <= n): binary[i] = 1 n = n - binary_val[i] if n == 0: break return ' '.join(str(x) for x in binary) for i in sentence_ascii: if i == 32: rtn += ' ' else: rtn += to_binary(i) + " " print('The binary value is -> ' , rtn)
# def fact(n): # if n==0: # return (1) # if n==1: # return (1) # else: # return n*fact(n-1) # # # factorial_required=[int(input()) for i in range(int(input()))] # print(*list(map(lambda x:fact(x),factorial_required)),sep='\n') import math T = int(input()) for i in range(0,T,1): N = int(input()) print (math.factorial(N))
A=[1,2,3] string="" for i in range(len(A)): string=string+str(A[i]) string=str(int(string)+1) answer=[int(i) for i in string] print(answer)
""" String 이 주어지면, 중복된 char 가 없는 가장 긴 서브스트링 (substring)의 길이를 찾으시오. 예제) Input: “aabcbcbc” Output: 3 // “abc” Input: “aaaaaaaa” Output: 1 // “a” Input: “abbbcedd” Output: 4 // “bced” """ def search_word(txt): result = 0 start = 0 char_dict = {} for i, c in enumerate(txt): if c in char_dict: start = max(char_dict.get(c), start) result = max(result, i - start + 1) char_dict[c] = i + 1 return result result_length = search_word('aaaaaaaa') print(f'{result_length}')
a=[1,2,3,4] b=[2,3,4] # c=(i+j for i in a for j in b) c=[i+j for i in a for j in b] print(c) #print(next(c)) #print(next(c)) #print(next(c))
#---------------------------------Importing Libraries import tkinter from tkinter import Button, StringVar from tkinter import Tk from tkinter import PhotoImage import socket import threading from tkinter import Listbox from tkinter import Entry from tkinter import Scrollbar #------------------A function to calculate power of a number def fast_exp(b,e,m): if e==0: return 1 half=int(e/2) ret=fast_exp(b,half,m) if e%2==0: return (ret*ret)%m else: return (((ret*ret)%m)*b)%m #--------Extended Euclid's algorithm for calculating multiplicative inverse def Extended_Euclid(x,y): if(y==0): return (x,0,1) g,x1,y1=Extended_Euclid(y,x%y) return (g,y1-int(x/y)*x1,x1) #------Multiplicative inverse calculation def Multiplicative_inverse(x,y): g,x1,y1=Extended_Euclid(y,x%y) if(g!=1): print("No multiplicative inverse exists for this pair") return "does not exist" else: return (x1%y) #--------letter to digit coversion def letter_to_digit(text): l=[] i=0 while i<len(text): l.append(ord(text[i])-ord(" ")) i+=1 return l #----------digit to letter conversion def digit_to_letter(l): t="" for i in l: t+=chr(i+ord(" ")) return t #-----------encrypting each of the characters using letter to digit technique #---------then converting the digits usingRSA then decrypting back using digit to letter def encrypt(msg, public_key): n,e = public_key blocks = letter_to_digit(msg) cipher = [] for i in blocks: c = pow(i,e,n) cipher.append(c) return digit_to_letter(cipher) def decrypt(cipher, private_key): n,d = private_key msg = [] blocks=letter_to_digit(cipher) for i in blocks: t = pow(i,d,n) msg.append(t) return digit_to_letter(msg) #--------------------------------Sending message function def sendm(): global count global port global sock global public_key global Receiver_IP print("send",count,lstbox.size()) #--------------------------Connection establishment to the socket happens only first time #------------------After that this socket is used for further sending of messages if count==0: #---------------first time connection establishment #----------------------If the other user is not listning, cannot establish connections------------ #-----------------If the other user stopped the connection, means this user's connection ###--- will also be stopped, so this user cannot establish the connection newly until the ###--- other user comes back try: sock.connect((Receiver_IP,port)) except : lstbox.insert(lstbox.size(),"Reciever may not be online") lstbox.insert(lstbox.size(),"Please click the + Button") return msg=msgbox.get() lstbox.insert(lstbox.size(),"You :: "+msg) #-------------this send does not require a try because this will only happen when the connection ###--is established, if the connection gets closed by the other side then definately this ###--connection will be stopped and all will be initialized to starting state. msg=encrypt(msg,public_key) #----------------for threading if the receiver thread is pre empted before reinitializing the ###-- count to zero this may happen try: sock.send(bytes(msg,"utf-8")) except: lstbox.insert(lstbox.size(),"It seems like other user has stopped the connection") count=1 else: msg=msgbox.get() lstbox.insert(lstbox.size(),"You :: "+msg) msg=encrypt(msg,public_key) try: sock.send(bytes(msg,"utf-8")) except: lstbox.insert(lstbox.size(),"It seems like other user has stopped the connection") #----------------------A function to send message thread def threadsend(): #------Creating a new thread for sending the message every time t=threading.Thread(target=sendm) t.start() #-------------------A function to receive message def receivem(): global count global ls global lport global conn global flag global sock global private_key flag=1 print(type(ls)) ls.bind((socket.gethostbyname(socket.gethostname()),lport)) ls.listen(100) print("user_2 is listning") #-------------Other user is not present in the system #-------After connection establishment and before getting the first message it stands here #---Even if user has started sending until it receives a msg it stays here try: conn,addr=ls.accept() except: print("check") return print("connection established") while True: print("receive",count,lstbox.size()) try: #--------------------Aborted by the other user data = conn.recv(64) if not data: lstbox.insert(lstbox.size(),"Other user has stopped the connection") conn.close() ls.close() sock.close() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM) count=0 flag=0 break #-----closing all connections from this side #-----Redefining the sockets because the other user may come back #-----Already closed sockets cannot be reused #-----If we do not close the old sockets and redefine the variable, ###--we cannot reconnect the socket with new address. #----------Also for new connection the two flags should be reinitialized to 0 except : #----------------------Aborted by this user print("connection stopped") conn.close() ls.close() sock.close() break #-----closing all connections from this side #-----Redefining the sockets because the other user may come back #-----Already closed sockets cannot be reused #-----If we do not close the old sockets and redefine the variable, ###--we cannot reconnect the socket with new address. #----------Also for new connection the two flags should be reinitialized to 0 recvd_msg=str(data.decode("utf-8")) recvd_msg=decrypt(recvd_msg,private_key) lstbox.insert(lstbox.size(),"client ::"+recvd_msg) #----------------------function to create a thread to receive msgs-------------- def threadreceive(): global flag global count #------Already receive Thread started or not if flag==1: lstbox.insert(lstbox.size(),"already connected") return t=threading.Thread(target=receivem) t.start() print("statement") #---------------------------function occurs during closing the chatbox app------- def on_closing(): print("user_2 closing") global ls global sock global conn ls.close() conn.close() sock.close() #-----IMP----If only sending is done the receiver is still at conn,addr=ls.accept, ###--so to get to the esceotion ls must be closed from here also sock is not closed anywhere ###-- It should be closed from here root.destroy() #-----------Close the listening socket, once this is closed the recv function will throw exception #-------the exception will be in receivem---------------- #-----------all threads executed and sockets reassigned along with chat app closed-------- sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) ls=socket.socket(socket.AF_INET,socket.SOCK_STREAM) conn=socket.socket(socket.AF_INET,socket.SOCK_STREAM) lport=12345 ##sender port flag=0 ##flag for the receiver count=0 ## flag for sender Receiver_IP="" print("Please Enter REceiver_IP") Receiver_IP=input() port="" print("Please Enter Receiver's port") port=int(input()) p = 19 q = 5 e = 5 n = p * q phi = (p-1)*(q-1) d=Multiplicative_inverse(e,phi) public_key = (n,e) private_key = (n,d) root=Tk() root.geometry("300x400") root.resizable(False, False) msg=StringVar() msgbox=Entry(root,textvariable=msg,font=('calibre',10,'normal'),border=2,width=35) msgbox.place(x=10,y=350) scrollbar = Scrollbar(root, orient="vertical") lstbox=Listbox(root,height=20,width=45,yscrollcommand=scrollbar.set) scrollbar.config(command=lstbox.yview) lstbox.place(x=10,y=30) scrollbar.pack( side = "right", fill ="y" ) start_img=PhotoImage(file="new_start_b.png") startb=Button(root,image=start_img,command=threadreceive,borderwidth=0,height=30,width=30) startb.place(x=120,y=0) send_img=PhotoImage(file="send_resized.png") sendb=Button(root,image=send_img,command=threadsend,borderwidth=0,height=30,width=30) sendb.place(x=250,y=345) root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop()
import re # To Read Tweets directly from Program: tweet = """Most employees fulfilled with used hardware based on device turns four years old. Some job categories (hardware or software developer, technical sales, etc.) are eligible at three years. Recognizing that employee job roles or device request qualities and inventory allows , the CIO considers requests for early refresh. When submitting, provide a detailed justification as to requirements can change at any time why a new device is needed. Devices reviews an early refresh request the request if the, Devices honors the request. Early refresh requests are eligible for refresh when their primary computing may be funding levels and available""" # To Read Tweets from File: # with open("tweets.txt", "r") as f: # tweet = f.read() tot_no_of_words = len(tweet.split()) half_of_words = tot_no_of_words // 2 list_of_abusive_words = ["device", "refresh"] abusive_words = 0 for abusive_word in list_of_abusive_words: abusive_words += len(re.findall(abusive_word, tweet))*2 if abusive_words == 0: print("Pure Content.") elif tot_no_of_words > abusive_words: print("Less Abusive.") else: print("More Abusive.")
import time import timeit #40.a i=12 while i>0: localtime = time.asctime(time.localtime(time.time())) print ("Local current time :", localtime) time.sleep(5) i=i-1 #40.b code = """list1=['Surat','Vyara','Vadodara','Ahmedabad','Div'] list2=['Pune','Chennai','Mumbai','Kolkata','Delhi'] list3=['Skikkm','Kalingpong','Gangtok','Bagdogra','Katra'] print ("List1: ",list1) for each in list1: print("City name : ",each," Length : ",len(each)) print ("List2: ",list2) for each in list2: print("City name : ",each," Length : ",len(each)) print ("List3: ",list3) for each in list3: print("City name : ",each," Length : ",len(each)) """ execution_time = timeit.timeit(code, number=1) print("Ececution time for the given code: ",execution_time)
Str = "this is string example....wow!!!"; Str = Str.encode('base64','strict'); print ("Encoded String: " + Str) print ("Decoded String: " + Str.decode('base64','strict'))
def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l)//2; # Check if x is present at mid if int(arr[mid]) == x: return mid # If x is greater, ignore left half elif int(arr[mid]) < x: l = mid + 1 # If x is smaller, ignore right half else: r = mid - 1 # If we reach here, then the element was not present return -1 str1=input("Enter the numbers") list1=list(str1) list1.sort() print ("The sorted order list1 of elements is",list1) searchElement=int(input("Enter the element tosearch from the above list")) res= binarySearch(list1 , 0 , len(list1)-1 , searchElement) if res!=-1: print("Success") else: print("Unsuccessful search")
import os import csv election_csv_path = os.path.join("/Users/himadevulapalli/Documents/Tech/GTATL201908DATA3/02 - Homework/03-Python/Instructions/PyPoll/Resources", "election_data.csv") #file_to_output = os.path.join("./election_output.txt") # you might declare election results here and then assignt them within the open() method just below #open and read the csv file with open(election_csv_path, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #Output file f=open("Election_results.txt", "w") #skip the Header csv_header = next(csvfile) #print(f"Header: {csv_header}") #Read CSV into a List election_list = list(csvreader) #Reads the total Length of the List totalVotes = len(election_list) print("Election Results") print("-----------------------------") print("Total Votes: {}".format(totalVotes)) print("-----------------------------") #write to output file print("Election Results", file=f) print("-----------------------------", file=f) print("Total Votes: {}".format(totalVotes), file=f) print("-----------------------------", file=f) candidate_dict={} #read each row for row in election_list: candidate_key = row[2] if candidate_key in candidate_dict.keys(): #increment the count candidate_dict[row[2]]+=1 else: candidate_dict[row[2]] = 1 #print("Candidates : {}".format(candidate_dict)) percent_candidate_key = {} maxcandidate = None maxval = 0 for key in candidate_dict.keys(): if candidate_dict[key]> maxval: maxval = candidate_dict[key] maxcandidate = key #print(key, candidate_dict[key]) #calculate the % Votes for each Candidate percent_candidate_key[key] = round(((candidate_dict[key]/totalVotes)*100),3,) #Percentage of Votes for Candidate {}: {}%".format(key, percent_candidate_key[key])) print("{} : {}% ({})".format(key, percent_candidate_key[key], candidate_dict[key])) print("{} : {}% ({})".format(key, percent_candidate_key[key], candidate_dict[key]),file=f) print("-----------------------------") print("Winner : {}".format(maxcandidate)) print("-----------------------------") #write to output file print("-----------------------------", file=f) print("Winner : {}".format(maxcandidate), file=f) print("-----------------------------", file=f) #with votes {}".format( maxcandidate, maxval)) f.close()
# -*- coding: utf-8 -*- """ problem 87 weblink: description: The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is 28. In fact, there are exactly four numbers below fifty that can be expressed in such a way: 28 = 22 + 23 + 24 33 = 32 + 23 + 24 49 = 52 + 23 + 24 47 = 22 + 33 + 24 How many numbers below fifty million can be expressed as the sum of a prime square, prime cube, and prime fourth power? Analysis """ from __future__ import print_function, unicode_literals, absolute_import, division from projecteulerhelper import * #timeit is encluded into projecteulerhelper now from prime import isprime,primesbelow # test the correction by a small dimension first. # test brute force first, method1 #then, try some smart method! def test(): # assert pass def bruteforce(): """ bruteforce seems not possible """ N=5*10**7 l=set() l2=[i**2 for i in primesbelow(int(N**0.5))] l3=[i**3 for i in primesbelow(int(N**(1.0/3.0)))] l4=[i**4 for i in primesbelow(int(N**0.25))] print(l2,l3) for i4 in l4: for i3 in l3: for i2 in l2: isum=i2+i3+i4 if isum <= N: l.add(isum) else: break print(len(l)) def smarter(): """ """ pass def solve(): bruteforce() #smarter() if __name__ == "__main__": test() timeit(solve) #timeit(func, param)
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: In the hexadecimal number system numbers are represented using 16 different digits: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F The hexadecimal number AF when written in the decimal number system equals 10x16+15=175. In the 3-digit hexadecimal numbers 10A, 1A0, A10, and A01 the digits 0,1 and A are all present. Like numbers written in base ten we write hexadecimal numbers without leading zeroes. How many hexadecimal numbers containing at most sixteen hexadecimal digits exist with all of the digits 0,1, and A present at least once? Give your answer as a hexadecimal number. (A,B,C,D,E and F in upper case, without any leading or trailing code that marks the number as hexadecimal and without leading zeroes , e.g. 1A3F and not: 1a3f and not 0x1a3f and not $1A3F and not #1A3F and not 0000001A3F) weblink: Analysis: """ from projecteulerhelper import * #timeit is import from helper, instead of timeit module # from math import factorial # test the correction by a small dimension first. # test brute force first, method1 #then, try some smart method! def P(N,s): if N<s: return 0 r=1 for i in range(s): r*=(N-i) return r def C(N,s): if N<s: return 0 r=1 for i in range(s): r*=(N-i) return r/factorial(s) def f(N): """ permutates '01A' by factorial(3), choose N-3 places from N =>production exclude the cases: zero is at the first position, permutates '1A' by factorial(2), choose N-3 places from N-1 =>production """ #return ( C(N,3) * factorial(3) - C(N-1,2) * factorial(2) ) * 16**(N-3) #CF593F4E531A7124 error!s #return ( factorial(3) - factorial(2) ) * 16**(N-3) # all 4 error! return 2* P(N-1,2) * 16**(N-3) + (16-3)*P(N-1,3) * 16**(N-4) def test(): print(C(5,3)) print(f(3)) print(f(4)) print(f(5)) print('test passed') def bruteforce(): print('{0:X}'.format(sum( [ f(i) for i in range(4,17) ]) + 4)) def smarter(): """ http://blog.dreamshire.com/2009/04/09/project-euler-problem-162-solution/ """ s = 0 for n in range(3, 17): p=15 * 16**(n - 1) + 41 * 14**(n - 1) - (43 * 15**(n - 1) + 13**n) print(n,p) s+=p print("Answer to PE162 = %X" % s) def problem(): test() bruteforce() smarter() if __name__ == "__main__": timeit(problem) #timeit(func, param)
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? weblink: https://projecteuler.net/problem=16 """ from projecteulerhelper import * #timeit is import from helper, instead of timeit module # # test the correction by a small dimension first. # test brute force first, method1 #then, try some smart method! def test(): print(2**50) print('0123'[-1]) # 3 print('0123'[:-1]) # '012' does not include the last one, print('0123'[:0]) # empty def bruteforce(): # one liner print("solution:", sum([int(c) for c in str(2**1000)[:-1]])) # there is trailing L for python 2.x long type, but python 2.7 str(long) will remove the def smarter(): pass def problem(): #test() bruteforce() #smarter() if __name__ == "__main__": timeit(problem) #timeit(func, param)
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. weblink: """ from projecteulerhelper import * #timeit is import from helper, instead of timeit module # test the correction by a small dimension first. # test brute force first, method1 #then, try some smart method! def test(): assert max_palindromic_number(2)==9009 def max_palindromic_number(ndigits): l=[] for i in range(10**ndigits-1,10**(ndigits-1),-1): for j in range(10**ndigits-1,10**(ndigits-1),-1): if str(i*j)==str(i*j)[::-1]: # #print i,j,i*j l.append(i*j) break return max(l) def problem(): print((max_palindromic_number(3))) if __name__ == "__main__": test() timeit(problem) #timeit(func, param)
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import, division """ problem description: The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? weblink: """ from projecteulerhelper import * #timeit is import from helper, instead of timeit module from math import sqrt # # test the correction by a small dimension first. # test brute force first, method1 #then, try some smart method! def divisors(x): #if x<4: return [1,x] if int(sqrt(x))**2 == x: l=[int(sqrt(x))] stop=int(sqrt(x)) else: stop=int(sqrt(x))+1 l=[] # for i in range(1, stop): if x%i==0: l.append(i) # there will be no repeat! l.append(x/i) return sorted(l) def test(): for i in range(1,10): print('divisors(',i ,')=', divisors(i)) print('divisors(28):',divisors(28)) print('divisors(64):', len(divisors(64))) print('divisors(128):', len(divisors(128))) def bruteforce(): # impossible dmax=2 start=1000 for i in range(start,10**6): l=len(divisors(i)) if l>dmax: dmax=l if dmax>500: print(i,dmax) break def product(list): p = 1 for i in list: p *= i return p def smarter(): # x=p1**i1 * p2**i2 ... p is the prime list # all prime has only 2 divisors # increasing the power is not effective as increase the prime, only by +1 print('divisors(30):', len(divisors(30))) # 2**3 print('divisors(210):', len(divisors(210))) # print('divisors(2310):', len(divisors(2310))) # 32 print('divisors(4620):', len(divisors(4620))) #X2 print('divisors(9240):', len(divisors(9240))) #X4 print('divisors(18480):', len(divisors(18480))) #X8 print('divisors(30030):', len(divisors(30030))) #2**6 p=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29] pp=[] #[2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870, 6469693230L] for i in range(len(p)): pp.append( product(p[:i+1])) pn=[len(divisors(x)) for x in pp] print(pp,pn) # mul by 2, can increase half of the len, print('divisors() of', 9699690*4, len(divisors(9699690*4))) #512 print("test passed") def problem(): #test() #bruteforce() smarter() if __name__ == "__main__": timeit(problem) #timeit(func, param)
# -*- coding: utf-8 -*- """ Euler's Totient function, φ(n) [sometimes called the phi function], is used to determine the number of positive numbers less than or equal to n which are relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, φ(9)=6. The number 1 is considered to be relatively prime to every positive number, so φ(1)=1. Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180. Find the value of n, 1 < n < 10**7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum. """ from __future__ import print_function, unicode_literals, absolute_import, division from factorization import primefactorize, totient from prime import isprime import itertools def test(): assert totient(87109)==79180 #print(list(itertools.permutations(str(31)))) assert set(str(13)) == set(str(31)) def phi(n): """ if it is prime number, n/phi(n) is small near 1 but for prime number phi(n)=n-1, """ if isprime(n): return n-1 else: s=[] #to-do return len(s) def problem70(): print("try to solve problem 70 by bruteforce") l = [] min = 1 for i in range(2,10**6): phi_i = totient(i) if not phi_i/i < min: continue else: if set(str(i)) == set(str(phi_i)): l.append((i,phi_i/i)) min = phi_i/i ll = sorted(l, key=lambda t:t[1]) print(ll[0][0]) if __name__ == "__main__": test() problem70()
#sort these arrays & print out median from itertools import cycle def main(): shouldEnter= int(raw_input()) masterList=[] median=[] for i in range(0,shouldEnter): list=raw_input().split(" ") masterList.append(list) for i in masterList: numList=[] for x in i: numList.append(int(x)) sorted(numList,key=int) print numList[1] main()
#################Pro Co 2009 Problems######################### ######################2.5####################### def main_Snupper(): sent= "we provide great gifts for every occasion" print sent.title() #####################5.2##################### def main_YaWho(): original= "stanford proco" check="pfd" count =0 for i in check: if original.find(i) !=-1: #if found count=count+1 if count ==len(check): print "yes" else: print "no" #####################2.3###################### def main_AtnTa(): input= "Go hang a salami I m a lasagna hog" input.lower() for i in input: if i== " ": input.replace(i,"") if input== input[::-1]: print "yes" else: print "no" main_AtnTa()
import numpy as np #Question 9: Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array. F= np.array([0, 12, 45.21 ,34, 99.91]) print ("Value of Centigrade degrees: {}".format(F)) C = (5*(F-32))/9 print ("Value of Centigrade degrees: {}".format(C)) #Using for loop to iterate entire F array and print out new array result #for i in F: # D = np.array([]) # j = (5*(F-32))/9 # D = np.append(D, j, axis = 0) #print ("Value of Centigrade degrees: {}".format(D)) #Question : Write a NumPy program to get the unique elements of an array. arr = np.array([10, 10, 20, 20, 30, 30, 1, 2, 4, 1, 3, 2, 10, 40, 5, 9]) uniqueArr = np.unique(arr) print ("The unique element in an array is {}".format(uniqueArr))
age = int(input("How old are you? ")) height= input(f"You are {age} old? Nice. How tall are you? ") weight = input("How much are you weight? ") print(f"So, you are {age} old, {height} tall and {weight} heavy.")
names = ['Richie','George','Gogdito','Sien','Lalo','Pepito','Gus','Xavo'] message = "Hi dear " print(message + names[0]) print(message + names[1]) print(message + names[2]) print(message + names[3]) print(message + names[4]) print(message + names[5]) print(message + names[-1])
from random import randint # 무작위로 정렬된 1 - 45 사이의 숫자 여섯개 뽑기 # 오름차순 리스트...이거 그건데 자료구조 # https://www.codeit.kr/assignments/140 def generate_numbers(): lotto = [] i = 0 while i < 6: select = randint(1, 45) while select in lotto: select = randint(1, 45) lotto.append(select) lotto.sort() return lotto # 보너스까지 포함해 7개 숫자 뽑기 # 정렬된 6개의 당첨 번호와 1개의 보너스 번호 리스트를 리턴 # 예: [1, 7, 13, 23, 31, 41, 15] def draw_winning_numbers(): lotto2 = [] i = 0 while i < 6: select = randint(1, 45) while select in lotto2: select = randint(1, 45) lotto2.append(select) lotto2.sort() bonus = randint(1, 45) lotto2.append(bonus) return lotto2 # 두 리스트에서 중복되는 숫자가 몇개인지 구하기 def count_matching_numbers(list1, list2): over_count = 0 i = 0 while i < int((range(list1)-1)): if list1[i] in list2: over_count += 1 i += 1 else: i += 1 return over_count # 로또 등수 확인하기 def check(numbers, winning_numbers): ranking = 0 i = 0 while i < int((range(numbers)-1)): if numbers[i] in winning_numbers: ranking += 1 i += 1 else: i += 1 if ranking == 6: return 1000000000 elif ranking == 5 and numbers[6] in winning_numbers: return 50000000 elif ranking == 5: return 1000000 elif ranking == 4: return 50000 elif ranking == 3: return 5000
from string import ascii_lowercase, ascii_uppercase import operator import nltk nltk.download("words", quiet=True) from nltk.corpus import words alphabet_lower = ascii_lowercase alphabet_upper = ascii_uppercase word_list = words.words() def encrypt(text_phrase: str, key: int) -> str: """[encrypts you phrase by shifting letters equal to the key] Args: text_phrase (str): [phrse you want to encrypt] key (int): [amount to shift] Raises: TypeError: [when phrase is not a str and when key is not an int] Exception: [When you use characters that are not a-z] Returns: str: [encypted phrase] """ if type(text_phrase) != str or type(key) != int: raise TypeError( "Please enter a valid string and a valid integer for this method" ) encrypted_text = "" for char in text_phrase: if not char.isalpha(): encrypted_text += char else: if char.islower(): alphabet = alphabet_lower elif char.isupper(): alphabet = alphabet_upper new_value = alphabet.index(char) + key if new_value > 25 or new_value < -25: new_value = new_value % 26 if new_value < 0: new_value = new_value + 26 encrypted_text += alphabet[new_value] return encrypted_text def decrypt(text_phrase: str, key: int) -> str: """[Will decrypt a phrase with the provided key] Args: text_phrase (str): [Phrase you want to decrypt] key (int): [amount to shift] Returns: str: [decrypted message] """ return encrypt(text_phrase, -key) def crack(encrypted_phrase: str) -> str: """[decode the cipher so that an encrypted message can be transformed into its original state WITHOUT access to the key] Args: encrypted_phrase (str): [encrypted string] Returns: str: [decrypted str] """ if type(encrypted_phrase) != str: return False decrypt_dict = {} for num in range(26): decrypted = decrypt(encrypted_phrase, num) decrypted_words_list = decrypted.split() readable_words = 0 for word in decrypted_words_list: if word in word_list: readable_words += 1 decrypt_dict[readable_words] = decrypted return decrypt_dict[max(decrypt_dict.keys())]
# Asynchronous TCP Server using core socket functions and "Select" import socket import select import string #Function to send message to client def send_data(sock, message): #Send message to client. #print("Connection is--",sock,"----Message is----", message) try: sock.send(message) except ConnectionResetError: print("Connection Closed by Client") #Reverse the string received from server def reverse(inputString): inputString = inputString[::-1] return inputString if __name__ == "__main__": # List to keep track of socket descriptors CONNECTION_LIST = [] # Create, bind and listening on the server socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("127.0.0.1", 8888)) #server_socket.settimeout(15) server_socket.listen() # Add server socket to the list of readable connections print(server_socket) CONNECTION_LIST.append(server_socket) print("TCP server running on PORT#8888") while True: # Check which sockets are ready to be read using select.select read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST, [], []) #print(read_sockets, "---", write_sockets, "---", error_sockets) for sock in read_sockets: #print("Socket is :", sock) if sock == server_socket: # if true, new connection received on server_socket sockfd, addr = server_socket.accept() sockfd.setblocking(1) sockfd.settimeout(15)#Does not work because Python Doc -> "18.1.4.2. Timeouts and the accept method" CONNECTION_LIST.append(sockfd) #print(CONNECTION_LIST) #print(sockfd,"---",addr) else:# Data received from client, process it try: # Sometimes TCP program closes abruptly resulting in "Connection reset by peer" exception data = sock.recv(1024) #print("Client Data --- ",data) if(len(data)==0): send_data(sock, data) sock.close() CONNECTION_LIST.remove(sock) continue except: send_data(sock, ("Client (%s, %s) is offline" % addr).encode()) print("Client (%s, %s) is offline" % addr) sock.close() CONNECTION_LIST.remove(sock) continue #print("Client (%s, %s) connected" % addr) outString = reverse(data) #print("Received---", data) #print("Sending---", outString) send_data(sock, outString) #sock.close() #CONNECTION_LIST.remove(sock) server_socket.close()
from random import randint # dictionary containing customized settings of each levels levels = { "1": { "name": "Easy", "start_message": ""f"What's the secret number to the treasure Chest", "min_num": 1, "max_num": 6, "guesses": 6 }, "2": { "name": "Medium", "start_message": "Guess the secret number to open the safe", "min_num": 1, "max_num": 20, "guesses": 4 }, "3": { "name": "Hard", "start_message": "Guess the secret number to the unlock the vault", "min_num": 1, "max_num": 50, "guesses": 3 } } # function for game play dialog def play_game(): while True: play = input("Yes/No: ") if play.lower() == "yes": start() elif play.lower() == "no": print("Okay, maybe next time!") exit(0) else: print("Wrong input!") # function to be used for each levels when selected def game(level): game_plot = levels[level] # assigning each key in the "levels" dictionary to the variable number = randint(game_plot["min_num"], game_plot["max_num"]) # setting the level secret number print(number) print(f"{game_plot['start_message']}\nYou have {game_plot['guesses']} number of guess(es) left.") while True: try: answer = input(f"hint: number is between {game_plot['min_num']} and {game_plot['max_num']}?\nAnswer: ") game_plot["guesses"] -= 1 if int(answer) == number: # if user gets the answer while in level 3 if level == "3": print("You win the game!\nRestart Game?") play_game() # if user gets the answer in other levels print("You got it right!\nEnter next level?") while True: next_level = input("Yes/No: ") if next_level.lower() == "yes": game(str(int(level) + 1)) elif next_level.lower() == "no": print("Okay, maybe next time!") exit(0) else: print("Wrong input!") # if user doesn't get the answer and has no more guesses left elif game_plot["guesses"] == 0: print("You have no more guesses left.\nYou lose!") print("Do you want to play again") play_game() # if user does not get the answer and still has guesses else: print(f"Wrong try again!\nYou have {game_plot['guesses']} guess(es) left") # if user enters anything other than a number except ValueError: print(f"Please enter a number!\nYou have {game_plot['guesses']} guess(es) left") # function that starts the game def start(): print("Select your difficulty level\nEasy: 1\nMedium: 2\nHard: 3") while True: try: level = input("Enter level number: ") if level == "1" or level == "2" or level == "3": game(level) # python uses the level selected to call the game function else: print("Wrong input!") except ValueError: print(f"Please enter a number!") # Game intro print("Hi gamer, Welcome to Number Guess!\nAre you ready to play?") play_game()
def tokenize(sentence): for sym in ['.', ',', '?', ';', '\'', ':']: sentence = sentence.replace(sym, ' ' + sym) return sentence.split()
# Convert the ASCII input to hex representation in upper case. # # Example: "FOo123" -> "464F6F313233" def transform(n): newstring = '' n = list(n) for c in n: newstring += hex(ord(c))[2:].upper() return newstring
#Radhika PC #5/25/2016 #Homework2 numbers = [22,90,0,-10,3,22, 48] #display th enumber of elements in the list print(numbers) #display the 4th elements print("The 4th element is", numbers[3]) #Display the sum of the 2nd and 4th element of the list. print("The sum of 2nd and 4th element is", numbers[1] + numbers[3]) #Display the 2nd-largest value in the list. sorted_numbers = sorted(numbers) print("The second largest number is", sorted_numbers[5]) #Display the last element of the original unsorted list print("The last element of the original list is", numbers[6]) #Sum the result of each of the numbers divided by two. new = 0 sum = 0 for i in numbers: new = i / 2 sum = sum + new print("The sum is", sum) # question no:6 #For each number, display a number: for number in numbers: print(number) #if your original number is less than 10, multiply it by thirty. for number in numbers: if number < 10: new_num= number * 30 print("If original number is less than 10, this is the answer", new_num) #If it's ALSO (less than ten and even I assume) even, add six if number%2 ==0: new_new_no = new_num + 6 print("If the number is less than 10 and an even number, the result is", new_new_no) # If it's greater than 50 subtract ten. if number > 50: x_no = number - 50 print("If the number is greater than 50, the result is", x_no) # If it's not negative ten, subtract one if number !=-10: xy_no = number - 1 print("if the number is not -10, then the result is ", xy_no)
#!/usr/bin/env python # coding: utf-8 import math def rotate(degre,posX,posY,largeur,hauteur): ''' Besoins de la fonction degre : angle en degré de la rotation souhaitée posX : Position initiale de x de la forme posy : Position initiale de y de la forme largeur : largeur de la forme hauteur : hauteur de la forme ''' angle = degre centre_posX = posX + largeur/2 centre_posY = posY + hauteur/2 print ("transform=\"rotate({0},{1},{2})\"").format(degre, centre_posX, centre_posY) print (""Fonction rotate") rotate(60,0,0,500,500) def matrix(degre,posX,posY,largeur,hauteur): ''' Matrice de rotation: matrix(cos(angle),-sin(angle),sin(angle),cos(60),OrigineX,OrigineY) Besoins de la fonction matrix: degre : angle en degré de la rotation souhaitée posX : Position initiale de x de la forme posy : Position initiale de y de la forme largeur : largeur de la forme hauteur : hauteur de la forme ''' angle = degre OrigineX = posX + largeur/2 OrigineY = posY + hauteur/2 a = math.cos(math.radians(angle)) b = -math.sin(math.radians(angle)) c = math.sin(math.radians(angle)) d = math.cos(math.radians(angle)) e = OrigineX f = OrigineY print (""Fonction Matrix") print("matrix({0},{1},{2},{3},{4},{5})").format(a,b,c,d,e,f) matrix(60,0,0,500,500)
#!/usr/bin/env python """ The Retuner script serves as a convenient means of adjusting the pitch and/or speed of a given audio file. The script makes use of the pydub and librosa libraries/modules to either adjust the pitch of a file by semitonal intervals or both the pitch and the playback speed. The latter retains the audio quality of the original file, though it produces a "chipmunks" quality that the former manages to avoid. """ __all__ = ["Retuner", "log_msg"] __author__ = "Andrew Eissen" __version__ = "0.1" import librosa import pydub import os import soundfile import sys class Retuner: def __init__(self, path, new_path, steps, sample_rate=44100): """ The ``Retuner`` class encapsulates the functions responsible for adjusting the pitch and/or speed of a given audio track denoted by the ``path`` formal parameter by the number of semitones specified by ``steps``. The ``sample_rate`` parameter, an optional param, is set to the industry standard 44100 by default. The class makes use of the librosa library for the adjustment of pitch without simultaneous adjustment of speed, while the pydub library is used to adjust the two in concert to preserve audio quality. :param path: The path to the audio file. Ideally, this file should be a ``wav`` file, though the script will convert ``mp3``s. :param new_path: The path indicating where and to what name the new file should be saved in relation to the working directory :param steps: The number of semitones by which to pitch-adjust the audio track (C -> C#, for example) :param sample_rate: An optional parameter denoting the sample rate at which to export the file, set to industry-standard 44100 by default """ self.path = path self.new_path = new_path self.steps = steps self.sample_rate = sample_rate @property def path(self): """ This function serves as the primary property "getter" function used to externally access the ``path`` instance attribute. It simply returns the value of the attribute in question. :return: The internal "private" object attribute endemic to the class instance """ return self._path @path.setter def path(self, value): """ This function serves as the primary property "setter" function used to externally set/reset new values for the ``path`` instance attribute. It evaluates the input passed in the ``value`` parameter, breaking it down and ensuring the file is a ``wav`` before applying the new value to the attribute. An mp3-to-wav conversion is undertaken if the file is not of the correct type (requires ffmpeg). :param value: The value to be applied to the "private" class instance attribute :return: None """ extension = os.path.splitext(value)[1] file_name = os.path.splitext(value)[0] # Convert MP3 files to WAV for ease of pitch adjustment if extension.lower() == ".mp3": sound = pydub.AudioSegment.from_mp3(value) sound.export(f"{file_name}.wav", format="wav") value = f"{file_name}.wav" self._path = value @property def new_path(self): """ This function serves as the primary property "getter" function used to externally access the ``new_path`` instance attribute. It simply returns the value of the attribute in question. :return: The internal "private" object attribute endemic to the class instance """ return self._new_path @new_path.setter def new_path(self, value): """ This function serves as the primary property "setter" function used to externally set/reset new values for the ``new_path`` instance attribute. It simply applies the new value to the attribute in question. :param value: The value to be applied to the "private" class instance attribute :return: None """ self._new_path = value @property def steps(self): """ This function serves as the primary property "getter" function used to externally access the ``steps`` instance attribute. It simply returns the value of the attribute in question. :return: The internal "private" object attribute endemic to the class instance """ return self._steps @steps.setter def steps(self, value): """ This function serves as the primary property "setter" function used to externally set/reset new values for the ``steps`` instance attribute. It simply applies the new value to the attribute in question, ensuring the input is coerced to type float. :param value: The value to be applied to the "private" class instance attribute :return: None """ self._steps = float(value) @property def sample_rate(self): """ This function serves as the primary property "getter" function used to externally access the ``sample_rate`` instance attribute. It simply returns the value of the attribute in question. :return: The internal "private" object attribute endemic to the class instance """ return self._sample_rate @sample_rate.setter def sample_rate(self, value): """ This function serves as the primary property "setter" function used to externally set/reset new values for the ``sample_rate`` instance attribute. It simply applies the new value to the attribute in question, ensuring the input is coerced to type int. :param value: The value to be applied to the "private" class instance attribute :return: None """ self._sample_rate = int(value) def pitch_shift_and_adjust_speed(self): """ The ``pitch_shift_and_adjust_speed`` function makes use of the ``pydub`` library's functionality to undertake semitonal pitch shifts that occur in concert with playback speed changes. The function creates a new file at a new name for the adjusted audio file, following the format "``Filename_[number of steps].wav``". :return: None """ sound = pydub.AudioSegment.from_file(self.path, format="wav") new_sound = sound._spawn(sound.raw_data, overrides={ "frame_rate": int(sound.frame_rate * (2.0 ** (self.steps / 12.0))) }) new_sound = new_sound.set_frame_rate(self.sample_rate) new_sound.export(f"{self.new_path}.wav", format="wav") def pitch_shift(self): """ The ``pitch_shift`` function makes use of the librosa library's functionality to undertake the semitonal adjustment of an audio file's pitch without making simultaneous adjustments to playback speed. The function creates a new file at a new name for the adjusted audio file, following the format "``Filename_[number of steps].wav``". :return: None """ y, sr = librosa.load(self.path, sr=self.sample_rate) y_shifted = librosa.effects.pitch_shift(y, sr, n_steps=self.steps) soundfile.write(f"{self.new_path}.wav", y_shifted, self.sample_rate, "PCM_24") def log_msg(message_text, text_io=sys.stdout): """ The ``log_msg`` function is simply used to log a message in the console (expected) using either the ``sys.stdout`` or ``sys.stderr`` text IOs. It was intended to behavior much alike to the default ``print`` function but with a little more stylistic control. :param message_text: A string representing the intended message to print to the text IO :param text_io: An optional parameter denoting which text IO to which to print the ``message_text``. By default, this is ``sys.stdout``. :return: None """ text_io.write(f"{message_text}\n") text_io.flush() def main(): """ In accordance with best practices, the ``main`` function serves as the central coordinating function of the script, handling all user input, calling all helper functions, catching all possible generated exceptions, and posting results to the specific text IOs as expected. :return: None """ lang = { "p_intro": "Enter file path, new file path, number of steps by which " + "to transpose, and whether or not to adjust both speed " + "and pitch", "e_steps": "Error: Second value must be of a number type", "e_adjust_both": "Third value must be of type boolean", "e_no_file": "Error: No audio file found by that name", "i_converting": "Converting...", "s_complete": "Success: Conversion complete" } # Accept either command line args or console input if len(sys.argv) > 1: input_data = sys.argv[1:] elif sys.stdin.isatty(): log_msg(lang["p_intro"], sys.stdout) input_data = [arg.rstrip() for arg in sys.stdin.readlines()] else: sys.exit(1) # Unpack input values path, new_path, steps, adjust_both = input_data # Ensure steps and adjustment flag are of proper types try: steps = float(steps) adjust_both = eval(adjust_both) except ValueError: log_msg(lang["e_steps"], sys.stderr) sys.exit(1) except NameError: log_msg(lang["e_adjust_both"], sys.stderr) sys.exit(1) log_msg(lang["i_converting"], sys.stdout) try: # Only adjust pitch, not speed, if adjust_both is False getattr(Retuner(path, new_path, steps), ("pitch_shift", "pitch_shift_and_adjust_speed")[adjust_both])() log_msg(lang["s_complete"], sys.stdout) except FileNotFoundError: log_msg(lang["e_no_file"], sys.stderr) if __name__ == "__main__": main()
import numpy as np count = 0 # счетчик попыток number = np.random.randint(1,101) # загадали число print ("Загадано число от 1 до 100") def score_game(game_core): '''Запускаем игру 1000 раз, чтобы узнать, как быстро игра угадывает число''' count_ls = [] np.random.seed(1) # фиксируем RANDOM SEED, чтобы ваш эксперимент был воспроизводим! random_array = np.random.randint(1,101, size=(1000)) for number in random_array: count_ls.append(game_core(number)) score = int(np.mean(count_ls)) print(f"Ваш алгоритм угадывает число в среднем за {score} попыток") return(score) def game_core_v2(number): '''Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного. Функция принимает загаданное число и возвращает число попыток''' count = 1 min_number = 1 #задаем нижнюю границу поиска max_number = 101 # задаем верхнюю границу поиска predict = np.random.randint(1,101) # первый раз пытаемся угадать число while number != predict: count+=1 if number > predict: min_number = predict+1 # Если предпологаемое число меньше загаданого то меняем нижнюю границу поиска elif number < predict: max_number = predict # Если предпологаемое число больше загаданого то меняем верхнюю границу поиска predict = np.random.randint(min_number,max_number) # попытка угадать число с новыми границами return(count) # выход из цикла, если угадали def game_core_v3(number): '''Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного. Функция принимает загаданное число и возвращает число попыток''' count = 1 min_number = 1 #задаем нижнюю границу поиска max_number = 101 # задаем верхнюю границу поиска predict = np.random.randint(1,101) # первый раз пытаемся угадать число while number != predict: count+=1 if number > predict: min_number = predict # Если предпологаемое число меньше загаданого то меняем нижнюю границу поиска elif number < predict: max_number = predict # Если предпологаемое число больше загаданого то меняем верхнюю границу поиска #predict = np.random.randint(min_number,max_number) # попытка угадать число с новыми границами predict = min_number + (max_number-min_number)//2 return(count) # выход из цикла, если угадали # Проверяем score_game(game_core_v3)
# -*- coding: utf-8 -*- """ Created on Tue Mar 30 14:04:28 2021 @author: Keshav """ def magic_square(n): magicSquare = [] #initializing magic square to all 0 for i in range(n): l = [] for j in range(n): l.append(0) magicSquare.append(l) i=n//2 j=n-1 num = n*n #total no of blocks count = 1 # my elements while (count<=num): if (i==-1 and j==n): # condition 4 i=0;j=n-2 else: if(j==n): # column is exceeding j=0 if(i<0): #row is becoming -1 i=n-1 if (magicSquare[i][j]!=0): i=i+1 j=j-2 continue #for checking above conditions again else: magicSquare[i][j]=count count+=1 i=i-1 j=j+1 #printing the magic square for i in range(n): for j in range(n): print(f'{magicSquare[i][j]:5}',end="") print() print("The sum of each row/column/diagonal is : "+str((n*(n**2+1))/2) ) magic_square(13)
import string flames = {'f':'friend','l':'love','a':'affirmative','m':'marriage','e':'enemy','s':'sister'} p1=list(input("Please Input Your Name : ").lower().replace(" ", "")) p2=list(input("Please Input Your Name : ").lower().replace(" ", "")) def remove_matching_letters(): for i in p1: for j in p2: if (i==j): p1.remove(j) p2.remove(j) return True return False def find_relation(n): s=list("flames") count =0 while True: index = 0 while (index < len(s)): if count == n: s.remove(s) count = 0 else: count +=1 index+=1 proceed = True while proceed: proceed = remove_matching_letters() my_number = len(p1)+len(p2) s=find_relation(my_number) print(my_number) print(p1) print(p2) print(s)
import timeit def linear_search(a,x): flag =0 for i in a : if (i==x): print("yes !! found my number at position",str(i)) flag =1 break if (flag==0): print("Number not found") def binary_search(a,x): first_pos = 0 last_pos = len(a)-1 flag = 0 while(first_pos<=last_pos and flag == 0): mid_pos = (first_pos + last_pos)//2 if(a[mid_pos]==x): flag=1 print("The element present in position: "+str(mid_pos)) elif(a[mid_pos]<x): first_pos = mid_pos else: last_pos = mid_pos print(mid_pos) if (flag == 0): print("your number is not present in list") a=[] for i in range(1000001): a.append(i) start1 = timeit.default_timer() binary_search(a, 87857) stop1 = timeit.default_timer() start = timeit.default_timer() linear_search(a,87857) stop = timeit.default_timer() print("linear",stop-start) print("binary",stop1-start1) #binary_search(a, 88)
def pattern(n) for i in range(0,n+1): for k in range(n,i-1): print("",end="") for j in range(0,i): print("*",end="") print("\r") n=5 pattern(n)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 26 21:44:30 2017 @author: saul Función para contar las palabras dentro de un texto. Pasar como parametro el vector que almacena el texto Nota: El texto no debe tener letras con acento. """ def contarPalabras(vector): l = 0 # longitud del vector j = 0 # apuntador nPal = 0 # numero de palabras iniCad = False # cuando inicia una palabra finCad = False # cuando termina la palabra tamVec = len(vector) while(l < len(vector)): # recorrer el vector de letras for i in range(j, tamVec): # letras mayusculas if ord(vector[i]) >= 65 and ord(vector[i]) <= 90: iniCad = True # letras minusculas elif ord(vector[i]) >= 97 and ord(vector[i]) <= 122: iniCad = True else: if iniCad == True: finCad = True # se evalua si es la ultima palabra if l == tamVec: if iniCad == True: finCad = True l = l + 1 # incrementar # si se encontro una palabra if iniCad == True and finCad == True: nPal = nPal + 1 # se contabiliza la palabra # resetear variables de apoyo iniCad = False finCad = False j = i break # salir del for return nPal
import random a1 = input('Primeiro Aluno: ') a2 = input('Segundo Aluno: ') a3 = input('Terceiro Aluno: ') a4 = input('Quarto Aluno: ') list = [a1, a2, a3, a4] sort = random.choice(list) print('O aluno escolhido foi {}'.format(sort)) print('-'*20) from random import shuffle n1 = input('Primeiro Aluno: ') n2 = input('Segundo Aluno: ') n3 = input('Terceiro Aluno: ') n4 = input('Quarto Aluno: ') lis = [n1, n2, n3 ,n4] shuffle(lis) print('A ordem de apresentação será') print(lis)
# Testando dicionários '''pessoas = {'nome': 'Jabes', 'sexo': 'Masculino', 'idade': 18} print(f'Seu nome é: {pessoas["nome"]}\n' f'Você é do Sexo: {pessoas["sexo"]}\n' f'Sua Idade é de: {pessoas["idade"]} anos ') print(pessoas.values()) print(pessoas.keys()) print(pessoas.items()) del pessoas['sexo'] pessoas['nome'] = 'Bernardo' pessoas['peso'] = 80.5 for k, v in pessoas.items(): print(f'{k} = {v}')''' # Criando Dicionário dentro de uma lista '''brasil = list() estado1 = {'uf': 'Rio de Janeiro', 'sigla': 'RJ'} estado2 = {'uf': 'Minas Gerais', 'sigla': 'MG'} brasil.append(estado1) brasil.append(estado2) print(brasil[0]['uf']) print(brasil[1]['sigla'])''' # Ex estado = dict() brasil = list() for c in range(0, 3): estado['uf'] = str(input('Unidade Federativa: ')) estado['sigla'] = str(input('Sigla do Estado: ')) brasil.append(estado.copy()) print('-=' * 20) for e in brasil: for v in e.values(): print(v, end=' ') print()
print('{:=^40}'.format(' LOJAS FANHES ')) preço = float(input('Preço das compras: R$')) print('''FORMAS DE PAGAMENTO [ 1 ] à vista dinheiro/cheque [ 2 ] à vista cartão [ 3 ] 2x no cartão [ 4 ] 3x ou mais no cartão''') opc = float(input('Qual é sua opção? ')) if opc == 1: total = preço - (preço * 10 / 100) elif opc == 2: total = preço - (preço * 5 / 100) elif opc == 3: total = preço parcela = total / 2 print('Sua compra será parcela de 2x de R${:.2f}'.format(parcela)) elif opc == 4: total = preço + (preço * 20 / 100) totparc = int(input('Quantas parcelas? ')) parcelas = total / totparc print('Sua compra será parcelada em {}x de R${:.2f} COM JUROS'.format(totparc, parcelas)) else: total = preço print('\033[31m''OPÇÃO INVÁLIDA''\033[m'' de pagamento. Tente novamente.') print('Sua compra de R${:.2f} vai custar R${:.2f} no final'.format(preço, total))
from time import sleep import moeda p = float(input('Digite o preço: R$')) print('-=' * 20) print('CALCULANDO...') print('-=' * 20) sleep(2) print(f'A metade de {p} é {moeda.metade(p)}') sleep(2) print(f'O dobro de {p} é {moeda.dobro(p)}') sleep(2) print(f'Aumentando em 10%, temos R${moeda.aumentar(p, 10)}') sleep(2) print(f'Diminuindo em 20%, temos R${moeda.diminuir(p, 20)}')
'''for c in range(0, 5): print('oi') print('Fim')''' for c in range(0, 10): print(c) print('FIM') #i = int(input('Início: ')) #f = int(input('Fim: ')) #p = int(input('Passo: ')) #for c in range(i, f + 1, p): # print(c) #print('Adeus') '''s = 0 for c in range(0, 4): n = int(input('Digite um número: ')) s += n print('O somatório de todos os valores foi {}'.format(s))'''
def solution(N): if N <= 9: result = N else: nine_count = ((N)// 9) second_num = str((N)%9) result = int(second_num + nine_count*'9') print(result) N = 7 solution(N)