def final_script(): ''' a script at the bottom of this module that calls these functions to solve the problem. (mine is 8 lines). ''' order_stat = prompt.for_int('Enter order statistic', default=None, is_legal=(lambda x: True), error_message='It is not an integer.s') dictionary = read_corpus( order_stat, goody.safe_open('Enter file to process', 'r', 'No file avail. Try again.', default=None)) print_corpus(dictionary) print('Enter ' + str(order_stat) + ' words to start with') starting_words = [] for i in range(order_stat): starting_words.append( prompt.for_string('Enter word ' + str(i + 1), default=None, is_legal=(lambda x: True), error_message='')) number = prompt.for_int('Enter # of words to generate', default=None, is_legal=(lambda x: True), error_message='an int, but not a legal value') print('Random text = ' + str(produce_text(dictionary, starting_words, number)))
def targeted_action(game, turn_counter): row, column = get_row_and_column_from_input(game) valid_action = False while not valid_action: action = prompt.for_string( 'Enter action ("o" for options) ', default='').lower() if action == '': # add number number = prompt.for_int('Enter number', is_legal=(lambda x: 1 <= x <=9)) game.make_move(row, column, number) turn_counter += 1 valid_action = True elif action == 'r': # remove number game.remove(row, column) turn_counter += 1 valid_action = True elif action == 'c': # change number number = prompt.for_int('Enter number', is_legal=(lambda x: 1 <= x <=9)) game.change(row, column, number) turn_counter += 1 valid_action = True elif action == 'o': # list options print('{:>10}:\t Add piece'.format('<Enter>')) print('{:>10}:\t Remove piece'.format('r')) print('{:>10}:\t Change piece'.format('c')) print('{:>10}:\t Return to main menu'.format('e')) elif action == 'e': # exit the current prompt valid_action = True return turn_counter
def final_script(): ''' a script at the bottom of this module that calls these functions to solve the problem. (mine is 8 lines). ''' order_stat = prompt.for_int('Enter order statistic', default=None, is_legal=(lambda x : True), error_message='It is not an integer.s') dictionary = read_corpus(order_stat,goody.safe_open('Enter file to process', 'r', 'No file avail. Try again.',default=None)) print_corpus(dictionary) print ('Enter ' + str(order_stat) + ' words to start with') starting_words = [] for i in range(order_stat): starting_words.append(prompt.for_string('Enter word ' + str(i+1) , default=None, is_legal=(lambda x : True), error_message='')) number = prompt.for_int('Enter # of words to generate', default=None, is_legal=(lambda x : True), error_message='an int, but not a legal value') print ('Random text = ' + str(produce_text(dictionary, starting_words, number)))
def get_results(pairs, players): still_playing = set(range(1, len(pairs) + 1)) while len(still_playing) > 0: print("Waiting for results from tables", still_playing) table = prompt.for_int( "Enter a table number to report results", is_legal=lambda x: x in still_playing, error_message="Enter a table that has not finished their match.", ) table -= 1 winner = prompt.for_string( "Enter a winner (" + str(pairs[table][0].name) + ") or (" + str(pairs[table][1].name) + ") or (tie)", is_legal=(lambda x: x == pairs[table][0].name or x == pairs[table][ 1].name or x == "tie"), error_message="please enter the winner's full name or tie", ) if winner == "tie": pairs[table][0].ties.append(pairs[table][1]) pairs[table][1].ties.append(pairs[table][0]) else: if winner == pairs[table][0].name: pairs[table][0].wins.append(pairs[table][1]) pairs[table][1].losses.append(pairs[table][0]) else: pairs[table][1].wins.append(pairs[table][0]) pairs[table][0].losses.append(pairs[table][1]) still_playing.remove(table + 1) print()
def end_of_round_cleanup(players): while True: dropping = prompt.for_string( "Enter the (name of a player) who is dropping or (p)air next round or view (s)tandings or (a)dd a new player", is_legal=lambda x: x in [y.name for y in players] or x == "p" or x == "s" or x == "a", error_message="Invalid player name or not (p), (s), or (a)", ) if dropping == "p": break elif dropping == "s": calculate_standings(players) print_standings(players) elif dropping == "a": new_player = Player.Player( input("Enter the name of the new player: ")) num_byes = prompt.for_int( "Enter the number of byes this player has (if any). For example if this player is entering with a round 1 loss, enter 0. If this player is entering round 2 with a 1-0 record enter 1", is_legal=lambda x: x < num_rounds, error_message= 'A player should not have more byes than the total number of rounds.' ) for i in range(num_byes): new_player.wins.append('BYE') players.append(new_player) else: for i in range(len(players)): if dropping == players[i].name: print(players[i].name, "has been dropped.") global dropped_players #add the '#' character to signify that the player has been dropped #for run_from_file purposes players[i].name = '#' + players[i].name dropped_players.append(players[i]) del players[i] break print()
import main import prompt from champ_data import Champ_Data if __name__ == '__main__': # Execute necessary functions here game_status = True champs = main.get_tft_dict(main.CHAMP_API) # print(champs) class_slots = main.get_slots(main.get_tft_dict(main.CLASSES_API)) origin_slots = main.get_slots(main.get_tft_dict(main.ORIGINS_API)) print(class_slots) print(origin_slots) while game_status: level = prompt.for_int('Input your current level') comp = [] for x in range(level): while True: champ = prompt.for_string('Input champ #' + str(x + 1)) if champ.upper() in [x.upper() for x in champs.keys()]: comp.append(champ) break else: print('This is not a valid unit name') origins, classes = main.find_comp_origins_classes(comp) origins = main.count_dict(origins) classes = main.count_dict(classes)
def produce_text(corpus: {(str): [str]}, start: [str], count: int) -> [str]: result = start[:] for num in range(count): looking_key = result[-len(start):] if tuple(looking_key) not in corpus.keys(): result.append(None) return result result.append(choice(corpus[tuple(looking_key)])) return result if __name__ == '__main__': # Write script here os = prompt.for_int('Specify the order statistic to use', is_legal=(lambda x: x > 0), error_message='Enter a positive number') corpus = read_corpus( os, goody.safe_open('Specify the file name for processing', 'r', 'unable to read this file')) print('Corpus\n{}'.format(corpus_as_str(corpus))) start_list = [ input('Specify word {}: '.format(i)) for i in range(1, os + 1) ] gen_num = prompt.for_int('Specify # of words to generate', is_legal=(lambda x: x >= 0), error_message='Enter a non-negative number') print('Random text = {}\n'.format(produce_text(corpus, start_list, gen_num))) # For running batch self-tests
for i in range(generate_count): try: new = random.choice(d[tuple(current)]) generated.append(new) current.pop(0) current.append(new) except IndexError: generated.append(None) break return generated order_statistic = prompt.for_int('Enter order statistic', is_legal = lambda x: x>0) file = open('thisisawesome.txt', 'r', encoding = 'utf-8') corpus = read_corpus(order_statistic, file) # print_corpus(corpus) print('Enter {} words to start with'.format(order_statistic)) starting_words = [] for i in range(order_statistic): starting_words.append(prompt.for_string('Enter word {}'.format(i+1))) words_to_generate = prompt.for_int('Enter # of words to generate', is_legal = (lambda x: x > 0))
def produce_text(corpus: {(str): [str]}, start: [str], count: int) -> [str]: text, new_word = start.copy(), '' for _ in range(count): new_word = None if tuple(text[-len(start):]) not in corpus else choice( corpus[tuple(text[-len(start):])]) text.append(new_word) if not new_word: return text return text if __name__ == '__main__': # Write script here os, start = prompt.for_int( 'Choose the order statistic ', default=2, is_legal=(lambda x: x >= 0), error_message='Not a Valid Order Statistic!'), [] corpus = read_corpus( os, safe_open('Choose the file name to process ', 'r', 'Not a Valid Filename! Try Again!', default='wginput1.txt')) print('Corpus', corpus_as_str(corpus), f'Choose {os} words to start with', sep='\n') for i in irange(1, os): start.append( prompt.for_string(
import prompt,math x = prompt.for_int('Enter x') print(x,'!=',math.factorial(x),sep='')
from goody import irange from dice import Dice from stopwatch import Stopwatch import prompt import predicate win_count = 0 #Win/Lose/Dice Statistics lose_count = 0 dice = Dice([6,6]) game_timer = Stopwatch() games_to_play = prompt.for_int('Enter # of games to play', is_legal=predicate.is_positive, error_message='an int, but not > 0') game_timer.start() dice.standard_rolls_for_debugging() for game in irange(1, games_to_play): #Each iteration plays one game first_roll = dice.roll().pip_sum() #Roll the dice and record their pip sum #Based on firstRoll, decide how to continue: # immediate win/loss or trying to make point if first_roll == 7 or first_roll == 11: win_count += 1 #Win on the first roll with 7 or 11 elif first_roll == 2 or first_roll == 3 or first_roll == 12: lose_count += 1 #Lose on the first roll with 2, 3, or 12 else: #Try to make the point as the game continues
# Script # Setup root root = Tk() root.title('main') main = Frame(root) main.pack(side=TOP,anchor=W) # Get a jpg file name, get the image from it, display the image i_file = prompt.for_string_via_index('Ener File name of JPG',legal=['uci.jpg','smallavengers.jpg'],default='uci.jpg') i = Image.open(i_file) display_image('image',i) # Get multiplicity for result image and M = prompt.for_int('Enter # repeats in rows,columns (1-10)',default=2,is_legal=lambda x : type(x) is int and 1<=x<=10) # Create image MxM times the original size, fill it with images, display the enlarged image ixM = Image.new('RGB',tuple(M*x for x in i.size)) for r in range(M+1): for c in range(M+1): ixM.paste(i,(r*i.size[0],c*i.size[1])) display_image('imageX'+str(M*M),ixM) # Create image the same size as i, filling it with smaller multiplicities of i i_small = i.resize(tuple(x//M for x in i.size)) i_smallxM = Image.new('RGB',i.size) for r in range(M): for c in range(M): i_smallxM.paste(i_small,(r*i_small.size[0],c*i_small.size[1])) display_image('image-squeezed'+str(M*M),i_smallxM)
import prompt x = prompt.for_int('Enter a value in [0,5]', is_legal=(lambda x: 0 <= x <= 5)) print(x)
def get_sudoku_number_from_input(): sudoku_number = prompt.for_int('Choose the sudoku number you want to use ', default=0, error_message='Please enter a non-negative integer.') return sudoku_number
""" return 'Modular(' + str(self._value) + ',' + str(self._modulus) + ')' if __name__ == '__main__': import prompt print('Begin testing Modular') command_prompt = \ """\nTesting Modular: Commands Queries Other i - inc v - value . - exec(...) d - dec m - modulus q - quit c - clear _ - __str__ Command""" m = Modular(prompt.for_int('Enter value'), prompt.for_int('Enter modulus')) while True: action = prompt.for_char(command_prompt, legal='idc_.q') try: if action == 'i': m.inc() elif action == 'd': m.dec() elif action == 'c': m.clear() elif action == 'v': print(' value =', m.value()) elif action == 'm': print(' modulus =', m.modulus()) elif action == 'c': m.clear() elif action == '_': print(' str =', m) elif action == '.': exec(prompt.for_string(' Enter command to exec (instance=m)')) elif action == 'q': break else:
mins,maxs=-1,-1 for k in sorted(corpus): print(' ',k,'can be followed by any of', corpus[k]) mins = len(corpus[k]) if mins == -1 or len(corpus[k]) < mins else mins maxs = len(corpus[k]) if maxs == -1 or len(corpus[k]) > maxs else maxs if len(corpus[k]) == 46: print (k,corpus[k]) print('min/max =',str(mins)+'/'+str(maxs)) def produce_text(corpus,text,count): os = len(text) for i in irange(count): key = tuple(start[-os:]) if key not in corpus: text.append(None) return text start.append(choice(corpus[key])) return start os = prompt.for_int('Enter order statistic',is_legal=lambda x : x >= 1) corpus = read_corpus(os, goody.read_file_values(goody.safe_open('Enter file to process', 'r', 'Cannot find that file'))) print_corpus(corpus) print('\nEnter '+str(os)+' words to start with') start = [prompt.for_string('Enter word '+str(i)) for i in irange(os)] how_many = prompt.for_int('Enter # of words to generate',is_legal=lambda x : x > 0) text = produce_text(corpus,start,how_many) print('Random text =',text)
import prompt, predicate StartingNumber = prompt.for_int("Enter starting number", is_legal = predicate.is_positive) while StartingNumber > 0: if StartingNumber % 3 == 0: print(StartingNumber, 0) StartingNumber = StartingNumber // 3 elif (StartingNumber+1) % 3 == 0: print(StartingNumber, 1) StartingNumber = (StartingNumber+1)//3 elif (StartingNumber-1) % 3 == 0 and (StartingNumber-1) != 0: print(StartingNumber, -1) StartingNumber = (StartingNumber-1)//3 elif StartingNumber == 1: print(StartingNumber) break
# Setup root root = Tk() root.title('main') main = Frame(root) main.pack(side=TOP, anchor=W) # Get a jpg file name, get the image from it, display the image i_file = prompt.for_string_via_index('Ener File name of JPG', legal=['uci.jpg', 'smallavengers.jpg'], default='uci.jpg') i = Image.open(i_file) display_image('image', i) # Get multiplicity for result image and M = prompt.for_int('Enter # repeats in rows,columns (1-10)', default=2, is_legal=lambda x: type(x) is int and 1 <= x <= 10) # Create image MxM times the original size, fill it with images, display the enlarged image ixM = Image.new('RGB', tuple(M * x for x in i.size)) for r in range(M + 1): for c in range(M + 1): ixM.paste(i, (r * i.size[0], c * i.size[1])) display_image('imageX' + str(M * M), ixM) # Create image the same size as i, filling it with smaller multiplicities of i i_small = i.resize(tuple(x // M for x in i.size)) i_smallxM = Image.new('RGB', i.size) for r in range(M): for c in range(M): i_smallxM.paste(i_small, (r * i_small.size[0], c * i_small.size[1]))
a - add p - peek . - exec(...) r - remove e - is_empty i - iterator c - clear s - size q - quit m - merge _ - __str__ Command""" #pq = eval('PriorityQueue('+input('pq = PriorityeQueue(')) pq = PriorityQueue(key=lambda x: priorities[x]) priorities = {} while True: print('\n\nPriorities:', priorities) action = prompt.for_char(command_prompt, legal='aurcmpes_.iq') try: if action == 'a': v = prompt.for_string(' Enter value to add') p = prompt.for_int(' Enter its priority') priorities[v] = p # must update first, ,so add knows priority pq.add(v) if action == 'u': v = prompt.for_string(' Enter value to UPDATE') p = prompt.for_int(' Enter its NEW priority') priorities[v] = p # must update first, ,so add knows priority pq.updated(v) elif action == 'r': print(' remove =', pq.remove()) elif action == 'c': pq.clear() priorities.clear() elif action == 'm':
import prompt, math x = prompt.for_int('Enter x') print(x, '!=', math.factorial(x), sep='')
if __name__ == '__main__': import prompt print('Begin testing Modular') command_prompt = \ """\nTesting Modular: Commands Queries Other i - inc v - value . - exec(...) d - dec m - modulus q - quit c - clear _ - __str__ Command""" m = Modular(prompt.for_int('Enter value'),prompt.for_int('Enter modulus')) while True: action = prompt.for_char(command_prompt, legal='idc_.q') try: if action == 'i': m.inc() elif action == 'd': m.dec() elif action == 'c': m.clear() elif action == 'v': print(' value =', m.value()) elif action == 'm': print(' modulus =', m.modulus()) elif action == 'c': m.clear() elif action == '_': print(' str =',m) elif action == '.': exec(prompt.for_string(' Enter command to exec (instance=m)')) elif action == 'q': break else: print(' Unknown command') except AssertionError as report: print(' AssertionError exception caught:', report)
def make(self, db): db.max_use = prompt.for_int("Maximum times to (re)use pixel") #db.max_use = askinteger("Photomosaic_Limited_Repeat","Maximum times to (re)use pixel") return Photomosaic.make(self, db)
return 'B' if (A_games >= 4 and A_games >= B_games + 2) or (B_games >= 4 and B_games >= A_games +2): break def match_winner(percent_A_win_point): A_sets=0 B_sets=0 while True: if game_winner(percent_A_win_point) == 'A': A_sets += 1 else: B_sets += 1 if A_sets >= 4 and A_sets >= B_sets + 2: return 'A' elif B_sets >= 4 and B_sets >= A_sets +2: return 'B' if (A_sets >= 4 and A_sets >= B_sets + 2) or (B_sets >= 4 and B_sets >= A_sets +2): break min_percentage=prompt.for_float('Enter minimum percentage',default=0.45) max_percentage=prompt.for_float('Enter maximum percentage',default=0.55) step_percentage=prompt.for_float('Enter percentage step',default=0.01) matches_to_play=prompt.for_int('Enter matches to play',default=1000) for i in frange(min_percentage,max_percentage,step_percentage): winner = A_win_stats(i,match_winner,matches_to_play) print('with percent_A_win_point =',str(round(i*100,1))+'% A wins',str(round(winner,1))+'% of the matches')
c - clear he - has_edge ion - iterator out_nodes e - edge_value iie - iterator in_edges id - in_degree ion - iterator out_edges od - out_degree r - read d - degree w - write _ - str q - quit Command""" g = eval('Graph('+input('g = Graph(')) while True: action = prompt.for_string(command_prompt, is_legal= \ lambda x : x in 'an ae rn re c nc ec mt hn he e id od d _ . in ie iin ion iie ion r w q rg cc mst sym'.split(' ')) try: if action == 'an': g.add_node(prompt.for_string(' Enter node to add')) elif action == 'ae': g.add_edge(prompt_edge(' Enter edge to add'),prompt.for_int(' Value (int) for edge',is_legal=predicate.is_non_negative)) elif action == 'rn': g.remove_node(prompt.for_string(' Enter node to remove')) elif action == 're': g.remove_edge(prompt_edge(' Enter edge to remove')) elif action == 'c' : g.clear() elif action == 'nc': print(' node_count =',g.node_count()) elif action == 'ec': print(' edge_count =',g.edge_count()) elif action == 'mt' : print(' is_empty =',g.is_empty()) elif action == 'hn': n = prompt.for_string(' Enter node to check') print(' has_node =',g.has_node(n)) elif action == 'he': e = prompt_edge(' Enter edge to check') print(' has_edge =',g.has_edge(e)) elif action == 'e' : e = prompt_edge(' Enter edge to get value')
maxs = len(corpus[k]) if maxs == -1 or len(corpus[k]) > maxs else maxs if len(corpus[k]) == 46: print(k, corpus[k]) print('min/max =', str(mins) + '/' + str(maxs)) def produce_text(corpus, text, count): os = len(text) for i in irange(count): key = tuple(start[-os:]) if key not in corpus: text.append(None) return text start.append(choice(corpus[key])) return start os = prompt.for_int('Enter order statistic', is_legal=lambda x: x >= 1) corpus = read_corpus( os, goody.read_file_values( goody.safe_open('Enter file to process', 'r', 'Cannot find that file'))) print_corpus(corpus) print('\nEnter ' + str(os) + ' words to start with') start = [prompt.for_string('Enter word ' + str(i)) for i in irange(os)] how_many = prompt.for_int('Enter # of words to generate', is_legal=lambda x: x > 0) text = produce_text(corpus, start, how_many) print('Random text =', text)
# # Program History: # 5/18/01: R. Pattis - Operational for 15-100 # 1/25/02: R. Pattis - Added Timer object for timing process # 2/23/13: R. Pattis - Converted to Python using similar libraries # ################################################################################ ################################################################################ import prompt from stopwatch import Stopwatch original_number = prompt.for_int('Enter a positive number', is_legal=(lambda x : x > 0)) is_debugging = prompt.for_bool('Display intermediate results',True) cycle_count = 1 test_number = original_number timer = Stopwatch(running_now = True) while True: if is_debugging: print('Cycle', cycle_count, ': test number is now', test_number) #################### if test_number == 1: break; ####################
return min_len([[d]+smns(amount-d, denom) for d in denom if amount-d >= 0]) # # or, not using min_len # from functools import reduce # return reduce(lambda x,y: x if len(x) < len(y) else y,[[d]+smns(amount-d, denom) for d in denom if amount-d >= 0]) # Returns the smallest postage requiring the most number of stamps # That is, if two amounts require the same number of stamps, the smaller will be returned. def worst(max_amount : int, denom : (int)) -> (int,[int]): def max_len(lol : [[]]): return max((len(s),-sum(s),s) for s in lol)[2] worst = max_len(smns(i,denominations) for i in irange(1,max_amount)) return (sum(worst),worst) if __name__ == '__main__': denominations = (1,6,14,57) amount = prompt.for_int('Enter amount',is_legal = lambda x : x >= 0) print('stamps needed = ', smns(amount,denominations)) # Table of smallest number of stamps needed for each amount of postage # At a certain point, printing this table becomes very slow for i in range(1,100): print('for',i,'stamps needed = ',smns(i,denominations)) # Largest number of stamps for postage from 1 to 100 cents # This function is likely to take too long to executes print(worst(100,denominations))
############################################################################## from goody import irange from dice import Dice from stopwatch import Stopwatch import prompt import predicate win_count = 0 #Win/Lose/Dice Statistics lose_count = 0 dice = Dice([6, 6]) game_timer = Stopwatch() games_to_play = prompt.for_int('Enter # of games to play', is_legal=predicate.is_positive, error_message='an int, but not > 0') game_timer.start() dice.standard_rolls_for_debugging() count = 0 for game in irange(1, games_to_play): #print('game',game) #Each iteration plays one game first_roll = dice.roll().pip_sum() #print(first_roll) #Roll the dice and record their pip sum #Based on firstRoll, decide how to continue: # immediate win/loss or trying to make point if first_roll == 7 or first_roll == 11: win_count += 1 count += 1 #print(first_roll,game) #Win on the first roll with 7 or 11
def make(self,db): db.max_use = prompt.for_int("Maximum times to (re)use pixel") #db.max_use = askinteger("Photomosaic_Limited_Repeat","Maximum times to (re)use pixel") return Photomosaic.make(self,db)
d - degree w - write _ - str q - quit Command""" g = eval('Graph(' + input('g = Graph(')) while True: action = prompt.for_string(command_prompt, is_legal= \ lambda x : x in 'an ae rn re c nc ec mt hn he e id od d _ . in ie iin ion iie ion r w q rg cc mst sym'.split(' ')) try: if action == 'an': g.add_node(prompt.for_string(' Enter node to add')) elif action == 'ae': g.add_edge( prompt_edge(' Enter edge to add'), prompt.for_int(' Value (int) for edge', is_legal=predicate.is_non_negative)) elif action == 'rn': g.remove_node(prompt.for_string(' Enter node to remove')) elif action == 're': g.remove_edge(prompt_edge(' Enter edge to remove')) elif action == 'c': g.clear() elif action == 'nc': print(' node_count =', g.node_count()) elif action == 'ec': print(' edge_count =', g.edge_count()) elif action == 'mt': print(' is_empty =', g.is_empty()) elif action == 'hn': n = prompt.for_string(' Enter node to check')
def get_row_and_column_from_input(game=None): row = prompt.for_int('Enter row', is_legal=zero_and_eight_inclusive) column = prompt.for_int('Enter column', is_legal=zero_and_eight_inclusive) print("Cell ({}, {}) contains: {}".format(row, column, game.get_cell(row, column))) return row, column
# # Program History: # 5/18/01: R. Pattis - Operational for 15-100 # 1/25/02: R. Pattis - Added Timer object for timing process # 2/23/13: R. Pattis - Converted to Python using similar libraries # ################################################################################ ################################################################################ import prompt from stopwatch import Stopwatch original_number = prompt.for_int('Enter a positive number', is_legal=(lambda x : x > 0)) is_debugging = prompt.for_bool('Display intermediate results',True) cycle_count = 1 test_number = original_number timer = Stopwatch(running_now = True) while True: if is_debugging: print('Cycle', cycle_count, ': test number is now', test_number) #################### if test_number == 1336: break ####################
import prompt,predicate import random switch=prompt.for_bool('Switch when asked?') trace=prompt.for_bool('Trace game?') games_played = prompt.for_int('Enter number of games to play',is_legal= predicate.is_positive) count = 0 win = 0 lose = 0 while True: if trace==True: print('Game Played') count += 1 if games_played != 0: prize=random.randint(1,3) contestant =random.randint(1,3) if trace==True: print(' Prize behind door',prize,'/ Contestant chooses door',contestant) while True: exposed=random.randint(1,3) if exposed != prize and exposed != contestant: print(' trying to expose door',exposed) break else: if trace==True: print(' trying to expose door',exposed) if trace==True: print(' Monty exposes door',exposed) if switch==True: while True: