blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3726d482990e901257fb732967456adf30f809eb
probhakarroy/Algorithms-Data-Structures
/Algorithmic Toolbox/week6/max_gold.py
595
3.5625
4
# python3 def max_gold_knapsack(W, n, gold_bars): weight = [[0 for i in range(n+1)] for j in range(W+1)] for i in range(1, n+1): for w in range(1, W+1): weight[w][i] = weight[w][i-1] if gold_bars[i-1] <= w: wgt = weight[w - gold_bars[i-1]][i-1] + gold_bars[i-1] if weight[w][i] < wgt: weight[w][i] = wgt return weight[W][n] if __name__ == "__main__": W, n = [int(i) for i in input().split()] gold_bars = [int(i) for i in input().split()] print(max_gold_knapsack(W, n, gold_bars))
de9098d791092245f5a0118a241bb70b595e303d
2014cdag21/c21
/wsgi/local_data/brython_programs/boolean1.py
543
3.984375
4
''' program: boolean1.py ''' print(None == None) print(None is None) print(True is True) print([] == []) print([] is []) print("Python" is "Python") ''' not 關鍵字使用 ''' grades = ["A", "B", "C", "D", "E", "F"] grade = "L" if grade not in grades: print("unknown grade") ''' and 關鍵字使用 ''' sex = "M" age = 26 if age < 55 and sex == "M": print("a young male") name = "Jack" if ( name == "Robert" or name == "Frank" or name == "Jack" or name == "George" or name == "Luke"): print("This is a male")
7e9cccc710d539dbdedf3eb31651c261d5e8ac76
newbiezz101/Map_for_Malls
/A_Star_Pathfinder/button_drawing_with_drawing_recorded.py
7,956
3.859375
4
import pygame import numpy as np from math import inf # ---------------------- Defining colors --------------------------------------- WALL_COLOR = BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) LIGHT_BLUE = (0, 111, 255) ORANGE = (255, 128, 0) PURPLE = (128, 0, 255) YELLOW = (255, 255, 0) GREY = (143, 143, 143) BROWN = (186, 127, 50) DARK_GREEN = (0, 128, 0) DARKER_GREEN = (0, 50, 0) DARK_BLUE = (0, 0, 128) # -------------------- Class for creating Button --------------------------------- class Button: def __init__(self, color, x, y, width, height, text=''): self.color = color self.x = int(x) self.y = int(y) self.width = int(width) self.height = int(height) self.text = text def draw(self, win, outline=None): # Call this method to draw the Button on the screen if outline: pygame.draw.rect(win, outline, (self.x, self.y, self.width, self.height), 0) pygame.draw.rect(win, self.color, (self.x + 1, self.y + 1, self.width - 1, self.height - 1), 0) if self.text != '': font = pygame.font.SysFont('arial', 12) text = font.render(self.text, 1, (0, 0, 0)) win.blit(text, ( self.x + int(self.width / 2 - text.get_width() / 2), self.y + int(self.height / 2 - text.get_height() / 2))) def isOver(self, pos): # Pos is the mouse position or a tuple of (x,y) coordinates if self.x < pos[0] < self.x + self.width: if self.y < pos[1] < self.y + self.height: return True return False # -------------------------- class end ------------------------------------------------------ # ------------------------- Declaring window properties ------------------------------- SCREEN_HEIGHT = 550 SCREEN_WIDTH = 1254 GRID_WIDTH = 10 GRID_HEIGHT = GRID_WIDTH ROWS = SCREEN_HEIGHT // GRID_HEIGHT COLUMNS = SCREEN_WIDTH // GRID_WIDTH BUTTON_HEIGHT = 50 WINDOW_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT + 2 * BUTTON_HEIGHT) # Defining window size with extra space for buttons # ------------------------- Declaring a 2-dimensional array -------------------------- grid = [] for row in range(ROWS): grid.append([]) for column in range(COLUMNS): grid[row].append(1) print(grid) # ---------------------------- Draw function ------------------------------------------ def draw_square(row, column, color, fill=0): pygame.draw.rect( window, color, [ GRID_WIDTH * column, GRID_HEIGHT * row, GRID_WIDTH, GRID_HEIGHT ], fill ) # ---------------------------- Initialising pygame ------------------------------------ pygame.init() FONT = pygame.font.SysFont('arial', 6) image = pygame.image.load("suriaconcoursemap.png") window = pygame.display.set_mode(WINDOW_SIZE) # setting up the screen window.blit(image, [0, 0]) # loading image on the screen done = False # ---------------------------- Defining & Drawing Buttons ----------------------------------------- Find = Button(GREY, 0, SCREEN_HEIGHT, SCREEN_WIDTH / 3, BUTTON_HEIGHT, 'Find') Clear = Button(GREY, SCREEN_WIDTH / 3, SCREEN_HEIGHT, SCREEN_WIDTH / 3, BUTTON_HEIGHT, 'Clear') Wall = Button(GREY, 2 * SCREEN_WIDTH / 3, SCREEN_HEIGHT, SCREEN_WIDTH / 3, BUTTON_HEIGHT, 'Wall') Start = Button(RED, 0, SCREEN_HEIGHT + BUTTON_HEIGHT, SCREEN_WIDTH / 2, BUTTON_HEIGHT, 'Start Point') End = Button(LIGHT_BLUE, SCREEN_WIDTH / 2, SCREEN_HEIGHT + BUTTON_HEIGHT, SCREEN_WIDTH / 2, BUTTON_HEIGHT, 'End Point') Find.draw(window) Clear.draw(window) Wall.draw(window) Start.draw(window) End.draw(window) pygame.display.flip() # ----------------------------- Drawing walls/maze ----------------------------------------- count = 0 WALLS = 3 file1 = open("saved_wall_1", "rb") file2 = open("saved_wall_2", "rb") file3 = open("saved_wall_3", "rb") wall = [] maze = [] wall_record = [] for i in range(WALLS): wall.append([]) wall[0] = np.load(file1) wall[1] = np.load(file2) wall[2] = np.load(file3) #wall[3] = np.load(file3) #wall[4] = np.load(file4) #wall[5] = np.load(file5) for i in range(WALLS): maze.append(wall[i]) selected_wall = maze[count] # wall coordinates # print(maze[count]) # print(len(maze[count])) # print(len(selected_wall)) # for i in range(len(selected_wall)): # drawing the walls based on the wall coordinates # grid[selected_wall[i][0]][selected_wall[i][1]] = inf # draw_square(selected_wall[i][0], selected_wall[i][1], WALL) # pygame.display.flip() # display the pygame drawing # ------------------------- Main Program Loop Start --------------------------------- while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: #file = open("saved_wall_2", "wb") #np.save(file, wall_record) #file.close() done = True elif event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() # If click is inside window if Wall.isOver(pos): if count < WALLS: print(count) image = pygame.image.load("suriaconcoursemap.png") window.blit(image, [0, 0]) selected_wall = maze[count] # wall coordinates for i in range(len(selected_wall)): # drawing the walls based on the wall coordinates grid[selected_wall[i][0]][selected_wall[i][1]] = inf draw_square(selected_wall[i][0], selected_wall[i][1], WALL_COLOR) pygame.display.flip() # display the pygame drawing count += 1 else: count = 0 print(count) image = pygame.image.load("suriaconcoursemap.png") window.blit(image, [0, 0]) selected_wall = maze[count] # wall coordinates for i in range(len(selected_wall)): # drawing the walls based on the wall coordinates grid[selected_wall[i][0]][selected_wall[i][1]] = inf draw_square(selected_wall[i][0], selected_wall[i][1], WALL_COLOR) pygame.display.flip() # display the pygame drawing count += 1 continue if pos[1] <= SCREEN_HEIGHT - 1 and pos[0] <= SCREEN_WIDTH - 1: # Change the x/y screen coordinates to grid coordinates column_draw = pos[0] // (GRID_WIDTH) row_draw = pos[1] // (GRID_HEIGHT) coor = [row_draw, column_draw] wall_record.append(coor) grid[row_draw][column_draw] = inf draw_square(row_draw, column_draw, WALL_COLOR) pygame.display.flip() print(wall_record) # if (row, column) == START_POINT: # drag_start_point = True # elif (row, column) == END_POINT: # drag_end_point = True # else: # cell_updated = grid[row][column] # if pressed[pygame.K_LCTRL]: # update_cell_to = 'mud' # elif pressed[pygame.K_LALT]: # update_cell_to = 'blank' # maze.remove(coor) # else: # update_cell_to = 'wall' # maze.append(coor) # print(coor) # cell_updated.update(nodetype=update_cell_to) # mouse_drag = True # if algorithm_run and cell_updated.is_path == True: # path_found = update_path() # ------------------------- Main Program Loop End -----------------------------------
0ca60cafaf7c641aa6d2717758cd4eb041bba59a
EvgeniyVashinko/BSUIR-PYTHON-2020
/Solutions/Task2/853506_Evgeniy_Vashinko/lab2/toJson/core.py
1,014
3.578125
4
def obj_to_json(obj, result="") : symbols = list() if type(obj) == dict : result += "{" symbols.append("}") for item in obj : result += obj_to_json(item) result += ": " result += obj_to_json(obj[item]) result += ", " result = result[:len(result) - 2] result += symbols.pop() elif type(obj) == list or type(obj) == tuple : result += "[" symbols.append("]") for item in obj : result += obj_to_json(item) result += ", " result = result[:len(result) - 2] result += symbols.pop() elif type(obj) == str : result += "\"" symbols.append("\"") result += obj result += symbols.pop() elif type(obj) == int or type(obj) == float : result += str(obj) elif obj == True : result += "true" elif obj == False : result += "false" elif obj == None : result += "null" return result
09b13e4cdeab3418bd6fd3360a4415e3336257c9
saturnisbig/euler-python
/pro022.py
1,435
3.9375
4
#!/usr/bin/env python # _*_ coding: utf-8 _*_ """ Problem: Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? Costs: 2015-01-26 08:53:40 - 2015-01-26 14:17:08 """ def first_name_sorted_alph(): with open('p022_names.txt', 'r') as fh: for line in fh: tmp = line.split(',') result = [eval(s) for s in tmp] return sorted(result) def name_scores(name, pos): # A -> 1, B -> 2, start from 1 intA = ord('A') - 1 score = map(ord, name) score = [i-intA for i in score] return sum(score) * pos def names_scores(l): result = 0 for i, name in enumerate(l): score = name_scores(name, i+1) result += score #if name == 'COLIN': # print i+1, name # break return result if __name__ == '__main__': print first_name_sorted_alph()[0] l = first_name_sorted_alph() print name_scores('COLIN', 938) print names_scores(l)
9cf2d4f5a24118a9f3433e57a0edc8eba436bcb4
AAKASH707/PYTHON
/Python Program to Multiply All Items in a Dictionary Example 1.py
632
4.5625
5
# Python Program to Multiply All Items in a Dictionary myDict = {'x': 20, 'y':5, 'z':60} print("Dictionary: ", myDict) total = 1 # Multiply Items for key in myDict: total = total * myDict[key] print("\nAfter Multiplying Items in this Dictionary: ", total) ************************************************************************************************* # Python Program to Multiply All Items in a Dictionary 2 myDict = {'x': 2, 'y':50, 'z':70} print("Dictionary: ", myDict) total = 1 # Multiply Items for i in myDict.values(): total = total * i print("\nAfter Multiplying Items in this Dictionary: ", total)
634bef95e971e68f20af8aefa44422413a1801bb
ftorresi/PythonLearning
/Unit3/ej3.22.py
246
3.5
4
from math import pi, exp, sqrt def gauss(x, m=0, s=1): return exp(-0.5*((x-m)/float(s))**2)/(s*sqrt(2*pi)) print " x gauss(x)" n=40 m=0 s=1 h=10.0*s/n for i in range(n+1): x=m-5*s+h*i print "%7.3f %8.5f" %(x,gauss(x, m, s))
a89f9e73bf870cf9d7f0996d86ab7befae35573d
devendrasingh143/python
/Tuples.py
792
3.890625
4
#this is comment t1 = 'a', print(type(t1),'\n') t = tuple('lupins') print(t,'\n') t = ('a', 'b', 'c', 'd', 'e') print(t[0]) #print index-wise print(t[1:3]) t = ('A',) + t[1:] #modification of tuple print(t,'\n') addr = '[email protected]' uname, domain = addr.split('@') # spliting one word into two print(uname) print(domain,'\n') t = divmod(7, 3) #fnx which retuurn two values at a time using tuples print(t,'\n') quot, rem = divmod(7, 3) #split tupleinto two objects print(quot) print(rem) t = (7, 3) # scatter print(divmod(*t),'\n') # passing two values by one object using *operator s = 'abc' t = [0, 1, 2] print(zip(s, t),'\n') #use of zip fnx, return iterator t = [('a', 0), ('b', 1), ('c', 2)] for letter, number in t: #traverse a list of tuples print(number, letter)
b726895ba2cd3b99e5aeeb505b6e7094c59c1c02
debolina-ca/my-projects
/Python Codes 2/pre_word_function.py
300
4.15625
4
def pre_word(word_1): if word_1.lower().startswith("pre"): if word_1.lower().isalpha(): print("True") else: print("False") else: print("False") word_2 = input("enter a word that starts with \"pre\": ") pre_word(word_2) print()
3032474d26304de91ee98b4b5632fcfd862d9ddc
Kunal352000/python_adv
/17_builtInFunction_eval1.py
372
4.21875
4
""" eval()-->to read the multiple values from the user input at at time either homogenious or hetrogenious elements. -->eval() automatically to perform type conversion based on our input -->in eval(),the input values are seperted by ',' only """ x,y,z=eval(input("Enter x,y,z value: ")) print(x+y+z) """ if we not gives comma we get error"""
18a63525a9083e0a090caf9e21801ec017a0b956
marsmans13/twitter-markov-chains
/markov.py
3,110
3.78125
4
"""Generate Markov text from text files.""" from random import choice import sys import twitter import os def open_and_read_file(file_path): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ text_string = open(file_path).read() return text_string def make_chains(text_string, n_gram): """Take input text as string; return dictionary of Markov chains. A chain will be a key that consists of a tuple of (word1, word2) and the value would be a list of the word(s) that follow those two words in the input text. For example: >>> chains = make_chains("hi there mary hi there juanita") Each bigram (except the last) will be a key in chains: >>> sorted(chains.keys()) [('hi', 'there'), ('mary', 'hi'), ('there', 'mary')] Each item in chains is a list of all possible following words: >>> chains[('hi', 'there')] ['mary', 'juanita'] >>> chains[('there','juanita')] [None] """ words = text_string.split() chains = {} for i in range(len(words) - n_gram): words_key = tuple(words[i:n_gram + i]) add_word = words[i + n_gram] if words_key in chains: chains[words_key].append(add_word) else: chains[words_key] = [add_word] return chains def make_text(chains, n_gram): """Return text from chains.""" words = [] keys_lst = list(chains.keys()) # start point link_tpl = choice(keys_lst) while not link_tpl[0][0].isupper(): link_tpl = choice(keys_lst) words.extend(list(link_tpl)) count_char = 0 while link_tpl in chains and count_char < 260: link_word_str = choice(chains[link_tpl]) words.append(link_word_str) count_char = len(' '.join(words)) # print('count char ', count_char) # if count_char > 279 and link_tpl[-1][-1] in ".!?": # break # else: link_tpl = tuple(words[-n_gram:]) return " ".join(words) def make_tweet(random_text): api = twitter.Api( consumer_key=os.environ['TWITTER_CONSUMER_KEY'], consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'], access_token_key=os.environ['TWITTER_ACCESS_TOKEN_KEY'], access_token_secret=os.environ['TWITTER_ACCESS_TOKEN_SECRET'] ) old_status = api.GetHomeTimeline(count=1) print(old_status[0].text) print('\n') status = api.PostUpdate(random_text) print(status.text) input_path = sys.argv[1] n_gram = int(sys.argv[2]) while True: # Open the file and turn it into one long string input_text = open_and_read_file(input_path) # Get a Markov chain chains = make_chains(input_text, n_gram) # Produce random text random_text = make_text(chains, n_gram) # print(random_text) make_tweet(random_text) user_input = input("Enter to tweet again [q to quit] > ") if user_input.lower() == 'q' or user_input.lower() == 'quit': break
a20c4b15461f71dffba5905779c6ae8516720d53
hrafnkellpalsson/Hypersonic-Shock
/Code/data.py
9,311
3.75
4
""" Arrays of upstream velocity where one line in the array corresponds to the velocity range for a single curve. A function for reading csv files outputted by Engauge. This function is then applied to all the engauge csv files and the resulting data is stored. """ # Python library imports import os # 3rd party imports import numpy def read_engauge_csv(file): """ Read the values from a csv file by Engauge with n lines into a (n-1) by 2 numpy.array. n-1 because we skip the header. :param file: Full path to a csv file outputted by Engauge. :return engauge_values: An (n-1) by 2 numpy.array with numerical value from the Engauge csv file. """ file = open(file) lines = file.readlines() number_of_lines = len(lines) number_of_entries = number_of_lines - 1 engauge_values = numpy.empty([number_of_entries, 2]) for i, line in enumerate(lines[1:]): xyvalues = line.split(',') xvalue = xyvalues[0] xvalue = xvalue.rstrip('\n') xvalue = float(xvalue) engauge_values[i,0] = xvalue yvalue = xyvalues[1] xvalue = yvalue.rstrip('\n') yvalue = float(yvalue) engauge_values[i,1] = yvalue return engauge_values def read_multiple_engauge_csv(dir, filenames): """ Read values from multiple Engauge csv files into a list. :param dir: The directory of the Engauge csv files. :param filenames: A list of filenames of Engauge csv files, including the .csv ending. """ engauge_list = [] for filename in filenames: engauge_values = read_engauge_csv(os.path.join(dir, filename)) engauge_list.append(engauge_values) return engauge_list def read_single_engauge_csv(file): """ Read the values from a csv file by Engauge with n lines into a (n-1) by 2 numpy.array. n-1 because we skip the header. :param file: Full path to a csv file outputted by Engauge. :return engauge_values: An (n-1) by 2 numpy.array with numerical value from the Engauge csv file. """ file = open(file) lines = file.readlines() number_of_lines = len(lines) number_of_entries = number_of_lines - 1 number_of_columns = 13 engauge_values = numpy.empty([number_of_entries, number_of_columns]) for i, line in enumerate(lines[1:]): values = line.split(',') xvalue = values[0] xvalue = xvalue.rstrip('\n') xvalue = float(xvalue) engauge_values[i,0] = xvalue for j in range(number_of_columns-1): data_index = j + 1 if data_index > 12: print 'jasveimertha' data_value = values[data_index] data_value = data_value.rstrip('\n') data_value = float(data_value) engauge_values[i,data_index] = data_value return engauge_values engauge_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','engauge_csv')) csv_filenames_144a = ['144a_35900.csv', '144a_154800.csv', '144a_322900.csv'] engauge_list_144a = read_multiple_engauge_csv(engauge_dir, csv_filenames_144a) csv_filenames_144b = ['144b_35900.csv', '144b_154800.csv', '144b_322900.csv'] engauge_list_144b = read_multiple_engauge_csv(engauge_dir, csv_filenames_144b) csv_filenames_145a = ['145a_35900.csv', '145a_154800.csv', '145a_322900.csv'] engauge_list_145a = read_multiple_engauge_csv(engauge_dir, csv_filenames_145a) csv_filenames_145b = ['145b_35900.csv', '145b_154800.csv', '145b_322900.csv'] engauge_list_145b = read_multiple_engauge_csv(engauge_dir, csv_filenames_145b) step_size = 0.2 u1_vector_feet_35900 = numpy.arange(3.5, 18.3 + step_size/2., step_size) * 1E3 u1_vector_feet_59800 = numpy.arange(3.5, 19.4 + step_size/2., step_size) * 1E3 u1_vector_feet_82200 = numpy.arange(3.5, 20.8 + step_size/2., step_size) * 1E3 u1_vector_feet_100000 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_120300 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_154800 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_173500 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_200100 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_230400 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_259700 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_294800 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_322900 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_144a_feet = [u1_vector_feet_35900, u1_vector_feet_59800, u1_vector_feet_82200, u1_vector_feet_100000, u1_vector_feet_120300, u1_vector_feet_154800, u1_vector_feet_173500, u1_vector_feet_200100, u1_vector_feet_230400, u1_vector_feet_259700, u1_vector_feet_294800, u1_vector_feet_322900] step_size = 0.2 u1_vector_feet_35900 = numpy.arange(16., 28.2 + step_size/2., step_size) * 1E3 u1_vector_feet_59800 = numpy.arange(16., 30. + step_size/2., step_size) * 1E3 u1_vector_feet_82200 = numpy.arange(16., 32.7 + step_size/2., step_size) * 1E3 u1_vector_feet_100000 = numpy.arange(16., 35. + step_size/2., step_size) * 1E3 u1_vector_feet_120300 = numpy.arange(16., 37.9 + step_size/2., step_size) * 1E3 u1_vector_feet_154800 = numpy.arange(16., 41.3 + step_size/2., step_size) * 1E3 u1_vector_feet_173500 = numpy.arange(16., 43.3 + step_size/2., step_size) * 1E3 u1_vector_feet_200100 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_230400 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_259700 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_294800 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_322900 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_144b_feet = [u1_vector_feet_35900, u1_vector_feet_59800, u1_vector_feet_82200, u1_vector_feet_100000, u1_vector_feet_120300, u1_vector_feet_154800, u1_vector_feet_173500, u1_vector_feet_200100, u1_vector_feet_230400, u1_vector_feet_259700, u1_vector_feet_294800, u1_vector_feet_322900] step_size = 0.2 u1_vector_feet_35900 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_59800 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_82200 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_100000 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_120300 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_154800 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_173500 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_200100 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_230400 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_259700 = numpy.arange(3.5, 22. + step_size/2., step_size) * 1E3 u1_vector_feet_294800 = numpy.arange(3.5, 20.9 + step_size/2., step_size) * 1E3 u1_vector_feet_322900 = numpy.arange(3.5, 19.6 + step_size/2., step_size) * 1E3 u1_145a_feet = [u1_vector_feet_35900, u1_vector_feet_59800, u1_vector_feet_82200, u1_vector_feet_100000, u1_vector_feet_120300, u1_vector_feet_154800, u1_vector_feet_173500, u1_vector_feet_200100, u1_vector_feet_230400, u1_vector_feet_259700, u1_vector_feet_294800, u1_vector_feet_322900] step_size = 0.2 u1_vector_feet_35900 = numpy.arange(16., 28.5 + step_size/2., step_size) * 1E3 u1_vector_feet_59800 = numpy.arange(16., 30.5 + step_size/2., step_size) * 1E3 u1_vector_feet_82200 = numpy.arange(16., 33. + step_size/2., step_size) * 1E3 u1_vector_feet_100000 = numpy.arange(16., 35.5 + step_size/2., step_size) * 1E3 u1_vector_feet_120300 = numpy.arange(16., 38.5 + step_size/2., step_size) * 1E3 u1_vector_feet_154800 = numpy.arange(16., 42. + step_size/2., step_size) * 1E3 u1_vector_feet_173500 = numpy.arange(16., 44.5 + step_size/2., step_size) * 1E3 u1_vector_feet_200100 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_230400 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_259700 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_294800 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_vector_feet_322900 = numpy.arange(16., 46. + step_size/2., step_size) * 1E3 u1_145b_feet = [u1_vector_feet_35900, u1_vector_feet_59800, u1_vector_feet_82200, u1_vector_feet_100000, u1_vector_feet_120300, u1_vector_feet_154800, u1_vector_feet_173500, u1_vector_feet_200100, u1_vector_feet_230400, u1_vector_feet_259700, u1_vector_feet_294800, u1_vector_feet_322900]
ade29ac395b873e047be55677bb3300c8ce23d3c
philmtl/youtube-python-tutorial
/if statments.py
131
3.96875
4
is_male = True is_tall = True if is_male or is_tall: print("you are a male or tall") else: print("you are not male")
0c67a54227d6e34ded6728537f8c243a24c94695
shalom-pwc/challenges
/02.Calculate-Remainder/calculate-remainder.py
57
3.5625
4
def remainder(num): return num % 2 print(remainder(5))
2f39869163e4201e5c47af42b0a6ae4f4723cd8b
arshadafzal/Optimization-Test-Problems
/Hartmann3.py
982
3.671875
4
# HARTMANN 3-DIMENSIONAL FUNCTION # Author: Arshad Afzal, IIT Kanpur, India # For Questions/ Comments, please email to [email protected] # Applications (1) Test Problems for Optimization Algorithms # (2) Generate Labelled Data sets for Regression Analysis import numpy as np from math import * def hartmann3(x1, x2, x3): x = [x1, x2, x3] alpha = [1, 1.2, 3.0, 3.2] a = [[3.0, 10, 30], [0.1, 10, 35], [3.0, 10, 30], [0.1, 10, 35]] p = np.dot(pow(10, -4), [[3689, 1170, 2673], [4699, 4387, 7470], [1091, 8732, 5547], [381, 5743, 8828]]) outer_sum = 0 for i in range(4): inner_sum = 0 for j in range(3): inner_sum = inner_sum + a[i][j] * pow((x[j] - p[i][j]), 2) if j == 2: break new = alpha[i] * np.exp(-inner_sum) outer_sum = outer_sum + new if i == 3: break f = -outer_sum return f print(hartmann3(0.5, 0.5, 0.5))
9219ad77a940c3266d7326725f46916317f8c93a
yujikawa/design_pattern
/singleton/sample.py
263
4
4
from singleton import Singleton if __name__ == "__main__": obj1 = Singleton("dog") obj2 = Singleton("cat") if obj1 == obj2: print("obj1 and obj2 are the same instance.") print("obj1.name={} obj2.name={}".format(obj1.name, obj2.name))
55bf213a24e97d2f344ad65e2388a96521b9bc6c
thewritingstew/lpthw
/ex33sd1.py
315
3.796875
4
numbers = [] l_len = 6 def listLoader(nums): i = 0 while i < nums: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i listLoader(l_len) print "The numbers: " for num in numbers: print num
e735adef2309edc03f5bf7f51a8f065ae045e756
gitHirsi/PythonNotes
/001基础/011推导式/02for循环嵌套实现列表推导式.py
203
4.21875
4
""" @author:Hirsi @time:2020/6/1 21:48 """ list1=[] for i in range(1,3): for j in range(3): list1.append((i,j)) print(list1) list2=[(i,j) for i in range(1,3) for j in range(3)] print(list2)
339028bde15f203041efd83454feb2d85cf8a973
HONGghddlwkdrns/cit_JHL
/200206/for.py
92
3.578125
4
number = [5,4,3,2,1] print (len(number)) for jh in number: print(jh) print("발사!")
abb2aa6e99f59695fb21c9120da70fd32a5397c5
weiyuyan/LeetCode
/剑指offer/27. 数值的整数次方.py
1,237
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ShidongDu time:2020/2/14 ''' 实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。   示例 1: 输入: 2.00000, 10 输出: 1024.00000 示例 2: 输入: 2.10000, 3 输出: 9.26100 示例 3: 输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25   说明: -100.0 < x < 100.0 n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 注意:本题与主站 50 题相同:https://leetcode-cn.com/problems/powx-n/ ''' class Solution: def myPow(self, x: float, n: int) -> float: if x == 0: return 0 if x == 1: return 1 if x == -1: return 1 if n%2==0 else -1 if n < 0: tmp = 1 for i in range(-n): tmp *= 1/x if tmp == 0.0: return float('inf') if x>0 else float('-inf') return tmp if n > 0: tmp = 1 for i in range(n): tmp *= x if tmp == 0.0: return 0.0 return tmp if n == 0: return 1 solution = Solution() res = solution.myPow(-2.00000, -214999990) print(res)
83af0ce9ea9b9f39203fd5a14aa049b0be1de7b8
lezelelena/python
/shufflePO_noseed.py
685
3.78125
4
#!/usr/local/bin/python3 import random import os l = [] try: gr_c = int(input("How many teams participating? ")) except ValueError: print("Not a digit, please try again"); exit() while gr_c < 2 or gr_c % 2 != 0: print("Wrong amount of teams"); gr_c = int(input("How many teams participating? ")) for i in range (1, gr_c+1): inp = input ("Input %i team: " % (i)) while inp=="": print("Blank input, try again?"); inp = input("Input %i team: " % (i)) if inp != '': l.append(inp) random.shuffle (l) print() while l: pop1 = l.pop(); pop2 = l.pop() random.shuffle (l) print(str(pop1) + " - " + str(pop2)) print() input("Press <Enter> to exit the app\n")
d5d978289abcebd755cc71e6de790d41a483514b
hampusrosvall/leetcode
/merge_two_linked_lists.py
1,075
3.859375
4
class ListNode: def __init__(self, value): self.val = value self.next = None def merge_lists(l1: ListNode, l2: ListNode): dummy_head = ListNode(0) curr_first = l1 curr_second = l2 node = dummy_head while curr_first and curr_second: if curr_first.val <= curr_second.val: node.next = ListNode(curr_first.val) curr_first = curr_first.next else: node.next = ListNode(curr_second.val) curr_second = curr_second.next node = node.next while curr_first: node.next = ListNode(curr_first.val) node = node.next curr_first = curr_first.next while curr_second: node.next = ListNode(curr_second.val) node = node.next curr_second = curr_second.next return dummy_head.next l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) head = merge_lists(l1, l2) while head: print(head.val) head = head.next
f25bb64b8885e3c5f99445961addc7e476851714
anguillanneuf/bigO
/22 coin.py
1,869
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 11 17:37:31 2017 @author: tz input --- amount = 4 denominations = [1,2,3] output --- number of ways = 4 0 1 2 3 4 [0, 0, 0, 0, 0] coint = 1 range(1,5) [1, 0, 0, 0, 0] [1, 1, 0, 0, 0] [1, 1, 1, 0, 0] [1, 1, 1, 1, 0] [1, 1, 1, 1, 1] coin = 2 range(2,5) l[2] += l[0] [1, 1, 2, 1, 1] l[3] += l[1] [1, 1, 2, 2, 1] l[4] += l[2] [1, 1, 2, 2, 3] coin = 3 range(3,5) l[3] += l[0] [1, 1, 2, 3, 3] l[4] += l[1] [1, 1, 2, 3, 4] """ def change_possibilities_bottom_up(amount, denominations): ways_of_doing_n_cents = [0] * (amount + 1) ways_of_doing_n_cents[0] = 1 #print(ways_of_doing_n_cents) for coin in denominations: for higher_amount in range(coin, amount + 1): higher_amount_remainder = higher_amount - coin ways_of_doing_n_cents[higher_amount] += \ ways_of_doing_n_cents[higher_amount_remainder] #print(ways_of_doing_n_cents) return ways_of_doing_n_cents[amount] print(change_possibilities_bottom_up(8, [1,2,3])) def coins(amount, c): # top down recursion global cnt cnt = 0 def _coins(rem, i, c): global cnt if rem == 0: cnt+=1 return # return is a formal exit if i <= len(c)-1: K = rem//c[i] for k in range(K, -1, -1): _coins(rem-k*c[i], i+1, c) _coins(amount, 0, c) return cnt def coins_it(amount, c): # bottom up iterative mem = [0 for _ in range(amount+1)] for v in sorted(c): for u in range(v, amount+1): if u == v: mem[v] += 1 else: mem[u] += mem[u-v] return mem[amount] print(coins(10, [5,2,1])) print(coins_it(10, [5,2,1]))
15d5fd943024946a8295f2392d796be8efede53d
Aleksandra-AK/Modul---13
/modul_13.py
390
3.765625
4
ticket = int(input('Введите количество билетов: ')) s = 0 for i in range(1, ticket+1): age = int(input('Введите возраст: ')) if age < 18: s += 0 elif 25 > age >= 18: s += 990 elif age >= 25: s += 1390 print("Сумма заказа: ", s) if ticket > 3: print('Сумма со скидкой: ', s*0.9)
76f4105eff1740e4e0c6667756acd13701d82694
CKMaxwell/Python_online_challenge
/edabit/4_Hard/Words_With_Duplicate_Letters.py
407
3.78125
4
# 20200909 - Words With Duplicate Letters def no_duplicate_letters(phrase): phrase = phrase.lower() word = map(list, phrase.split( )) for i in word: word_set = set(i) word_list = list(i) if len(word_set) == len(word_list): continue else: return False break return True print(no_duplicate_letters("Look before you leap."))
0ea72852820a63c257998e06998f5ec5706e762b
shelldweller/Mars-Rover
/mars_rover/rover.py
2,271
3.671875
4
import logging from .datastructures import Point class Rover(): DIRECTIONS = ('N', 'E', 'S', 'W') def __init__(self, max_point: Point, landing_point: Point, direction: str, name: str): assert direction in self.DIRECTIONS, \ f'Invalid direction {direction}; expected one of {self.DIRECTIONS}' assert max_point.x > 0 and max_point and max_point.y > 0, \ f'Invalid max point {max_point}' self.min_point = Point(0, 0) self.max_point = max_point self.current_point = landing_point self.current_direction = direction self.name = name self.logger = logging.getLogger(name) def can_move(self) -> bool: ''' Returns True if Rover can move in the current direction and False otherwise. ''' if self.current_direction == 'N': return self.current_point.y < self.max_point.y if self.current_direction == 'E': return self.current_point.x < self.max_point.x if self.current_direction == 'S': return self.current_point.y > self.min_point.y if self.current_direction == 'W': return self.current_point.x > self.min_point.x return False def turn_right(self) -> None: ''' Turns rover right: N -> E -> S -> W -> N. Changes rover's current_direction. ''' i = (self.DIRECTIONS.index(self.current_direction) + 1) % len(self.DIRECTIONS) self.current_direction = self.DIRECTIONS[i] def turn_left(self) -> None: ''' Turns rover left: N <- E <- S <- W <- N. Changes rover's current_direction. ''' i = self.DIRECTIONS.index(self.current_direction) - 1 self.current_direction = self.DIRECTIONS[i] def move(self) -> None: if self.can_move(): if self.current_direction == 'N': self.current_point.y += 1 elif self.current_direction == 'E': self.current_point.x += 1 elif self.current_direction == 'S': self.current_point.y -= 1 elif self.current_direction == 'W': self.current_point.x -= 1 else: self.logger.error(f'Cannot move from {self.current_point} in the direction of {self.current_direction}')
924b0b9a8dd96b08090a076be67658b8f8c4018c
YuanyuanZh/MapReduce
/hamming.py
3,880
3.515625
4
class Hamming(object): def get_hamming_code(self,binary_str): binary_list = list(binary_str) for i in range(4): binary_list.insert(2**i-1,0) sum =0 for j in [0,2,4,6,8,10]: if binary_list[j] == '1': sum +=1 binary_list[0] = str(sum%2) sum = 0 for j in [1,2,5,6,9,10]: if binary_list[j] == '1': sum += 1 binary_list[1] = str(sum%2) sum = 0; for j in [3,4,5,6,11]: if binary_list[j] == '1': sum +=1 binary_list[3] = str(sum%2) sum = 0; for j in [7,8,9,10,11]: if binary_list[j] == '1': sum +=1 binary_list[7] = str(sum%2) b_str = ''.join(binary_list) return b_str def get_ascii(self,byte_str): binary_list = list(byte_str) for i in [7,3,1,0]: binary_list = binary_list[:i]+binary_list[i+1:] b_str = ''.join(binary_list) value = int(b_str,2) c = chr(value) return chr(value) class HammingEncoder(Hamming): def encode(self,text): hamming = '' for c in text: binary_str = "{0:08b}".format(ord(c)) hamming += self.get_hamming_code(binary_str) return hamming class HammingDecoder(Hamming): def decode(self, text): """Return decoded text as a string.""" out_string = '' while len(text) > 0: if text[0] == '\n': break byte_str = text[0:12] text = text[12:] out_string += self.get_ascii(byte_str) return out_string class HammingChecker(Hamming): def check(self, text): pos =0 positions = [] l = len(text) while(len(text)>0): if text[0] == '\n': break byte_str = text[0:12] text = text[12:] c = self.get_ascii(byte_str) binary_str = "{0:08b}".format(ord(c)) p = self.get_hamming_code(binary_str) for i in [0,1,3,7]: if p[i] != byte_str[i]: positions += [pos] break pos += 1 if positions: return "next "+str(l/12)+" bytes"+':error at byte'+str(positions) else: return "next "+str(l/12)+" bytes"+"no error" class HammingFixer(Hamming): def fix(self,text): fix_text = '' while(len(text)>0): if text[0] == '\n': break byte_str = text[0:12] text = text[12:] #temp = byte_str[0:12] c = self.get_ascii(byte_str) binary_str = "{0:08b}".format(ord(c)) p = self.get_hamming_code(binary_str) pos = 0 b =0 for i in [0,1,3,7]: if p[i] != byte_str[i]: b =1 pos += i+1 if b==1: byte_list = list(byte_str) if byte_list[pos-1] == '0': byte_list[pos-1] = '1' else: byte_list[pos-1] = '0' t = ''.join(byte_list) fix_text += t else: fix_text += byte_str return fix_text class HammingError(Hamming): def createError(self,pos,text): if pos == None or pos <0: return text else: byte_pos = pos/12 bit_pos = pos%12 target_str = text[byte_pos * 12:(byte_pos+1)*12] target_list = list(target_str) if target_list[bit_pos-1] =='1': target_list[bit_pos-1] ='0' else: target_list[bit_pos-1] ='1' error_str = ''.join(target_list) rst = text[:byte_pos * 12]+error_str+text[(byte_pos+1)*12:] return rst
3e60aca70015f4a5ed83ad5e2b9b343a1bcecb5b
GanGaRoo/Langtangen
/Chapter_one/Formulas.py
691
3.953125
4
# -*- coding: utf-8 -*- import math print("The First Programming Encounter: a Formula") v0 = initial_velocity = 5 g = acceleration_of_gravity = 9.81 TIME = 0.6 VerticalPositionOfBall = initial_velocity*TIME - \ 0.5*acceleration_of_gravity*TIME**2 print("The Vertical Position Of The Ball is {} meters".format(VerticalPositionOfBall)) yc = 0.2 t1 = (v0 - math.sqrt(v0**2 - 2*g*yc))/g t2 = (v0 + math.sqrt(v0**2 - 2*g*yc))/g print('At t={:.2f} s and {:.2f} s, the height is {} m.'.format(t1, t2, yc)) # Calculation of sinh using exponential function x = 2*math.pi r1 = math.sinh(x) r2 = 0.5 * (math.exp(x) - math.exp(-x)) r3 = 0.5 * (math.e**(x) - math.e**(-x)) print (r1, r2, r3)
3861e45d9fe4f61a67a76182c63a7d9ba5fb0c08
ChloeDumit/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
986
4.03125
4
#!/usr/bin/python3 """Divide all elements of a matrix """ def matrix_divided(matrix, div): """ Function to divide elements of a matrix """ e1 = "Each row of the matrix must have the same size" e2 = "matrix must be a matrix (list of lists) of integers/floats" new_matrix = list(map(list, matrix)) large = 0 if div == 0: raise ZeroDivisionError("division by zero") elif type(div) is not int and type(div) is not float: raise TypeError("div must be a number") for row in matrix: for col in row: if large == 0: large = len(row) elif large != len(row): raise TypeError(e1) for i in range(len(matrix)): for j in range(len(matrix[i])): if type(new_matrix[i][j]) is not int: if type(new_matrix[i][j]) is not float: raise TypeError(e2) new_matrix[i][j] = round(matrix[i][j]/div, 2) return new_matrix
99ddf74ccfdb28a3b1d0e025e550e7b7b1b5233f
saradbb/Etch-A-Sketch
/main.py
1,248
4.125
4
from turtle import Turtle,Screen #Simple Etch-A_Sketch Using Turtle # KEYS AND WHAT THEY DO: # W Move forward # S Move Backward # A counter-clockwise turn # D clockwise turn # C clear sketch_turtle =Turtle() def initialize_position(): sketch_turtle.setheading(0) sketch_turtle.penup() sketch_turtle.goto(START_X_POS, START_Y_POS) sketch_turtle.pendown() sketch_turtle.shape('turtle') screen = Screen() DISTANCE = 10 #The distance turtle draws in one key-press ANGLE = 10 #The angle turtle turns when keys pressed FORWARD_KEY = 'w' BACKWARD_KEY = 's' CLOCKWISE_KEY = 'd' COUNTERCLOCK_KEY = 'a' START_X_POS = 25 START_Y_POS = 25 CLEAR_KEY = 'c' initialize_position() def forward(): sketch_turtle.forward(DISTANCE) def backward(): sketch_turtle.forward(-DISTANCE) def clockwise(): sketch_turtle.right(ANGLE) def counterclockwise(): sketch_turtle.left(ANGLE) def clear(): sketch_turtle.clear() initialize_position() screen.listen() screen.onkey(key = FORWARD_KEY,fun = forward) screen.onkey(key = BACKWARD_KEY,fun = backward) screen.onkey(key = CLOCKWISE_KEY, fun = clockwise ) screen.onkey(key = COUNTERCLOCK_KEY, fun = counterclockwise) screen.onkey(key = CLEAR_KEY, fun = clear) screen.exitonclick()
32e0d19f0fcf66f49ba8f8b468e1b65afdaa08b9
9Brothers/Learn.Python
/06_files.py
248
3.734375
4
# my_file = open("files/texto.txt") # text = my_file.read() # print(text) # text = my_file.readline() # print(text) # my_file.seek(0) # text = my_file.readline() # print(text) my_file = open("files/text.txt") for line in my_file: print(line)
a1424111bb75dfcd60054d47a67c91ed53a53880
vtrbtf/hackerrank-algorithms
/implementation/kangaroo/main.py
242
3.640625
4
#!/usr/bin/env python3 x1, v1, x2, v2 = [int(n) for n in input('').split(' ')] if (x1 > x2 and v1 >= v2) or (x2 > x1 and v2 >= v1): print("NO") else: if (x1 - x2) % (v2 - v1) == 0: print ("YES") else: print ("NO")
11d7feae06b0316b2ef17d3dc7339d57587f602a
iproduct/intro-python
/acad_2022_01_intro/comprehensions.py
984
3.75
4
from functools import reduce from math import sqrt if __name__ == "__main__": l = [x * x for x in range(1, 11)] print(l) def is_prime(n): for i in range(2, int(sqrt(n))): if n % i == 0: return False return True n = 10 primes= [i for i in range(2, n + 1) if is_prime(i)] primes= [i*j for i in range(2, n + 1) for j in range(2, n + 1) ] primes= {j: [i*j for i in range(2, n + 1)] for j in range(2, n + 1) } print(primes) fact = {i : reduce(lambda a, x: a * x, (j for j in range(1, i+1))) for i in range(1, n+1)} def is_palindrom(s): i = 0 half = len(s) // 2 while i < half: if s[i] != s[-i-1]: return False i += 1 return True print(is_palindrom("abcdcba")) print(is_palindrom("abcdcab")) words = ['abcdcba', 'abcdcab', 'neveroddoreven', 'neverevenorodd'] palindroms = (words) #TODO print(list(palindroms))
d097713c99b1fbb893212b79d5dd528220235d5c
ironsubhajit/Udemy_course
/DBMS/utils/database_sql.py
1,000
3.578125
4
from utils.database_connections import DatabaseConnections def create_book_table(): with DatabaseConnections('data.db') as cursor: cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, read integer)') def get_all_books(): with DatabaseConnections('data.db') as cursor: cursor.execute('SELECT * FROM books') books = [{'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor .fetchall()] # [(name, author, read), ...] return books def add_book(name, author): with DatabaseConnections('data.db') as cursor: cursor.execute('INSERT INTO books VALUES(?, ?, 0)', (name, author)) def mark_book_as_read(find_name): with DatabaseConnections('data.db') as cursor: cursor.execute('UPDATE books SET read=1 WHERE name=?', (find_name,)) def delete_book(delete_book_name): with DatabaseConnections('data.db') as cursor: cursor.execute('DELETE FROM books WHERE name=?', (delete_book_name,))
0cc99bb427495d9efe7773a0b4e8f952d04f24e4
Gnorbi951/4th_battleship
/final_battleship_2_player.py
12,801
3.625
4
import random def ai_user_input(player_tips=None): # need of checking the already guessed values isItGuessed = True # init while isItGuessed == True: row_input = True col_input = True while col_input: try: col = int(input("Column: ")) if col >= 10 or col < 1: raise Exception col_input = False except: print("Input numbers between 1 and 9") continue while row_input: try: row = int(input("Row: ")) if row >= 10 or row < 1: raise Exception row_input = False except: print("Input numbers between 1 and 9") continue isItGuessed = is_it_guessed(player_tips, row, col) if isItGuessed == True: print("You already guessed the filed", col, row,) store_tips(player_tips, row, col) # store the guessed numbers in pairs return row, col def user_input(): # need of checking the already guessed values row_input = True col_input = True while col_input: try: col = int(input("Column: ")) if col >= 10 or col < 1: raise Exception col_input = False except: print("Input numbers between 1 and 9") continue while row_input: try: row = int(input("Row: ")) if row >= 10 or row < 1: raise Exception row_input = False except: print("Input numbers between 1 and 9") continue return row, col def create_table(): i = 0 my_array = [] # tömböt row-ra table = [] while i < 9: j = 0 my_array = [] while j < 9: my_array.append(0) j += 1 table.append(my_array) i += 1 return table def print_table(table): mytable = table i = 0 print(" 1 2 3 4 5 6 7 8 9") while i < 9: print(i+1, *mytable[i]) i += 1 def check_for_hit(background_map, row, col): if background_map[row-1][col-1] != 0: return True print("its a hit") else: return False def ai_value_change(main_map, background_map, row, col, list_hits): checkForHit = check_for_hit(background_map, row, col) if checkForHit == True: # strig literal kimehet akár globális változóba main_map[row-1][col-1] = "x" win_condition_change(list_hits, background_map[row-1][col-1]) print("Hit") elif checkForHit == False: main_map[row-1][col-1] = "M" print("Miss") return main_map # nem feltétlenül kell def value_change(main_map, background_map, row, col, player_hits): checkForHit = check_for_hit(background_map, row, col) if checkForHit == True: # strig literal kimehet akár globális változóba main_map[row-1][col-1] = "x" player_hits += 1 print("You've hit the ship") elif checkForHit == False: main_map[row-1][col-1] = "M" print("You missed") return main_map # nem feltétlenül kell def random_generator(size): rotation = random.randint(0, 1) if rotation == 0 and size == 3: positionH = random.randint(0, 6) positionV = random.randint(0, 8) elif rotation == 0 and size == 4: positionH = random.randint(0, 5) positionV = random.randint(0, 8) elif rotation == 1 and size == 3: positionH = random.randint(0, 8) positionV = random.randint(0, 6) elif rotation == 1 and size == 4: positionH = random.randint(0, 8) # sizeot fel lehet használni a tiltáshoz positionV = random.randint(0, 5) return rotation, positionH, positionV def check_for_ships(shipParameter, backgroundList): # randomshipposition placable = True j = 0 while j < shipParameter[1]: if shipParameter[2] == 0: if backgroundList[shipParameter[3]+j][shipParameter[4]] != 0: placable = False elif shipParameter[2] == 1: if backgroundList[shipParameter[3]][shipParameter[4]+j] != 0: placable = False j += 1 return placable def place_ships(shipParameter, backgroundList): # randomshipposition k = 0 while k < shipParameter[1]: if shipParameter[2] == 0: backgroundList[shipParameter[3]+k][shipParameter[4] ] = shipParameter[0] # ez írja át a 0-t IDra elif shipParameter[2] == 1: backgroundList[shipParameter[3] ][shipParameter[4]+k] = shipParameter[0] k += 1 def ship_parameter(id, size): rotation, positionH, positionV = random_generator(size) shipList = [id, size, rotation, positionH, positionV] return shipList def random_ship_position(): backgroundList = create_table() i = 0 while i < 4: shipParameter = [] if i < 2: size = 3 shipParameter = ship_parameter(i+1, size) else: size = 4 shipParameter = ship_parameter(i+1, size) if check_for_ships(shipParameter, backgroundList) == True: place_ships(shipParameter, backgroundList) else: i -= 1 i += 1 return backgroundList def win_condition(hits_list, win_condition_numbers, winner): sorted_list = sorted(hits_list) if sorted_list == win_condition_numbers: print(winner, " won the game") return True else: return False def whose_turn_is_it(current_turn): if current_turn % 2 == 0: return "Player" else: return "AI" # PhaseTwo(The player or the AI guess a coordinate based on whose turn is it) def turns(whose_turn_is_it, player_tips, main_map, background_map, player_hits): if whose_turn_is_it == "Player": print("Players Turn") row, col = ai_user_input(player_tips) print_table(ai_value_change( main_map, background_map, row, col, player_hits)) elif whose_turn_is_it == "AI": print("AI-s turn") row = random.randint(1, 9) col = random.randint(1, 9) print_table(ai_value_change( main_map, background_map, row, col, player_hits)) def player_placement_input(id, size): # return shiplist with 5 items row_input = True col_input = True pos_input = True ship_list = [id, size, 0, 0, 0, ] print("Insert your ship coordinates!") while pos_input: try: ship_list[2] = int(input("H = 1, V = 0: ")) if ship_list[2] == 0 or ship_list[2] == 1: pos_input = False else: raise Exception except: print("Type 0 or 1") while col_input: try: ship_list[4] = int(input("Column: ")) if ship_list[2] == 0: if ship_list[4] >= 10 or ship_list[4] < 1: raise Exception ship_list[4] = ship_list[4] - 1 col_input = False elif ship_list[2] == 1: if ship_list[4] >= 10-ship_list[1]+1 or ship_list[4] < 1: raise Exception ship_list[4] = ship_list[4] - 1 col_input = False except: if ship_list[2] == 0: print("Input numbers between 1 and 9") continue elif ship_list[2] == 1: print("Input numbers between 1 and ", 10-ship_list[1]) while row_input: try: if ship_list[2] == 0: ship_list[3] = int(input("Row: ")) if ship_list[3] >= 10-ship_list[1]+1 or ship_list[3] < 1: raise Exception ship_list[3] = ship_list[3] - 1 row_input = False elif ship_list[2] == 1: ship_list[3] = int(input("Row: ")) if ship_list[3] >= 10 or ship_list[3] < 1: raise Exception ship_list[3] = ship_list[3] - 1 row_input = False except: if ship_list[2] == 0: print("Input numbers between 1 and ", 10-ship_list[1]) continue if ship_list[2] == 1: print("Input numbers between 1 and 9") continue return ship_list def player_ship_placement(): # Bug = merge backgroundList = create_table() i = 0 while i < 4: shipParameter = [] if i < 2: size = 3 shipParameter = player_placement_input(i+1, size) # place_ships(shipParameter,backgroundList) else: size = 4 shipParameter = player_placement_input(i+1, size) # place_ships(shipParameter,backgroundList) if check_for_ships(shipParameter, backgroundList) == True: place_ships(shipParameter, backgroundList) else: i -= 1 print("That field is already taken") i += 1 print_table(backgroundList) return backgroundList def is_it_guessed(list_tips, col, row): # Check if the coordinates are guessed already guessed_pair = (col, row) isItGuessed = False i = 0 while i < len(list_tips): if guessed_pair == list_tips[i]: isItGuessed = True i += 1 return isItGuessed def store_tips(list_tips, col, row): # Store the guessed values in pairs tmp_pair = (col, row) if tmp_pair not in list_tips: list_tips.append(tmp_pair) def win_condition_change(list_hits, id_of_ship): list_hits.append(id_of_ship) print(list_hits) def player_vs_ai(): current_turn = 0 win_condition_numbers = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4] player_tips = [] player_hits = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4] ai_tips = [] ai_hits = [] main_map = create_table() background_map = random_ship_position() ai_map = create_table() ai_background = player_ship_placement() print("Background table test") print("AI's table") print_table(background_map) print("Player's table") print_table(ai_background) print("\n") someone_win = False while someone_win == False: turns(whose_turn_is_it(current_turn), player_tips, main_map, background_map, player_hits) someone_win = win_condition( player_hits, win_condition_numbers, "Player") if someone_win == True: break current_turn += 1 turns(whose_turn_is_it(current_turn), ai_tips, ai_map, ai_background, ai_hits) someone_win = win_condition(ai_hits, win_condition_numbers, "Enemy") if someone_win == True: break current_turn += 1 print("") def player_vs_player(): player_n_hits = 0 player2_n_hits = 0 main_map = create_table() player2_main_map = create_table() print("Player 1! Place your ships") player2_background_map = player_ship_placement() print("Player 2! Place your ships") background_map = player_ship_placement() print_table(main_map) while True: print("Player 1's turn") row, col = user_input() print_table(value_change( main_map, player2_background_map, row, col, player_n_hits)) if check_for_hit(player2_background_map, row, col) == True: player_n_hits += 1 if player_n_hits == 14: print("Player1 won the game!") break print("Player 2's turn") row2, col2 = user_input() print_table(value_change(player2_main_map, player2_background_map, row2, col2, player2_n_hits)) if check_for_hit(background_map, row2, col2) == True: player2_n_hits += 1 if player2_n_hits == 14: print("Player 2 won the game!") break def menu(): choose = True answer = "" while choose: print("1. PvP mode\n2. PvE mode\n3. Exit") press = int(input()) if press == 1: player_vs_player() elif press == 2: player_vs_ai() elif press == 3: while answer != "yes" or answer != "no": answer = input("Are you sure you quit? yes/no \n") if answer == "yes": print("Good Bye!") exit() elif answer == "no": break else: print("Please enter a number between 1 and 3") def main(): while True: menu() main()
655202b53dec6e356d3b8cdf68235ea1968e6bc1
You-NeverKnow/Cracking-the-coding-interview
/2/2.6.py
3,499
3.8125
4
from Node import Node # -----------------------------------------------------------------------------| def main(): """ """ _list = Node().init_from_list(list("CAS")) print(is_palindrome_recursive(_list)) print(is_palindrome_stack(_list)) print(is_palindrome(_list)) # -----------------------------------------------------------------------------| # -----------------------------------------------------------------------------| def is_palindrome_recursive(head: Node) -> bool: """ """ if not head: return True _, is_palindrome_ = _is_palindrome(head, len(head)) return is_palindrome_ # -----------------------------------------------------------------------------| # -----------------------------------------------------------------------------| def _is_palindrome(head: Node, length: int) -> (Node, bool): """ """ if length == 1: return head.next_node, True elif length == 2: return head.next_node.next_node, head.value == head.next_node.value next_node, is_palindrome_ = _is_palindrome(head.next_node, length - 2) return next_node.next_node, is_palindrome_ and head.value == next_node.value # -----------------------------------------------------------------------------| # -----------------------------------------------------------------------------| def is_palindrome_stack(head: Node) -> bool: """ """ stack = [] dummy_head = Node(next_node = head) fast = dummy_head slow = dummy_head while fast.next_node: slow = slow.next_node fast = fast.next_node if fast.next_node: fast = fast.next_node slow = slow.next_node while slow: stack.append(slow.value) slow = slow.next_node comparator = dummy_head.next_node while stack: if comparator.value != stack.pop(): return False comparator = comparator.next_node return True # -----------------------------------------------------------------------------| # -----------------------------------------------------------------------------| def is_palindrome(head: Node) -> bool: """ """ if not head: return True reverse_list = reverse(deep_copy_linked_list(head)) while head and reverse_list: if head.value != reverse_list.value: return False head = head.next_node reverse_list = reverse_list.next_node return True # -----------------------------------------------------------------------------| # -----------------------------------------------------------------------------| def deep_copy_linked_list(head: Node) -> Node: """ """ dummy = Node() list_copy = dummy while head: list_copy.next_node = Node(head.value) head = head.next_node list_copy = list_copy.next_node return dummy.next_node # -----------------------------------------------------------------------------| # -----------------------------------------------------------------------------| def reverse(head: Node) -> Node: """ """ if not head: return head previous = None current = head while current: next_node = current.next_node current.next_node = previous previous = current current = next_node return previous # -----------------------------------------------------------------------------| if __name__ == '__main__': main()
c527a2d7aa83ba214a6cace7b78ed76e2a8a6712
IgoAlgo/Problem-Solving
/choieungi/NewThisIsCT/12_12 기둥과 보.py
868
3.765625
4
def check_possible(ans): for x, y, installed in ans: if installed == 0: if y == 0 or [x - 1, y, 1] in ans or [x, y, 1] in ans or [x, y - 1, 0] in ans: continue return False elif installed == 1: if [x, y - 1, 0] in ans or [x + 1, y - 1, 0] in ans or ([x - 1, y, 1] in ans and [x + 1, y, 1] in ans): continue return False return True def solution(n, build_frame): answer = [] for x, y, stuff, operate in build_frame: if operate == 0: answer.remove([x, y, stuff]) if not check_possible(answer): answer.append([x, y, stuff]) elif operate == 1: answer.append([x, y, stuff]) if not check_possible(answer): answer.remove([x, y, stuff]) return sorted(answer)
66e54512575aa689c4f4626b5f8627e2f0255ad9
jamal357/hello-world
/flip_clock.py
1,935
4.21875
4
import time secsnow = 0 def twentyfourh(): hoursnow = int(input("Enter the current hour in 24 hour format")) minutenow = int(input("Enter the current minute")) seconds = 0 for hours in range (24): hours = hours + hoursnow for mins in range(60): mins = mins + minutenow seconds = seconds + secsnow for seconds in range(60): print(hours, ":", mins, ":", seconds) time.sleep(1) def twelvehour(): hoursnow = int(input("Enter the current hour in 12 hour format")) minutenow = int(input("Enter the current minute")) seconds = 0 for hours in range (12): hours = hours + hoursnow for mins in range(60): mins = mins + minutenow seconds = seconds + secsnow for seconds in range(60): print(hours, ":", mins, ":", seconds) time.sleep(1) ask = input("Would you like your flip clock in a 24 hour version? y/n") if ask == "y": twentyfourh() else: twelvehour() #We are aiming to produce this: https://www.youtube.com/watch?v=rbOStasEUV0 #1) Run the program #2) Get this to display the time from 0:00 to 23:59. #Make sure it does not display as 0 0 or 0 1 as these are not correct times #it should be 0:00, 0:01 etc #3) Give them the option to display in 24hrs or (12hr with AM and PM) #4) Write each version of the clock in separate procedures and call #each one when requested #5) Add in seconds hint: nest another for loop #6) Use time.sleep() to get it to be pseudo-accurate in incrementing the seconds. If you are in IDLE, use Ctrl-C to break this when testing #7) Ask the user to enter the current time and then keep outputting the #time from then onwards #Build your own calendar to output the correct dates in order. #You will need to use lots of if statements as each month has different days.
d568b4ec4e8e110d4206ffaa0602d49fd9df2682
sureshyhap/Python-Crash-Course
/Chapter 9/8/privileges.py
1,506
3.703125
4
class User(): """User profile""" def __init__(self, first, last, nick, country, age): self.first_name = first self.last_name = last self.nickname = nick self.country = country self.age = age def describe_user(self): print(self.first_name.title() + " " + self.last_name.title() + ", a.k.a. " + self.nickname + " is from " + self.country + " and is " + str(self.age) + " years old.") def greet_user(self): print("Hello " + self.first_name.title()) class Privileges(): def __init__(self, privileges= ["can add post", "can delete post", "can ban user"]): self.privileges = privileges def show_privileges(self): for privilege in self.privileges: print(privilege.title()) class Admin(User): def __init__(self, first, last, nick, country, age): super(Admin, self).__init__(first, last, nick, country, age) self.privileges = Privileges() user1 = User("Suresh", "Yhap", "SkyTree", "America", 26) user2 = User("Joseph", "Michael", "fwesh", "America", 26) user1.describe_user() user1.greet_user() print() user2.describe_user() user2.greet_user() """ privileges = ["can add post", "can delete post", "can ban user"] admin = Admin("Suresh", "Yhap", "Forte", "Japan", 26, privileges) admin.show_privileges() """ admin = Admin("Suresh", "Yhap", "Forte", "Japan", 26) admin.privileges.show_privileges()
6a3aee8c9dc30573306576fc20dc3ec6559f695c
FreshOats/RollerCoaster
/Steel_and_Wood.py
2,027
3.671875
4
import pandas as pd import matplotlib.pyplot as plt wood = pd.read_csv('Golden_Ticket_Award_Winners_Wood.csv') steel = pd.read_csv('Golden_Ticket_Award_Winners_Steel.csv') print(wood.head()) print(steel.head()) # load rankings data here: def plot_rank(coaster, park, df): rankings = df[(df["Name"] == coaster) & (df["Park"] == park)] ax = plt.subplot() ax.plot(rankings["Year of Rank"],rankings["Rank"]) ax.set_xticks(rankings["Year of Rank"]) ax.set_yticks(rankings["Rank"]) ax.invert_yaxis() plt.title("Rankings of Roller Coaster by Year") plt.xlabel("Year") plt.ylabel("Rank") plt.show() plot_rank("El Toro", "Six Flags Great Adventure", wood) # Plot 2 Coasters at Once def dbl_rank(coaster1, park1, df1, coaster2, park2, df2): rankings1 = df1[(df1["Name"] == coaster1) & (df1["Park"] == park1)] rankings2 = df2[(df2["Name"] == coaster2) & (df2["Park"] == park2)] ax = plt.subplot() ax.plot(rankings1["Year of Rank"],rankings1["Rank"]) ax.plot(rankings2["Year of Rank"],rankings2["Rank"]) ax.set_xticks(rankings1["Year of Rank"]) ax.set_yticks(rankings1["Rank"]) ax.invert_yaxis() plt.title("Rankings of Roller Coaster by Year") plt.xlabel("Year") plt.ylabel("Rank") plt.legend([coaster1, coaster2], loc=1) plt.show() dbl_rank("El Toro", "Six Flags Great Adventure", wood, "Boulder Dash", "Lake Compounce", wood) plt.clf() # Show the Top n Roller Coasters on the same graph def top_n(n, df): ax = plt.subplot() ax.invert_yaxis() for i in range(1,n+1): for y in range(2013, 2018): ranking = df[(df["Rank"] == i) & (df["Year of Rank"] == y)] ax.plot(ranking["Year of Rank"], ranking["Rank"]) ax.set_xticks(ranking["Year of Rank"]) ax.set_yticks(range(1, n+1)) plt.title("Top Roller Coasters over Time") plt.xlabel("Year") plt.ylabel("Rank") plt.legend(df["Name"]) plt.show top_n(5, wood)
65515c169802b0d55f3dfa458957225c54b91837
dansmyers/Simulation
/Sprint-1-Python_and_Descriptive_Statistics/Examples/guessing_game.py
1,028
4.15625
4
""" A number guessing game Demonstrates the while loop and conditionals """ # randint is another random function that generates integers from a given range from random import randint # Pick a random target value target = randint(1, 1000) guesses_remaining = 10 while guesses_remaining > 0: # Prompt for a guess # # Recall: the int function casts the string input to an integer value guess = int(input('Guess a number between 1 and 1000: ')) # Test if the guess is too high, too low, or correct if guess > target: print('Too high!') guesses_remaining = guesses_remaining - 1 elif guess < target: print('Too low!') guesses_remaining = guesses_remaining - 1 else: print('Correct!') break # End the current loop immediately, proceed to the code after the loop # Print a message based on whether the user found the correct answer if guesses_remaining == 0: print('Better luck next time!') else: print('Good job!')
610523726c6bbc705c86ddabc561a19e2a76aa35
wrthls/bmstu-5sem
/AA/rk_2/main.py
3,718
3.78125
4
import re def get_symb_type(char): if len(char) == 0: return -1 if char == '.': return 'dot' elif char == ' ': return 'space' elif ord('А') <= ord(char) <= ord('Я') or char == 'Ё': return 'capital' elif ord('а') <= ord(char) <= ord('я') or char == 'ё': return 'char' elif char == '\n': return 'n' else: return 'other' def main(): print("Конечный автомат:") file = open("data_1.txt", 'r') char = 1 cnt = 0 pos = 'begin' while char: char = file.read(1) cnt += 1 type = get_symb_type(char) if pos == 'begin': if type == 'capital': pos = 'first_capital' first_symb = cnt elif pos == 'first_capital': if type == 'dot': pos = '1_dot_after_capital' elif type == 'char': pos = '2_char_after_capital' else: pos = 'begin' elif pos == '1_dot_after_capital': if type == 'space': continue elif type == 'capital': pos = '1_surname_capital' else: pos = 'begin' elif pos == '1_surname_capital': if type == 'char': pos = '1_char_after_surname_capital' elif type == 'dot': pos = '1_dot_after_capital' else: pos = 'begin' elif pos == '1_char_after_surname_capital': if type == 'char': continue else: pos = 'end' last_symb = cnt # '2_char_after_capital': 5, elif pos == '2_char_after_capital': if type == 'space': pos = '2_space_found' elif type == 'char': continue else: pos = 'begin' # '2_space_found': 6, elif pos == '2_space_found': if type == 'capital': pos = '2_capiatl_found_1' else: pos = 'begin' # '2_capiatl_found_1': 6, elif pos == '2_capiatl_found_1': if type == 'dot': pos = '2_dot_found_1' else: pos = 'begin' # '2_dot_found_1': 8, elif pos == '2_dot_found_1': if type == 'space': continue elif type == 'capital': pos = '2_capiatl_found_2' else: pos = 'begin' # '2_capiatl_found_2': 9, elif pos == '2_capiatl_found_2': if type == 'dot': pos = '2_dot_found_2' else: pos = 'begin' # '2_dot_found_2': 10, elif pos == '2_dot_found_2': pos = 'end' last_symb = cnt # 'end': 11 elif pos == 'end': print("символы с", first_symb, "по", last_symb,": ", end='') with open("data_1.txt", "r") as f: print(f.read()[first_symb - 1:last_symb -1]) pos = 'begin' file.close() print() print("Регулярные выражения:") with open("data_1.txt", "r") as f: s = f.read() sm = 0 while True: result = re.search(r'(([А-Я]\.\s?[А-Я]\.\s?[А-Я][а-я]{1,20})|([А-Я][а-я]{1,20}\s[А-Я]\.\s?[А-Я]\.))', s) if result is None: break print("Символы с %d до %d: "%(result.start()+1+sm, result.end()+1+sm) + s[result.start():result.end()]) s = s[result.end():] sm += result.end() if __name__ == '__main__': main()
e100f9f293132c9bdf6ae8323683fe265d4b9110
GauthamVarmaK/CBSE-XI-XII-Record-Programs
/Class XI/11-Greatest among two numbers2.py
184
4.125
4
num1=int(input('Enter 1st number ')) num2=int(input('Enter 2nd number ')) if num1>=num2: print(num1,'is greater than or equal to',num2) else: print(num2,'is greater than',num1)
7c2e92172c019c38075f9f8d644511181239f0d0
anjaligeda/Pythonstring-branch
/lnbsplitlist.py
481
3.71875
4
#adding elements in list q=[] for i in range(20): a=int(input('enter number = ')) q.append(a) print(q) #slicing the list l2=q[0:5] l3=q[15:20] l4=l2+l3 print(l4) #squaring the elements of list square=[i**2 for i in l4 ] print(square) #splitting the list length = len(l4) middle_index = length // 2 first_half = l4[:2] second_half = l4[2:middle_index] third_half=l4[middle_index:] print(first_half) print(second_half) print(third_half)
6bc88a4ae524c8e5f2102628537ebb0b76c74bb3
AndrewPau/interview
/maxHistogramArea.py
1,391
4
4
""" Given an array of heights, find the maximum rectangular area of the array. """ def maxArea(array): stack = [] maxArea = 0 for index in range(len(array)): # If it's empty or you have a larger element, add it. if len(stack) == 0 or stack[-1][1] <= array[index]: stack.append((index, array[index])) # You have an increasing stack so that when you find a smaller element, # the next area is the top of the element and everything to the right until your current index. else: # If you remove a larger number, your number inherits its start position # If I remove a 4 and add a 3, the sum of my 3's starts where the 4 started. lastIndex = index while len(stack) > 0 and stack[-1][1] > array[index]: val = stack.pop() lastIndex = val[0] area = val[1] * (index - val[0]) if area > maxArea: maxArea = area stack.append((lastIndex, array[index])) # Empty the rest of the stack while len(stack) > 0: val = stack.pop() area = val[1] * (len(array) - val[0]) if area > maxArea: maxArea = area return maxArea # Should print 9, 4, 5, 12 print(maxArea([1,2,3,4,5])) print(maxArea([1,2,5])) print(maxArea([2,1,2,3,1])) print(maxArea([2,3,2,3,2,3]))
97b4020968a5b700f8060988bbd61ec7145397c1
ramonvaleriano/python-
/Livros/Livro-Introdução à Programação-Python/Capitulo 8/Exercicios 8/Exercicio8_4.py
415
4.0625
4
# Program: Exercicio8_4.py # Author: Ramon R. Valeriano # Description: # Developed: 05/06/2020 - 11:38 # Updated: def area_triangulo(base, altura): if base>=0 and altura>=0: area = ((base*altura)/2) return area else: return 0 base = float(input("Enter com a base de um triângulo: ")) altura = float(input("Entre com a altura do triângulo: ")) area = area_triangulo(base, altura) print(area)
a3d311efe4643a04aa58fea89dd31bab058e1328
aamerino/EjerciciosClase
/ejercicio Billetes.py
1,052
3.71875
4
def calcularBilletes (importe, billete): numeroDeBilletes = importe//billete return numeroDeBilletes def calcularResto (importe, billete): importeResto = importe % billete return importeResto def contadorBilletes (importe, billetes): for billete in billetes: numBilletes = int(calcularBilletes(importe, billete)) if numBilletes == 0: pass elif billete >= 2: print("%s billetes %s" % (numBilletes, billete)) else: print("%s monedas %s" % (numBilletes, billete)) importe = calcularResto(importe , billete) billetes=[500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.10, 0.05, 0.02, 0.01] importe = float(input('Ingresar Capital: ')) contadorBilletes(importe,billetes) # #### # Caso test calcularBilletes if calcularBilletes(5000, 500) == 10: print("Caso test calcularBilletes OK") else: print("Caso test calcularBilletes FAIL") # Caso test calcularResto if calcularResto(5000, 500) == 0: print("Caso test calcularResto OK") else: print("Caso test calcularResto FAIL")
71d336a071ed87470f119d2368c537e5507b0f5d
menggod/python_laboratory
/test/find_it.py
332
3.53125
4
def find_it(seq): num_map = {} for num in seq: if num in num_map: num_map[num] = num_map.get(num) +1 else: num_map[num] = 1 for item in num_map.items(): if item[1]%2!=0: return item[0] print(find_it([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]))
96ce51bede2868cb2d6a02c4b56bc98041f3d262
drunkwater/leetcode
/medium/python3/c0351_767_reorganize-string/00_leetcode_0351.py
716
3.625
4
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #767. Reorganize String #Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. #If possible, output any possible result. If not possible, return the empty string. #Example 1: #Input: S = "aab" #Output: "aba" #Example 2: #Input: S = "aaab" #Output: "" #Note: #S will consist of lowercase letters and have length in range [1, 500]. # #class Solution: # def reorganizeString(self, S): # """ # :type S: str # :rtype: str # """ # Time Is Money
675853a5b6509fe7ab97e47495248d3bf38a6293
Dadajon/100-days-of-code
/competitive-programming/hackerrank/mathematics/12-restaurant/restaurant.py
1,131
4.25
4
def restaurant(length, breadth): """ Martha is interviewing at Subway. One of the rounds of the interview requires her to cut a bread of size lxb into smaller identical pieces such that each piece is a square having maximum possible side length with no left over piece of bread. :param length: the length of the bread :param breadth: the breadth of the bread :return: T lines, each containing an integer that denotes the number of squares of maximum size, when the bread is cut as per the given condition. """ greatest_common_divisor = 1 min_input = min(length, breadth) if length == breadth: return 1 else: for i in range(1, min_input + 1): if length % i == 0 and breadth % i == 0: print(i) greatest_common_divisor = i return (length * breadth) // (greatest_common_divisor ** 2) if __name__ == '__main__': t = int(input()) for t_itr in range(t): lb = input().split() l = int(lb[0]) b = int(lb[1]) result = restaurant(l, b) print(str(result) + '\n')
c7e0b2fb37da2789c6f3413a3fa4c06a25dc035f
dong-pro/fullStackPython
/p1_basic/day27_31netpro/day30/02_考试题相关.py
762
4.21875
4
# ########## 第10题 v = [lambda: x for x in range(10)] print(v) print(v[0]) print(v[0]()) # 1.Python中函数时一个作用域;打印?报错 # 正确 # i = 0 # for i in range(10): # pass # 44444444444444444444444 # print(i) # 9 # 报错 # def func(): # for i in range(10): # pass # # func() # print(i) # 2.lambda表达式 # def f1(x): # return x + i # # func_list = [] # i = 0 # for i in range(10): # func_list.append(f1) # 4444444444444444444444444444444444444 # # 此时i=9 执行函数:内部调用函数代码 # print(func_list[5](8)) # 3.列表生成式 # val = [lambda x:x+i for i in range(10)] # ret = val[3](6) # print(ret) # 4.列表生成式 # val = [lambda:x for x in range(10)] # ret = val[3]() # print(ret)
f1f2e202b31315ef4788b99f7cad0d47d6541da5
MarcinPietkiewicz/SortEfficiencyGraph
/src/quicksort.py
592
3.734375
4
from src.abstractsort import AbstractSort class QuickSort(AbstractSort): def __init__(self): super().__init__() self.sort_method_name = 'Quick sort' def get_numbers_list(self, numbers: list): print('I should get numbers list here ', numbers) self.numbers = numbers def sort_numbers(self): print("I should quick sort here and return sorted list") return [x ^ 2 for x in self.numbers] if __name__ == '__main__': sortme = QuickSort() sortme.get_numbers_list([1,2,3]) sortme.sort_numbers() sortme.print_sort_name()
e8b470bc85e86daffad2df83c3a3364292ef4509
LiriNorkin/myCollage
/GUICollage.py
971
3.71875
4
import tkinter as tk from PIL import Image,ImageTk from tkinter import filedialog import myCollage root = tk.Tk() root.title('Collage Maker') label1 = tk.Label(root, text="Collage Maker", fg="black", bg="pink", height="30", width="70") label1.pack() global imgs def open(): filez = tk.filedialog.askopenfilenames(parent=root, title='Choose a file') imgs = list(filez) col = myCollage.myCollage(imgs) col.makeCollage() button1 = tk.Button(root, text="Pick Images",command=open).pack() #root.filename = filedialog.askopenfilename(initialdir="/tkinterGUI/images",title="Select Images For The Collage", filetypes=(("jpg files", "*.jpg"),("all files","*.*"))) #filez = tk.filedialog.askopenfilenames(parent=root, title='Choose a file') #imgs = list(filez) # label2 = tk.Label(root, text=root.filename).pack() # img = ImageTk.PhotoImage(Image.open(root.filename)) # imgLabel = tk.Label(image=img).pack() root.mainloop()
aff5de85c68ad5e908fcb87e1da609d2aa904f1c
INNOMIGHT/hackerrank-solutions
/LinkedLists/insertion_of_nodes_at_diff_pos.py
1,199
3.9375
4
class Node: def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def insert_at_head(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def insert_at_tail(self, data): tail = self.head while tail.next is not None: tail = tail.next new_node = Node(data) tail.next = new_node def insert_at_position(self, data, position): new_node = Node(data) counter = 0 pointer = self.head while pointer is not None: counter += 1 if counter == position: new_node.next = pointer.next pointer.next = new_node pointer = pointer.next def print_list(self): print_val = self.head while print_val is not None: print(print_val.data) print_val = print_val.next a = Node(1) b = Node(2) c = Node(3) a.next = b b.next = c c.next = None obj = SinglyLinkedList() obj.head = a obj.insert_at_head(0) obj.insert_at_tail(5) obj.insert_at_position(4, 4) obj.print_list()
53f8620710aaa648f9df26a03e4ac76a9227c383
aidris823/Bresenbacon
/line_draw.py
2,164
3.84375
4
from display import * import math def draw_line(x0,y0,x1,y1,screen,color): # float slope = (max(y0,y1) - min(y0,y1)) / (x1 - x0)) #Octant 1 / 5 draw_line_one(x0,y0,x1,y1,screen,color) #Octant 2 / 6 #Octant 7 / 3 #Octant 8 / 4 delta_y = y1 - y0 delta_x = x1 - x0 if (delta_y > 0): if (delta_x < delta_y): draw_line_two (x0, y0, x1, y1, screen, color) else: draw_line_one (x0, y0, x1, y1, screen, color) else: if (abs(delta_y) > abs(delta_x)): draw_line_seven (x0, y0, x1, y1, screen, color) else: draw_line_eight (x0, y0, x1, y1, screen, color) #Octants 1 and 5. def draw_line_one(x0,y0,x1,y1,screen,color): if (x0 > x1): buffer = x1 x1 = x0 x0 = buffer buffer = y1 y1 = y0 y0 = buffer #^ If it's an octant 5 line ^ x,y = x0,y0 a = y1-y0 b = -(x1-x0) d = 2 * a + b while (x <= x1): plot(screen,color,x,y) if d >= 0: y += 1 d += 2 * b x += 1 d += 2 * a def draw_line_two(x0,y0,x1,y1,screen,color): if (x0 > x1): buffer = x1 x1 = x0 x0 = buffer buffer = y1 y1 = y0 y0 = buffer #^ If it's an octant 6 line ^ x,y = x0,y0 a = y1-y0 b = -(x1-x0) d = 2 * b + a while y <= y1: plot(screen,color,x,y) if d < 0: x += 1 d += 2 * a y += 1 d += 2 * b def draw_line_seven(x0,y0,x1,y1,screen,color): y0 *= -1 y1 *= -1 draw_line_two(x0,y0,x1,y1,screen,color) def draw_line_eight(x0,y0,x1,y1,screen,color): y0 *= -1 y1 *= -1 draw_line_one(x0,y0,x1,y1,screen,color) screen = new_screen() color = [0,98,51] draw_line(0,600,350,500,screen,color) plot(screen,[255,255,255],100,600) draw_line(400,600,0,600,screen,color) draw_line(0,600,400,600,screen,color) draw_line(200,0,50,500,screen,color) draw_line(200,0,550,500,screen,color) draw_line(0,500,0,250,screen,color) draw_line(400,600,50,500,screen,color) display(screen) save_extension(screen,'img.png')
af53224511886f323fa4a0840cb2ad27ef4b99b6
ceciliawambui/byte_of_python
/ex34.py
242
3.765625
4
animals = ['bear', 'python 3.6', 'peacock', 'kangaroo', 'whale', 'platypus'] print("The animal at 1 is", animals[1]) print("The animal at 3 is", animals[3]) print("The animal at 2 is", animals[2]) print("The animal at 4 is", animals[4])
35828fd305f69e633c559159070d4bf25ba9b637
baomanedu/Python-Basic-Courses
/课程源码/03-list.py
906
4
4
##定义 a = [] print(type(a)) numlist = [1,2,3,4,5,6] strlist = ["a","b","c","d"] print(numlist,strlist) ##获取list元素 print(numlist[3],strlist[2]) print(numlist[:5]) print(len(numlist)) ## 应用 ipAddress = [r"192.158.0.1",r"192.168.0.2"] print(ipAddress) ## 遍历 for ip in ipAddress: print(ip) #内置函数 testHosts = ["aa","bb","cc","dd"] t1 = ["dd","cc"] testHosts.append("EE") #末尾追加 print(testHosts.count('bb')) # 计算元素出现的次数 print(testHosts.extend(t1)) # 扩展列表、合并列表 print(testHosts.index("EE")) # 获取列表中元素的索引 testHosts.insert(5,"DD") #列表中插入元素 ,参数: 索引,元素 print(testHosts) print(testHosts.pop(2)) #根据索引删除元素,并返回被删元素 print(testHosts) testHosts.remove("EE") ##删除元素 print(testHosts) testHosts.reverse() #反向列表 print(testHosts)
1fb5a6782cc5bc87506a5fd39ee5b3e8768a94bc
EdisonZhu33/Algorithm
/备战2020/035-全排列2.py
1,086
3.71875
4
""" @file : 035-全排列2.py @author : xiaolu @time : 2020-02-03 """ ''' 给定一个可包含重复数字的序列,返回所有不重复的全排列 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] ''' from typing import List class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: result = [] def permute(nums, tmp): if not nums: result.append(tmp) for i in range(len(nums)): permute(nums[:i] + nums[i + 1:], tmp + [nums[i]]) permute(nums, []) final_res = [] for r in result: t = '%'.join([str(i) for i in r]) final_res.append(t) final_res = list(set(final_res)) # print(final_res) # ['211', '112', '121'] result = [] for elem in final_res: temp = [int(i) for i in elem.split('%')] result.append(temp) return result if __name__ == '__main__': nums = [1, 1, 2] sol = Solution() result = sol.permuteUnique(nums) print(result)
8bb3b05bf40c612961bfe8338c74743a99983386
sarvparteek/Data-structures-And-Algorithms
/recursiveEvenOutput.py
569
3.984375
4
__author__ = 'sarvps' ''' Author: Sarv Parteek Singh Course: CISC 610 Term: Late Summer Final exam, Problem 2 Brief: Print out positive even numbers between two given numbers using recursion ''' def evenOutput(lower,upper): if upper - lower <= 1: if lower %2 == 0: print(lower) else: print(upper) else: if lower %2 == 0: if lower >0: print(lower) lower = lower + 2 else: lower = lower + 1 evenOutput(lower, upper) evenOutput(-12,24)
2fa8f63ba8d39e51838cfffd5899a569c3ecbca0
aligg/markov-chains
/markov.py
2,331
3.984375
4
"""Generate Markov text from text files.""" from random import choice # import random def open_and_read_file(file_path): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ opened_file = open(input_path) text_string = opened_file.read() return text_string def make_chains(text_string, ngram_size): """Take input text as string; return dictionary of Markov chains. A chain will be a key that consists of a tuple of (word1, word2) and the value would be a list of the word(s) that follow those two words in the input text. For example: >>> chains = make_chains("hi there mary hi there juanita") Each bigram (except the last) will be a key in chains: >>> sorted(chains.keys()) [('hi', 'there'), ('mary', 'hi'), ('there', 'mary')] Each item in chains is a list of all possible following words: >>> chains[('hi', 'there')] ['mary', 'juanita'] >>> chains[('there','juanita')] [None] """ chains = {} word_list = text_string.split() ngram_size = int(ngram_size) i= 0 for i in range(len(word_list) - ngram_size): ngram = [] for j in range(i, i + ngram_size): word_to_add = word_list[j] ngram.append(word_to_add) ngram_tuple = tuple(ngram) if ngram_tuple in chains: chains[ngram_tuple].append(word_list[i + ngram_size]) else: chains[ngram_tuple] = [word_list[i + ngram_size]] return chains def make_text(chains): """Return text from chains.""" words = [] starter_ngram = choice(chains.keys()) words = list(starter_ngram) ngram_size = len(starter_ngram) while starter_ngram in chains.keys(): random_word = choice(chains[starter_ngram]) words.append(random_word) starter_ngram = tuple(words[-ngram_size:]) return " ".join(words) # input_path = "green-eggs.txt" input_path = "trump.txt" # Open the file and turn it into one long string input_text = open_and_read_file(input_path) # Get a Markov chain chains = make_chains(input_text, 5) # Produce random text random_text = make_text(chains) print random_text
a425457bc80922af57eb415cbd49d80ae975e70f
Alejandro-Gonzalez-Barriga/learningPython
/python3basics/dictionaries.py
1,447
4.75
5
##Dictionaries is a collection of key-value pairs ## in order to return a value in a dictionary it must be referenced using the key #dictionaryName = {key1:value1, key2:value2, key3:value3} steakPrices = {"sirloin":18.99, "t-bone":27.99, "ribeye":29.99} print(steakPrices) #prints {'sirloin': 18.99, 't-bone': 27.99, 'ribeye': 29.99} print(steakPrices["t-bone"]) #prints 27.99 #to change the value of a key use this syntax steakPrices["sirloin"] = 20.99 print(steakPrices["sirloin"]) #prints 20.99 ##Operations #dictionaryName.keys() calls out all the keys in that particular dictionary print(steakPrices.keys()) #prints dict_keys(['sirloin', 't-bone', 'ribeye']) #dictionaryName.values() calls out all the values in that particular dictionary print(steakPrices.values()) #prints dict_values([20.99, 27.99, 29.99]) #to clone a dictionary you can use dictionaryName.copy() #Ex. copyOfSteakPrices = steakPrices.copy() print(copyOfSteakPrices) #prints {'sirloin': 20.99, 't-bone': 27.99, 'ribeye': 29.99} #to delete a key-value pair in a dictionary.. del steakPrices["t-bone"] print(steakPrices) #prints {'sirloin': 20.99, 'ribeye': 29.99} #to clear the contents of a dictionary.. steakPrices.clear() print(steakPrices) #prints {} # to add a key-value pair to a dictionary.. steakPrices["t-bone"] = 27.99 print(steakPrices) #prints {'t-bone': 27.99} steakPrices["ribeye"] = 29.99 print(steakPrices) #prints {'t-bone': 27.99, 'ribeye': 29.99}
c37b8b4009778c4a85d141bcdb7833a9304ab0e7
hernandez232/FP_Tareas_00075919
/División.py
161
4
4
n = int (input("Ingrese un numero: ")) n2 = int (input("Ingrese un numero: ")) div = (n/n2) print (" ") print ("La división de los numeros ingresados es:",div)
5238c5cddd8fd5c6979672f7bba61962e94e1fa1
YoushaExT/practice
/moreproblems/q39.py
315
4.1875
4
# Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). # Then the function needs to print the last 5 elements in the list. def myFunc(): L=[] for i in range(1,21): L.append(i**2) print(L[-5:]) #[startIncluded:stop:step] myFunc()
7993bb5446cb24becaba1dca7caf3791f2adc47b
LaurenGeis/PythonNotes
/strings.py
957
4.5625
5
# escape characters # use backslash \ followed by character to add in a string # example: print('go to Dana's house) does not work, tries to create variables after 's house. print('go to Dana\'s house') # \n is for newline print('Hello \nhow are you today? \nI am well') #putting r in front of a string, this is a raw sting, prints all the text: print(r'Hello \nhow are you today? \nI am well') # you can achieve the new line effect w/ triple quotes as well print('''Hello How are you today? I am doing well''') # slicing strings by character position: spam = 'hello world' print(spam[0]) print(spam[1]) print(spam[-1]) print(spam[0:5]) fizz = spam[0:5] print(fizz) #boolean statements example age = 18 old_enough_to_get_driving_licence = age >= 17 print(old_enough_to_get_driving_licence) print('h' in 'hello') #string interpolation name = 'Lauren' age = 10000 print('My name is %s and I am %s years old' %(name, age))
547ba649fa219f39830b262c6b37641fa02785b4
ejmurray/Codeacademy
/Loops/ex10.py
123
3.796875
4
hobbies = [] # Add your code below! for i in range(3): hobby = raw_input("Enter a hobby: ") hobbies.append(hobby)
b96f7709ac41f65bc34b60539e26978fec132035
gjogjreiogjwer/jzoffer
/其他/扑克牌顺子.py
1,278
3.96875
4
# -*- coding:utf-8 -*- ''' 扑克牌顺子 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。 2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。 example1: 输入: [1,2,3,4,5] 输出: True example2: 输入: [0,0,1,2,5] 输出: True 解: 输入5个数;在0-13之间;除大小王外无重复;大小差值<=5 ''' class Solution(object): def isStraight(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) != 5: return False flag = 0 maximum = -1 minimum = 14 for num in nums: if num > 13 or num < 0: return False # 大小王 if num == 0: continue # 是否重复,重点 if flag >> num & 1 == 1: return False flag |= 1 << num if num > maximum: maximum = num if num < minimum: minimum = num if maximum - minimum >= 5: return False return True if __name__ == '__main__': a = Solution() print (a.isStraight([1,2,0,3,5]))
d321b1c4902ec8f4c546e54b821a8cf9f9d9b70a
pdjan/fcc
/Scientific Computing with Python/Shape_calculator.py
1,863
3.984375
4
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return Rectangle.__name__ + "(width=" + str(self.width) + ", height=" + str(self.height) + ")" def set_width(self, w): self.width = w def set_height(self, h): self.height = h def get_area(self): return (self.width * self.height) def get_perimeter(self): return (2 * self.width + 2 * self.height) def get_diagonal(self): return ((self.width ** 2 + self.height ** 2) ** .5) def get_picture(self): output = "" if (self.width > 50 or self.height > 50): output += "Too big for picture." else: for i in range(self.height): for i in range(self.width): output += "*" output += "\n" return output def get_amount_inside(self, shape): a = self.get_area() b = shape.get_area() res = int(a / b) return res class Square(Rectangle): def __init__(self, s): self.side = s Rectangle.__init__(self, s, s) def __str__(self): return "Square(side=" + str(self.side) + ")" def set_side(self, s): self.side = s Rectangle.__init__(self, s, s) def set_width(self, s): self.side = s def set_height(self, s): self.side = s rect = Rectangle(10, 5) print(rect.get_area()) rect.set_height(3) print(rect.get_perimeter()) print(rect) print(rect.get_picture()) sq = Square(9) print(sq.get_area()) sq.set_side(4) print(sq.get_diagonal()) print(sq) print(sq.get_picture()) rect.set_height(8) rect.set_width(16) print(rect.get_amount_inside(sq))
e753701fce495c27c930ecd12b5a622db1bdd5e4
soundary219/python
/abs.py
237
3.765625
4
from abc import ABC,abstractmethod import math class shape(ABC): @abstractmethod def getArea(): pass class Circle(shape): def getArea(self): return math.pi*5*5 circle=Circle() print(circle.getArea())
bd84147762cdc829429aa89542f9ac3310708569
rlongo02/Python-Book-Exercises
/Chapter_6/6-11_Cities.py
559
3.78125
4
SA = {'country': 'the united states', 'population': '1.493 million', 'fact': 'home to the Alamo'} CS = {'country': 'the united states', 'population': '464,474', 'fact': 'my birthplace'} GB = {'country': 'the united states', 'population': '69,499', 'fact': 'where my school is'} cities = {'san antonio': SA, 'colorado springs': CS, 'glen burnie': GB} for name, info in cities.items(): print(name.title() + " is a city in " + info['country'] + " and has a population of " + info['population'] + " people.") print("Fun fact: it is " + info['fact'] + '.\n')
ed30249be3e7e2156b58e18db0c131cbe8accf7b
NishchaySharma/Competitve-Programming
/Codechef/Area or perimeter.py
173
3.734375
4
l=int(input()) b=int(input()) if l*b>2*(l+b): print('Area',l*b,sep='\n') elif 2*(l+b)>l*b: print('Peri',2*(l+b),sep='\n') else: print('Eq',l*b,sep='\n')
bd609d3981ec2aca30fb9a993271b9e78860de92
shlampley/learning
/learn python/codewars.py
268
3.875
4
def disemvowel(string_): vowels = ('a', 'e', 'i', 'o', 'u',) for x in string_: if x in vowels: string_ = string_.replace(x, "") return string_ teststring = "This is a test string with several words\n" print(disemvowel(teststring))
ee5680eda52ca273ee33f32416a20d175f094fb4
Gera2019/gu_python
/lesson_5/task_1_2.py
433
4.21875
4
def odd_nums(n): result = (num for num in range(1, n + 1, 2)) return result # for num in range(1, n+1, 2): # yield num # другой вариант вывода нечетных чисел, при использовании yield # print(type(result)) # print(odd_nums(7) # result = odd_nums(7) # print(next(result), next(result), next(result), next(result), next(result), next(result)) print(*odd_nums(7))
1b886a864782904b8aa2b4b4f900b65ae91b0a14
gschen/where2go-python-test
/1906101038江来洪/day20191217/Test_3_2.py
627
3.5625
4
#查验身份证是否是正确的 N = int(input('请输入你要查验身份证的个数:')) list1 = [] list2 = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2] list3 = [1,0,'x',9,8,7,6,5,4,3,2] for i in range(N): n = int(input('请输入你要查验的身份证号码:')) for a in range(2,19): m = (n%(10**a))//(10**(a-1)) s = n%10 a += 1 list1.append(m) list1.reverse() S = 0 for k in range(17): S += list1[k]*list2[k] z = S%11 z = int(z) if z != s: print('该身份证是错的') else: print('该身份证是对的') list1 = []
31048002b75edba6cfd1a9b6cbd2a25efae76242
papalagichen/leet-code
/0231 - Power of Two.py
394
3.515625
4
class Solution(object): def isPowerOfTwo(self, n): i = 1 while i <= n: if i == n: return True i *= 2 return False if __name__ == '__main__': import Test Test.test(Solution().isPowerOfTwo, [ (0, False), (1, True), (2, True), (4, True), (3, False), (-1, False), ])
4f1b722bd93b7538f12106d018836f9858c5d120
King9587/Interesting-projects
/飞机大战/plane_sprites.py
3,852
3.578125
4
import random import pygame # 屏幕大小的常量 SCREEN_RECT = pygame.Rect(0, 0, 480, 700) # 创建敌机的事件 CREATE_ENEMY_EVENT = pygame.USEREVENT # 英雄飞机发射子弹的事件 HERO_FIRE_EVENT = pygame.USEREVENT + 1 class GameSprite(pygame.sprite.Sprite): """游戏主类——继承自pygame.sprite.Sprite""" def __init__(self, image_name, speed=1): # 调用父类的初始化方法 super().__init__() # 定义属性 self.image = pygame.image.load(image_name) self.rect = self.image.get_rect() self.speed = speed def update(self): # 在屏幕的垂直方向向下移动 self.rect.y += self.speed class BackGround(GameSprite): """背景类,继承自GameSprite""" def __init__(self, is_alt=False): # 调用父类方法创建精灵对象 super().__init__("./游戏素材/background.png") # 判断是否为背景图像2,若是则改变初始坐标位置 if is_alt: self.rect.bottom = 0 def update(self): # 调用父类方法——向下移动 super().update() if self.rect.y >= SCREEN_RECT.height: self.rect.bottom = 0 class Enemy(GameSprite): """敌机精灵类,继承自GameSprite""" def __init__(self): # 随机抽取敌机 number = random.randint(1, 3) if number == 1: # 调用父类方法创建精灵对象 super().__init__("./游戏素材/enemy1.png") # 随机抽取出场位置 elif number == 2: # 调用父类方法创建精灵对象 super().__init__("./游戏素材/enemy2.png") elif number == 3: # 调用父类方法创建精灵对象 super().__init__("./游戏素材/enemy3_n1.png") # 随机抽取出场位置 self.rect.x = random.randrange( 0, (SCREEN_RECT.width - self.rect.width), 1) # 随机抽取出场速度 self.speed = random.randint(1, 3) # 初始位置应该在游戏主窗口的上方 self.rect.bottom = 0 def update(self): # 调用父类方法——向下移动 super().update() # 判断是否飞出屏幕,是则释放 if self.rect.y >= SCREEN_RECT.height: self.kill() class Hero(GameSprite): """英雄飞机类,继承自GameSprite""" def __init__(self): # 设置速度为0 super().__init__("./游戏素材/me1.png", speed=0) # 位于游戏主窗口的中央 self.rect.centerx = SCREEN_RECT.centerx self.rect.bottom = SCREEN_RECT.height - 10 # 创建子弹精灵组 self.bullet_group = pygame.sprite.Group() def update(self): # 英雄飞机在水平方向移动且不能移出边界 if self.rect.x < 0: self.rect.x = 0 elif self.rect.right > SCREEN_RECT.width: self.rect.right = SCREEN_RECT.width else: self.rect.x += self.speed def fire(self): """英雄飞机发射子弹""" for i in (0, 1, 2): # 创建子弹精灵 bullet = Bullet() # 设定子弹精灵的位置,应该与英雄飞机的正上方中央发射 bullet.rect.y = self.rect.y - 2 * i * bullet.rect.height bullet.rect.centerx = self.rect.centerx # 子弹精灵加入精灵组 self.bullet_group.add(bullet) class Bullet(GameSprite): """子弹类,继承自GameSprite""" def __init__(self): super().__init__("./游戏素材/bullet1.png", speed=-3) def update(self): # 调用父类方法——向下移动 super().update() # 判断子弹是否飞出屏幕,是则释放 if self.rect.bottom <= 0: self.kill()
869e88c5fa20594b85a6d3d0f8296c1c0521aa0c
SkippyWiggly/SkippyLearnsPython
/ex15.py
960
4.375
4
#imports argv to use for user input from sys import argv #outlines the two inputs we need from user #(the script to load and the filename we'll load) script, filename = argv #defining variable txt as a file object that is opened via the open function. #not necessary to define txt variable, can simply do open(filename).read() #later when I want to read the file txt = open(filename) #print out filename that is typed in before running print "Here's your file %r" % filename #commanding the file that was opened in the txt variable to be "read" (printed) print txt.read() #asking for input, presumably the same filename as before print "Type the filename again:" #set new variable file_again to that filename file_again = raw_input("> ") #defining new variable txt_again to the open the file inputted by user txt_again = open(file_again) #commanding the file opened in txt_again definition to be read print txt_again.read() txt.close() txt_again.close()
7b1fb533023fdd6e11ac1aa49356d014dd6e62a1
bgg7547/date_structure
/2020.10.09/02栈.py
1,635
4.0625
4
# # 数组实现栈 # class Stack: # def __init__(self): # self.stack = [] # self.size = 0 # # #压栈 # def push(self,data): # self.stack.append(data) # self.size += 1 # # #弹栈 # def pop(self): # if self.stack: # temp = self.stack.pop() # self.size -= 1 # else: # raise IndexError('索引越界') # return temp # # #栈顶元素 # def peek(self): # if self.stack: # return self.stack[-1] # # #是否为空 # def is_empty(self): # if self.stack: # return False # return True # # #长度 # def chang(self): # return self.size # # stack = Stack() # for i in range(5): # stack.push(i) # print(stack) # print(stack.pop()) # print(stack.is_empty()) # print(stack.chang()) #链表实现栈 class Node: def __init__(self,data): self.data = data self.next = None def __repr__(self): return f"Node({self.data})" class linkstack: def __init__(self): self.top = None self.size = 0 # 压栈 (相当于头部插入节点) def push(self,data): node = Node(data) if self.top is None: self.top = node else: node.next = self.top self.top = node self.size += 1 #弹栈 def pop(self): if self.top is None: raise Exception("空列表") else: temp = self.top self.top = temp.next temp.next = None self.size -= 1 return temp
d6cda1dc01d2f063d59aed48ad92dbd77d83ff2c
dunnette/ctci
/Chapter1.py
3,156
4.125
4
# 1.1 # Implement an algorithm to determine if a string has all unique characters. # What if you can not use additional data structures? def all_unique(s1): return len(s1) == len(set(s1)) def all_unique_no_structs(s1): for c in s1: if s1.count(c) > 1: return False return True # 1.2 # Write code to reverse a C-Style String def rev_str(s1): return s1[::-1] # 1.3 # Design an algorithm and write code to remove the duplicate characters in a string # without using any additional buffer NOTE: One or two additional variables are fine. # An extra copy of the array is not. # FOLLOW UP # Write the test cases for this method. def remove_dup(s1): l = list(s1) last_char = s1[0] for i in range(1,len(l)): if l[i] == last_char: l[i] = '' else: last_char = l[i] return ''.join(l) def remove_dup_no_buf(s1): return ''.join([s1[i] for i in range(len(s1)-1) if s1[i] is not s1[i+1]] + [s1[-1]]) # 1.4 # Write a method to decide if two strings are anagrams or not. import collections def is_anagram(s1, s2): if len(s1) == len(s2): return collections.Counter(s1) == collections.Counter(s2) return False is_anagram('admirer','married') is_anagram('test','test') is_anagram('test','best') # 1.5 # Write a method to replace all spaces in a string with '%20'. def replace_space(s1): return s1.replace(' ','%20') replace_space('This is a sentence') replace_space(' space ') replace_space(' ') # 1.6 # Given an image represented by an NxN matrix, where each pixel in the image is 4 # bytes, write a method to rotate the image by 90 degrees Can you do this in place? def rotate_mat(m): n = len(m) return [[r[i] for r in reversed(m)] for i in range(n)] import numpy as np m = [[1, 2, 3, 4], [5, 6, 0, 8], [9, 10, 11, 12], [13, 14, 15, 16]] print(np.matrix(m)) print(np.matrix(rotate_mat(m))) # 1.7 # Write an algorithm such that if an element in an MxN matrix is 0, its entire row and # column is set to 0. def zero_mat(mat): m = len(mat) n = len(mat[0]) zero_row = set() zero_col = set() for m_i in range(m): for n_i in range(n): if mat[m_i][n_i] == 0: zero_row.add(m_i) zero_col.add(n_i) new_mat = list() for m_i in range(m): if m_i in zero_row: new_mat.append([0] * n) else: new_mat.append([0 if (i in zero_col) else mat[m_i][i] for i in range(n)]) return new_mat import numpy as np m = [[1, 2, 3, 4], [5, 6, 0, 8], [9, 10, 11, 12]] print(np.matrix(m)) print(np.matrix(zero_mat(m))) # 1.8 # Assume you have a method isSubstring which checks if one word is a substring of # another Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using # only one call to isSubstring (i e , "waterbottle" is a rotation of "erbottlewat") def isSubstring(s1, s2): return s1.find(s2) > -1 def sub_check(s1, s2): if len(s1) == len(s2): return isSubstring(s1 * 2, s2) return False sub_check('waterbottle', 'erbottlewat') sub_check('waterbottle', 'gasbottle')
503863dcdd5ed24fee2f6d05d29b25a24748a90d
shiniapplegami/NIELIT
/Python_Codes/DAY27/DAY27.py
628
3.640625
4
import pandas as pd import numpy as np #------------------------------------------------------------------------------------- drinks=pd.read_csv("drinks.csv") print drinks.head() print "=======================" group=drinks.groupby('continent') print "\nContinent that drinks more beer on average :",group['beer_servings'].mean().idxmax() print "=======================" print "\n",group['wine_servings'].describe() print "=======================" print "\n",group.mean() print "=======================" print "\n",group.median() print "=======================" print group['spirit_servings'].describe()[['mean','min','max']]
0ba9c66696b0b8a6f93d0f48e690a1dfa6084f76
otecilliblazh/New
/triangle2.py
324
4
4
r=int(input("Введите высоту :")) c=r*2-1 x=0 for i in range(r): for j in range(c): if j==c//2-x or j==c//2+x or i==r-1: print("*", end=" ") elif c//2-x<j and c//2+x>j: print("*", end=" ") else: print(" ", end=" ") x=x+1 print() print()
d420487746d453766dba6c07946925311fba04ce
mebaysan/LearningKitforBeginners-Python
/basic_ödevler/döngüler ödev dosyası/100ekadar3ebölünensayılar.py
382
3.828125
4
print(""" ************************* 1'den 100'e kadar olan sayılardan sadece 3'e bölünen sayıları ekrana bastırın. Bu işlemi continue ile yapmaya çalışın ************************* for i in range(1,101): if (i % 3 != 0): continue print(i) """) for i in range(1,101): if (i % 3 != 0): continue print(i)
7389eb6ab215924a2fe5f45f2494a6fdb82d8e98
minhluanlqd/AlgorithmProblem
/problem13.py
981
3.9375
4
"""""" """ This problem was asked by Apple. #273 A fixed point in an array is an element whose value is equal to its index. Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return False. For example, given [-6, 0, 2, 40], you should return 2. Given [1, 5, 7, 8], you should return False. """ def find_fixed_point(arr): for i in range(len(arr)): if i == arr[i]: return i return False """O(N) Time""" def find_fixed_point_1(arr): low, high = 0, len(arr) while low <= high: mid = (low + high) // 2 if arr[mid] == mid: return mid elif arr[mid] < mid: low = mid + 1 else: high = mid - 1 return False """O(logN)""" arr = [-6, 0, 2, 40] arr_1 = [1, 5, 7, 8] print(find_fixed_point(arr)) print(find_fixed_point(arr_1)) print(find_fixed_point_1(arr)) print(find_fixed_point_1(arr_1))
dcd9d136edcf4ce49e82c75dea958404ff4adea1
jjbernard/100DaysOfCode
/Days 16-18/D17.py
626
3.828125
4
import random import itertools NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos', 'julian sequeira', 'sandra bullock', 'keanu reeves', 'julbob pybites', 'bob belderbos', 'julian sequeira', 'al pacino', 'brad pitt', 'matt damon', 'brad pitt'] name_list = [name.title() for name in NAMES] name_reversed = [" ".join(list(reversed(name.split()))) for name in name_list] def gen_pair(): name_list = [name.title() for name in NAMES] while True: pairs = random.choices(name_list, k=2) yield f'{pairs[0].split()[0]} teams up with {pairs[1].split()[0]}' if __name__ == '__main__': pairs = gen_pair() print(list(itertools.islice(pairs, 10)))
a8a8443daaeab7cd059a1050d5856d3f71de3b29
TheMiloAnderson/data-structures-and-algorithms
/Py401/radix_sort/radix_sort.py
805
4.0625
4
def radix_sort(arr): """ Implements radix sort in conjunction with counting sort function below """ if len(arr) > 0: biggest_number = max(arr) exp = 1 while biggest_number/exp > 1: counting_sort(arr, exp) exp *= 10 def counting_sort(arr, exp): """ Implements counting sort, to be called by radix_sort with appropriate exponent """ n = len(arr) output = [0] * n count = [0] * 10 for i in range(n): index = arr[i] // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i-1] i = n - 1 while i >= 0: index = arr[i] // exp count[index % 10] -= 1 output[count[index % 10]] = arr[i] i -= 1 for i in range(n): arr[i] = output[i]
c3f622e303a004de4071b5f263d6508e09ca99c9
sangha25/PythonTutorials
/FindingAge.py
224
3.921875
4
import datetime #This Library will import computer Timer. DOB=input("Enter your Date of Birth:") #date of current system. CurrentYear=datetime.datetime.now().year Age=CurrentYear-int(DOB) print("Your age is {}".format(Age))
dc2b416ab47bf97b1913502be3306b7751d8ed73
austinsonger/CodingChallenges
/Hackerrank/_Contests/Project_Euler/Python/pe072.py
757
3.890625
4
""" Counting fractions Problem 72 Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? """ import time from pe070 import totient_array __date__ = '14-4-7' __author__ = 'SUN' if __name__ == '__main__': start = time.clock() N = 1000000 print(sum(totient_array(N)) - 1) print('Runtime is ', time.clock() - start)
a1bbaa171729de5727a5e3dc7463421cd953e7fc
firstgenius/-Filming-Location-Next-To-Me
/main.py
5,137
3.5625
4
''' This module creates a web map. The web map displays information about the locations of films that were shot in a given year. ''' def read_info(file_path: str, year: str) -> list(): ''' This function reads the movies of the desired year from the list, lists them, replaces them with coordinates and returns this new list. >>> type(read_info('locations.list', '1980')) <class 'list'> >>> len(read_info('locations.list', '1980')[:10]) 10 ''' values = [] with open(file_path, "r", encoding = "utf-8", errors = 'ignore') as file: counter = 0 for line in file: counter += 1 if 'Federal' not in line and 'Highway' not in line and counter > 14: line = line.strip().split('\t') line = list(filter(lambda elem: elem != '', line)) line[0] = line[0].replace('\'', '') line[0] = line[0].replace('\"', '') line[0] = line[0].split('(') line[0][1] = line[0][1][:4] line[0] = line[0][:2] if line[0][1] != year: continue if len(line[0]) > 2: line[0].pop(2) if len(line) > 2: line.pop(2) geolocator = Nominatim(user_agent="film location", scheme='http') geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) ctx = ssl.create_default_context(cafile=certifi.where()) geopy.geocoders.options.default_ssl_context = ctx location = geolocator.geocode(line[1]) if location == None: continue else: line[1] = (location.latitude, location.longitude) if line not in values: values.append(line) return values def find_closest_locations(file_path: str, year: str, user_x, user_y: float) -> list(): ''' This function returns a list of the 10 closest shooting scenes to the user's coordinates. >>> type(find_closest_locations('locations.list', '1980', 20, 20)) <class 'list'> >>> len(find_closest_locations('locations.list', '1989', 49, 50)) 10 ''' values = read_info(file_path, year) for i in range(len(values)): distance = distance_between_points(user_x, user_y, values[i][1][0], values[i][1][1]) values[i].append(distance) values.sort(key=lambda x:x[2]) return values[:10] def distance_between_points(user_x, user_y, scene_x, scene_y: float) -> int: ''' This function returns distance between user's and scene's coordinates. >>> distance_between_points(20, 20, 50, 50) 4253 >>> distance_between_points(49.83826, 24.02324, 30.2686032, -97.7627732) 9442 ''' userloc = (user_x, user_y) filmloc = (scene_x, scene_y) distance = geopy.distance.geodesic(userloc, filmloc).km return int(distance) def create_map(values: list(), user_x: float, user_y: float): ''' This function creates a map with 3 layers. The map shows 10 labels of the nearest filming locations. ''' map = folium.Map(tiles="Stamen Terrain", location=[user_x,user_y]) fg = folium.FeatureGroup(name='Scenes') fg_2 = folium.FeatureGroup(name='Distances') for film in values: distance = film[2] film_x = film[1][0] film_y = film[1][1] name = film[0][0] fg.add_child(folium.Marker(location=[film_x,film_y], popup=name, icon=folium.Icon())) fg_2.add_child(folium.CircleMarker(location=[film_x,film_y], radius=10, fill_color = color_creator(distance), color = 'black', fill_opacity = 1)) map.add_child(folium.Marker(location=[user_x,user_y], popup='ME', icon=folium.Icon())) map.add_child(fg) map.add_child(fg_2) map.add_child(folium.LayerControl()) map.save('Film_Scenes_Map.html') def color_creator(distance : int) -> str: ''' This function returns color depending on distance parameter. >>> color_creator(300) 'green' >>> color_creator(1000) 'yellow' >>> color_creator(2000) 'red' ''' if distance < 800: return 'green' elif 800 <= distance <= 1300: return 'yellow' else: return 'red' if __name__ == "__main__": import folium import certifi import ssl import geopy.distance from geopy.distance import geodesic from geopy.exc import GeocoderUnavailable from geopy.exc import GeocoderTimedOut from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter print('Please enter a year you would like to have a map for:') year = str(input()) print('Please enter latitude:') user_lat = input() print('Please enter longitude:') user_long = input() print('Map is generating...') values = find_closest_locations('locations.list', year, user_lat, user_long) print('Please wait...') create_map(values, user_lat, user_long) print('Finished. Please have a look at the map Film_Scenes_Map.html')
0a618218aa261dee2bff504c3787447baa6d5426
saetar/pyEuler
/not_done/py_not_started/euler_448.py
493
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # ~ Jesse Rubin ~ project Euler ~ """ Average least common multiple http://projecteuler.net/problem=448 The function lcm(a,b) denotes the least common multiple of a and b. Let A(n) be the average of the values of lcm(n,i) for 1≤i≤n. E.g: A(2)=(2+2)/2=2 and A(10)=(10+10+30+20+10+30+70+40+90+10)/10=32. Let S(n)=∑A(k) for 1≤k≤n. S(100)=122726. Find S(99999999019) mod 999999017. """ def p448(): pass if __name__ == '__main__': p448()
c88784356587f987135738ee08d8869fd40fb89d
yu-linfeng/leetcode
/python/20_valid_parentheses.py
681
3.84375
4
class Solution: """ 是否是合法的括号,括号成对出现 """ def isValid(self, s): """ :type s: str :rtype: bool """ parentheses = {'{' : '}', '[' : ']', '(' : ')'} stack = [] for i, item in enumerate(s): if item in parentheses.keys(): stack.append(item) else: if len(stack) == 0 or parentheses[stack.pop()] != item: return False if len(stack) != 0: return False else: return True if __name__ == "__main__": solution = Solution() s = "{{[]()}}" print(solution.isValid(s))
8cfe18b4c044c7d92dac02a1dd626e672ce5e7d6
letivela/AnitaBorg-Python-Certification-Course
/Week 6 Coding Challenges/Flow Control Statements/rightTriangle.py
2,060
4.625
5
# SCRIPT: rightTriangle.py # AUTHOR: Sahar Kausar # CONTACT: [email protected] # # Anita Borg - Python Certification Course # # DESCRIPTION: Anna likes to draw right angled triangles. She recently learnt how to code in Python, and she is curious to see if it can be used to print the same. # You need to help her out by writing a program which takes an input number n from the user and prints a right angled triangle of height n. Anna also wants that the triangle should display the respective line numbers if the line number is odd (1st, 3rd, 5th… line), and censor out the even numbered lines (2nd, 4th, 6th… line) using the hash (‘#’) symbol. # Note: 1 ≤ n ≤ 10 """ Sample Input: 5 Sample Output: 1 ## 333 #### 55555 """ triHeight = int(input("Please enter a number between 1 and 10 for the desired height of the triangle: ")) #Function for printing the specialized right triangle def rightTriangle(height): for row in range(1, height + 1): for col in range(1, height + 1): if (col <= height - row): print(' ', end = "") else: #if a row is on an odd lined number (1st, 3rd, 5th...), then print that number if (row % 2) != 0: print(row, end = "") #if a row is on an even lined number (2nd, 4th, 6th...), then print the hash ('#') symbol else: print("#", end = "") print() #Executes for printing a right triangle while checking that the value inputted is within bounds while True: try: #If the input is not within bounds if (triHeight > 10 or triHeight < 0): #Then an error is raised raise ValueError #Otherwise, we pass in the input from the user 'triHeight' into our rightTriangle function rightTriangle(triHeight) break except ValueError: print("The inputted number is not within bounds! Please enter an integer between 1 and 10!") break
d66b2aee72ec93cd0a58b274b442f952578446c7
gfpp/MITx6001x2017
/ex/week3_biggest.py
1,181
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 2 17:49:29 2017 @author: gfpp """ # Exercise: biggest # Consider the following sequence of expressions: animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') # We want to write some simple procedures that work on dictionaries # to return information. # # This time, write a procedure, called biggest, which returns the key # corresponding to the entry with the largest number of values associated # with it. If there is more than one such entry, return any one of the # matching keys. # # Example usage: # >>> biggest(animals) # 'd' # If there are no values in the dictionary, biggest should return None. def biggest(aDict): ''' aDict: A dictionary, where all the values are lists. returns: The key with the largest number of values associated with it ''' # Your Code Here if len(aDict) == 0: return None num = 1 key = [] for k in aDict: if len(aDict[k])>num: num = len(aDict[k]) key += k return key[0]
067a95caabeef03368f80d3f8cf1062a4e233d8f
kmggh/cards
/play_lots_of_poker.py
1,155
3.625
4
#!/usr/bin/env python # Copyright (C) 2013 by Ken Guyton. All Rights Reserved. """Play many poker hands.""" import cards import hand import player NUM_HANDS = 1000 def improve_hand(the_player, deck): """Optionally throw out a card and draw another one.""" this_hand = hand.Hand(the_player.cards()) if this_hand.improve_hand(): the_player._cards = list(this_hand._cards) the_player.draw(deck) def play_hand(): """Play a single hand and return the result. Returns: A str which is the classification of this hand. """ deck = cards.Deck() deck.shuffle() player1 = player.Player('Player1') for unused_i in range(5): player1.draw(deck) # It's interesting to adjust the number of calls to improve_hand(). improve_hand(player1, deck) improve_hand(player1, deck) return hand.Hand(player1.cards()).classify() def main(): results = {} for unused_count in range(NUM_HANDS): result = play_hand() if result in results: results[result] += 1 else: results[result] = 1 print 'Results\n' for key, value in results.items(): print value, key if __name__ == '__main__': main()
f27cf24d5ac7b70478883102f72274717f9467fb
maximilianogomez/Progra1
/Practica 5/5.4.py
650
3.6875
4
# Todo programa Python es susceptible de ser interrumpido mediante la pulsación de # las teclas Ctrl-C, lo que genera una excepción del tipo KeyboardInterrupt. Realizar # un programa para imprimir los números enteros entre 1 y 100000, y que solicite # confirmación al usuario antes de detenerse cuando se presione Ctrl-C. #PROGRAMA PRINCIPAL: def main(): for i in range(1,100001): try: print(i) except KeyboardInterrupt: resp = input("Desea finalizar: (s/n) ") if resp.lower() == "s" or resp.lower() == "si": print("Fin") break main()
438ab9d7b217a8361d7cb5600bb1fe83e30ea99d
joselpereda/python-lab_06
/L6_4.py
925
3.5
4
#P6_6 Write a binary pickle file for serialization import pickle #std library for pickle file support from random import randrange #support from randam data #generate random data from a dictionary d = {} for each in range(65,95): d[chr(each)] = randrange(1000,2000) print('Pickle Data: ', d,end='\n\n') FILENAME ="mypickle.pickle" #file to write in current directory FILE_MODE ="wb" #open for write of binary data #pickle the generated data with open(FILENAME, FILE_MODE) as pickle_file: pickle.dump(d,pickle_file) #delete the dictionary del d #read the pickled data FILE_MODE = 'rb' with open(FILENAME, FILE_MODE) as pickle_file: pickled_data = pickle.load(pickle_file) #print pickled data print('Pickled data: ', pickled_data) print('Finished Reading:', FILENAME)
0f6f5c0dcd441d5da0ba595ff11aebc82407a4b8
buurro/interviews
/solutions/algorithms/fizzbang.py
237
3.6875
4
''' Problem: For the numbers 1 to 100, print fizz if divisible by 3, bang if divisible by 5. ''' print(', '.join(('fizz bang' if ii % 15 == 0 else 'fizz' if ii % 3 == 0 else 'bang' if ii % 5 == 0 else str(ii) for ii in range(1, 101))))
6d56e3132c60a29dd757bc0e2f47ace368f4459a
Yigang0622/LeetCode
/hIndex.py
435
3.8125
4
from typing import List # 274. H 指数 # https://leetcode-cn.com/problems/h-index/ class Solution: def hIndex(self, citations: List[int]) -> int: citations.sort(reverse=True) n = len(citations) # print(citations) i = 0 while i < n and i + 1 <= citations[i]: print() i += 1 return i citations = [3, 0, 6, 1, 5] r = Solution().hIndex(citations) print(r)
3e55998824cc3d02f5356c4561d8004d7243d4bb
PDXCodeGuildJan/SarahPDXCode2016
/Algorithms/bubbles.py
2,375
4.4375
4
unsorted_list=[6, 17, 9, 34, 4] print(unsorted_list) def bubble_sort(unsorted_list): #define a function listLength = len(unsorted_list) # 1)Find the length of the list #2) Compare the value of the current index and compare it with the value of the next index. firstItem = 0 while firstItem < listLength -1: #this starts the outter loop currentIndex = firstItem while currentIndex < listLength - 1: # need to establish an inner while loop - this says that while the current Index has any length #to use for comparison, keep loop but decrease the length by one each time # 3) Determine if value of current index is is greater than value of next index. if unsorted_list[currentIndex] > unsorted_list[currentIndex+1]: # 4) If it greater, swap with next index. If it is not greater, do nothing. #unsorted_list[currentIndex], unsorted_list[currentIndex+1] = unsorted_list[currentIndex+1], unsorted_list[currentIndex] tempSpot = unsorted_list[currentIndex] unsorted_list[currentIndex] = unsorted_list[currentIndex+1] unsorted_list[currentIndex+1] = tempSpot currentIndex += 1 #this makes sure that the index does up by one index each loop listLength -= 1 #6) Once end is reached, move the end point in by one. return unsorted_list sorted_list = bubble_sort(unsorted_list) print(sorted_list) """ Bubble Sort Given a list: 1) Find the lenth of the list 2) Compare the value of the current index and compare it with the value of the next index. 3) Determine if value of current index is is greater than value of next index. 4) If it greater, swap with next index. If it is not greater, do nothing. 5) Change current index to next index, repeat process for the length of the list. 6) Once end is reached, move the end point in by one. 7) Repeat process. while current_index < len(unsorted_list[first_number:]): #this moves """ #2) Compare the value of the current index and compare it with the value of the next index. #for firstItem,value in enumerate(unsorted_list): #this starts the outter loop #currentIndex = firstItem #if currentIndex #Does the currentIndex need to be identified as the lowest index?
692aaf8028b6cc5e887a369710b71f849119ab63
Retrnon/cse210-student-dice
/dice/game/thrower.py
815
3.640625
4
import random class Thrower(object): def __init__(self): """ Initializes object attributes """ self.dice = [] self.score = 0 def throw_dice(self): """ Clears previous Dice and throws Dice and randomizes 5d6 dice in self.dice """ self.dice.clear() for x in range(5): self.dice.append(random.randint(1, 6)) def get_points(self): """ Counts instances of 5s and 1s and returns the sum """ return (self.dice.count(5) * 50 + self.dice.count(1) * 100) def can_throw(self): """ Checks and returns True if there are any instances of 1s ir 5s in self.dice """ return any([die == 1 for die in self.dice]) or any([die == 5 for die in self.dice])
7ebdfdf519aaa85d76e5db870ee7655971280feb
jnst/x-python
/leetcode/q0002.py
997
3.734375
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: @classmethod def add_two_numbers(cls, l1: ListNode, l2: ListNode) -> ListNode: dummy = cur = ListNode(0) carry = 0 while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next cur.next = ListNode(carry % 10) cur = cur.next carry //= 10 return dummy.next if __name__ == '__main__': # [2, 4, 3] l1_3 = ListNode(3) l1_2 = ListNode(4) l1_1 = ListNode(2) l1_2.next = l1_3 l1_1.next = l1_2 # [5, 6, 4] l2_3 = ListNode(4) l2_2 = ListNode(6) l2_1 = ListNode(5) l2_2.next = l2_3 l2_1.next = l2_2 ans = Solution.add_two_numbers(l1_1, l2_1) # [7, 0, 8] assert ans.val == 7 assert ans.next.val == 0 assert ans.next.next.val == 8
fbf034dd3aa46185ee25d36f5bd82fbfb699a982
jpfogato/ObjDetc_RP3b-Autonomous_Vehicle
/Exemplos/functions.py
985
4.375
4
def jumpline(): print("\n") def my_function(): print("Hello World from a function") my_function() jumpline() def machado(name,surname): print(name + " " + surname + " Machado") machado("João","Paulo") jumpline() def multplicacao(input): resultado = 5*input return resultado print("resultado: ", multplicacao(3)) jumpline() # recursive functions (functions that call themselves def recursion(k): if(k>0): result = k+recursion(k-1) print(result) else: result = 0 return result recursion(10) jumpline() # lambda functions: x = lambda a: a*5 print(x(5)) x = lambda a,b: a*b print(x(5,6)) x = lambda a,b,c: a*b*c print(x(1,2,3)) jumpline() def func_lambda(n): return lambda a: a*n doubler = func_lambda(2) print(doubler(11)) # 11 is parsed as a function through doubler (a) jumpline() def multplier(n): return lambda a: a*n doubler=multplier(2) tripler=multplier(3) print(doubler(10)) print(tripler(10))