blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
037516f4744eee2121721a5806a1ebfa4c930b91
qianli2424/test11
/python_Practice/test.py
209
3.59375
4
# -*- coding-utf8 -*- # author :xiaosheng #文件说明 #创建时间:2019/12/16 print ('hello word') print(1+2*10) print('you age is \\test',str(20)) print(r'you age is \test',str(20)) print('hello','***')
6cd674cba2d8ca4e1e18695aa2ad1a2ae1cd36a7
nkorobkov/competitive-programming
/codeforces/1165/dtest.py
100
3.53125
4
print(25) for i in range(25): print(300) print(' '.join(list(map(str, range(i+3, i+303)))))
2299870e7d62ce84ed49d188bafcc519c744c09f
MACHEIKH/Datacamp_Machine_Learning_For_Everyone
/21_Introduction_to_Deep_Learning_with_Keras/2_Going_Deeper/exploringDollarBills.py
1,170
4.125
4
# Exploring dollar bills # You will practice building classification models in Keras with the Banknote Authentication dataset. # Your goal is to distinguish between real and fake dollar bills. In order to do this, the dataset comes with 4 features: variance,skewness,kurtosis and entropy. These features are calculated by applying mathematical operations over the dollar bill images. The labels are found in the dataframe's class column. # A pandas DataFrame named banknotes is ready to use, let's do some data exploration! # Instructions # 100 XP # Import seaborn as sns. # Use seaborn's pairplot() on banknotes and set hue to be the name of the column containing the labels. # Generate descriptive statistics for the banknotes authentication data. # Count the number of observations per label with .value_counts(). # Import seaborn import seaborn as sns # Use pairplot and set the hue to be our class column sns.pairplot(banknotes, hue='class') # Show the plot plt.show() # Describe the data print('Dataset stats: \n', banknotes.describe()) # Count the number of observations per class print('Observations per class: \n', banknotes['class'].value_counts())
0416e3b28cd13cd7eea9ef20e0dcaaba04f0aa11
SpykeX3/NSUPython2021
/problems-2/v-nikiforov/problem1.py
198
3.546875
4
n = int(input()) print( [ (x, y, z) for x in range(1, n) for y in range(1, n) for z in range(1, n) if x ** 2 + y ** 2 == z ** 2 if x <= y ] )
674d299bcd7d2103c99954e3d4730513a39d27e4
cwjshen/dailycodingproblems
/python/3-serialize-binary-tree.py
2,259
3.984375
4
# This problem was asked by Google. # Given the root to a binary tree, implement serialize(root), # which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. # For example, given the following Node class # class Node: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # The following test should pass: # node = Node('root', Node('left', Node('left.left')), Node('right')) # assert deserialize(serialize(node)).left.left.val == 'left.left' class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def serialize(node_tree): if node_tree == None: return 'null' return '{"val": "' + node_tree.val + '","left":' + serialize(node_tree.left) + ',"right":' + serialize(node_tree.right) + '}' def deserialize(node_string): if node_string == 'null': return None # Remove leading and trailing bracket node_string = node_string[1:-1] ## Get value of current node node_val = node_string.split(',', 1)[0].split(':')[1] node_left_val_string = 'null' node_right_val_string = 'null' ## Get value of current left # Remaining string contains current left and right remaining_string = node_string.split(',', 1)[1].split(':', 1)[1] print('Remaining string: ', remaining_string) # Isolating left node object if it exists if remaining_string.startswith('{'): bracket_counter = 1 # Starts at one because of space at beginning of string char_index = 1 while bracket_counter > 0: if remaining_string[char_index] == '{': bracket_counter += 1 elif remaining_string[char_index] == '}': bracket_counter -= 1 char_index += 1 node_left_val_string = remaining_string[:char_index] # If doesn't exist, then check right node else: node_right_val_string = remaining_string.split(',', 1)[1].split(':', 1)[1] return Node(node_val, deserialize(node_left_val_string), deserialize(node_right_val_string)) root = Node('root') node1 = Node('root', Node('left'), Node('right')) node2 = Node('root', Node('left', Node('left.left')), Node('right')) print(serialize(node2)) print(deserialize(serialize(node2)).left.left.val)
fe6cfad1f1855e147acb40294a1dee598120db2a
nickthorpe71/python-playground
/cs50/pset6/lecture/scores.py
130
3.703125
4
scores = [72,73,33,33,55,66,77,88] print("Average: " + str(sum(scores) / len(scores))) s = raw_input("type: ") print(s.upper())
1af60fd5d0831c800e6f58d476187baa35f22b1f
tingxuelouwq/python
/src/com.kevin.python/advance/generator.py
834
4.09375
4
# 生成器 # 斐波那契数列模块 def fib(n): print(__name__) count, a, b = 0, 0, 1 while count < n: print(a, end=' ') a, b = b, a + b count = count + 1 print() def fib2(n): print(__name__) count, a, b = 0, 0, 1 while count < n: yield a a, b = b, a + b count = count + 1 # 杨辉三角形 def pascal_triangle(line): i, arr = 0, [1] for n in range(line): print(arr) arr = [1] + [arr[i] + arr[i + 1] for i in range(0, len(arr) - 1)] + [1] def pascal_triangle2(line): i, arr = 0, [1] for n in range(line): yield arr arr = [1] + [arr[i] + arr[i + 1] for i in range(0, len(arr) - 1)] + [1] if __name__ == '__main__': print(__name__) fib(5) for arr in pascal_triangle2(2): print(arr)
f94522e9cf49ceae0a05c6e3dc52d31be1f3ce4b
ryanolv/Learning-Python
/DesafioPOO/clientes.py
426
3.6875
4
from abc import ABC, abstractmethod class Pessoa(ABC): def __init__(self,nome,idade): self.__nome = nome self.__idade = idade @property def nome(self): return self.__nome @property def idade(self): return self.__nome class Cliente(Pessoa): def __init__(self,nome,idade,conta): super().__init__(nome,idade) self.conta = conta
e9b4f17bf11e18f4c64a0928561c713c3a4415b8
gabrielramospereira/codes
/python/ex038 - maior.py
319
4.09375
4
n1 = int(input('Digite o primeiro número:')) n2 = int(input('Digite o segundo número: ')) if n1 > n2: print('O número {} é maior que o número {}'.format(n1,n2)) elif n1 < n2: print('O número {} é menor que o número {}'.format(n1,n2)) else: print('O número {} é igual ao número {}'.format(n1,n2))
f66fc1caf0f7ffcbaa91e0f97448dedb52d277ad
debolina-ca/my-projects
/Python Codes 2/List with count().py
250
4.09375
4
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"] search_letter = "a" total = 0 for city_name in cities: total += city_name.lower().count("a") print("No. of 'a's in the list is", total)
26217d1ae8669e89d8257b3d1aa14987a7ee98f3
IshfaqKhawaja/Saving-Lists-in-Python-without-use-of-numpy-or-pickle
/Saving_lists_into_text_file.py
627
3.859375
4
# If you wanna save list into txt file and load it as list in python # IF you wanna save list into file as retrieve it back as list # with out using pickle or numpy in python # here is a trick import json data = [1, 2, 3, 4, 5] print(data[4]+data[2]) with open('bin.data', "wb") as file: file.write(json.dumps(data).encode()) # Encoding is necessary because we are saving # it in binary format# Run it now # Reading list back with open("bin.data", "rb") as file: data = file.read() data = json.loads(data) # Reading from file as list print(data) print(data[4] + data[2]) # Boom
ecace532f38b915b5722b61849f20fc9c82d23bb
KBataev/lab_python
/1/lab3.1.py
124
3.515625
4
string = 'FastEthernet0/1' print(string.replace('Fast', 'Gigabit')) MAC = 'AAAA:BBBB:CCCC' print(MAC.replace(':', '.'))
1d338b65838d5b0dc83b664f1233fd639e141dba
karolinanikolova/SoftUni-Software-Engineering
/1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/03_Conditional-Statements-Advanced/00.Book-Exercise-4.1-13-Point-in-the-Figure.py
1,864
4.09375
4
# точка във фигурата # Фигура се състои от 6 блокчета с размер h * h, разположени като на фигурата. Долният ляв ъгъл на сградата е на позиция {0, 0}. # Горният десен ъгъл на фигурата е на позиция {2*h, 4*h}. На фигурата координатите са дадени при h = 2: # # Да се напише програма, която въвежда цяло число h и координатите на дадена точка {x, y} (цели числа) и отпечатва дали # точката е вътре във фигурата (inside), вън от фигурата (outside) или на някоя от стените на фигурата (border). h = int(input()) x = float(input()) y = float(input()) # check to see if dot is inside rectangle 1 dot_inside_horizontal_rectangle = 0 < x < (3 * h) and 0 < y < h # check to see if dot is inside rectangle 2 dot_inside_vertical_rectangle = h < x < (2 * h) and 0 < y < (4 * h) # check to see if dot is on one of the borders dot_on_bottom_border = 0 <= x <= (3 * h) and y == 0 dot_on_middle_border = (0 <= x <= h or (2 * h) <= x <= (3 * h)) and y == h dot_on_top_border = h <= x <= (2 * h) and y == (4 * h) dot_on_left_border = x == 0 and 0 <= y <= h dot_on_middle_left_border = x == h and h <= y <= (4 * h) dot_on_middle_right_border = x == (2 * h) and h <= y <= (4 * h) dot_on_right_border = x == (3 * h) and 0 <= y <= h if dot_inside_horizontal_rectangle or dot_inside_vertical_rectangle: print('inside') elif dot_on_bottom_border or dot_on_middle_border or dot_on_top_border or dot_on_left_border or \ dot_on_middle_left_border or dot_on_middle_right_border or dot_on_right_border: print('border') else: print('outside')
c95cea11aa99a9f21bf821bbca44407cea3d60f9
QuisEgoSum/different
/algorithms/sort/insertion/insertion.py
478
3.84375
4
def main(): lenght = int(input('Lenght: ')) array = [None] * lenght for i in range(lenght): array[i] = int(input('Item {}: '.format(i))) print('Source array: ', array) for i in range(lenght): key = array[i] j = i - 1 while j >= 0 and array[j] > key: array[j + 1] = array[j] j = j - 1 array[j + 1] = key print('Sorted array: ', array) if __name__ == "__main__": main()
0d6867a6f7cd976bbc731645aac7244357e6af12
WayneLambert/portfolio
/apps/blog/search.py
201
3.53125
4
import re def cleanup_string(q: str) -> str: """ Performs initial cleanup removing superfluous characters """ pattern = '[^a-zA-Z0-9" ]+' return re.sub(pattern, '', q).strip().casefold()
641dca7ade0794d21a667aa6b2380417f2e92ff3
popovale/python-stepic
/zad3_slovar_s_funcshion_v2_rab.py
208
3.578125
4
# Задача на словари урок3.2 def f(x): rez=x+1 return rez n=int(input()) d={} for i in range(n): x = int(input()) if x not in d: d[x]=f(x) print(d[x]) # print(d)
9212aab6bd078818314fb123c6d466952c50cf29
msilvprog7/get-with-the-program
/world/characters.py
5,521
3.890625
4
import pygame class Face: """ Represent the direction a character is facing """ LEFT = -1 RIGHT = 1 @staticmethod def is_facing_left(face): """ See if character is facing left """ return face == Face.LEFT @staticmethod def is_facing_right(face): """ See if character is facing right """ return face == Face.RIGHT class Speed: """ Represents the speed at which a character is moving """ STOP = 0 WALK = 1 RUN = 2 @staticmethod def is_stopped(speed): """ See if character is stopped """ return speed == Speed.STOP @staticmethod def is_walking(speed): """ See if character is walking """ return speed == Speed.WALK @staticmethod def is_running(speed): """ See if character is running """ return speed == Speed.RUN class Character(pygame.sprite.Sprite): """ State and basic functionality of a movable character """ def __init__(self, position): """ Constructor """ super(Character, self).__init__() self.position = position self.size = (0, 0) self.face = Face.RIGHT self.speed = Speed.STOP self.is_running = False self.is_jumping = False self.can_jump = True self.is_rolling = False self.can_roll = True self.is_falling = False self.can_fall = False self.health = 1 self.has_health = True def step(self, level): """ Update the character's position """ # Move forward if not Speed.is_stopped(self.speed): self.position = (self.position[0] + self.face * self.size[0] * Speed.WALK, self.position[1]) # If running (*** cut early if running through the flag ***) self.is_running = Speed.is_running(self.speed) and not level.flag_reached(self) \ and not level.collided_with_standing_object(self) \ and not(not self.is_rolling and level.collided_with_ceiling_spikes(self)) # Check fall after a jump if (self.can_fall and not self.can_jump): self.fall(should_die=False) # Check for jumping (handle double turn) if self.is_jumping: self.position = (self.position[0], self.position[1] - self.size[1]) self.is_jumping = False self.can_jump = False else: self.can_jump = True # Check for rolling (handle double turn) if self.is_rolling: self.is_rolling = False self.can_roll = False else: self.can_roll = True # Check for falling in hole if (self.can_jump and not Speed.is_stopped(self.speed) and self.can_fall and level.hole_beneath(self)): self.is_falling = True def fall(self, should_die): """ Make the character fall a space """ self.position = (self.position[0], self.position[1] + self.size[1]) if should_die: self.health = 0 self.speed = Speed.STOP self.is_falling = False def finish_run(self, level): """ Finish a running motion """ # Move forward if not Speed.is_stopped(self.speed): self.position = (self.position[0] + self.face * self.size[0] * Speed.WALK, self.position[1]) # Check for falling in hole if (self.can_jump and not Speed.is_stopped(self.speed) and self.can_fall and level.hole_beneath(self)): self.is_falling = True class Player(Character): """ Main character with appropriate controls that the World can control """ def __init__(self, position, size, color): """ Constructor """ super(Player, self).__init__(position) # Properties self.speed = Speed.WALK self.can_fall = True self.winner = False # Image self.size = size self.image = pygame.Surface([size[0], size[1]]) self.image.fill(color) self.sprite_sheet = None def set_sprite_sheet(self, file): """ Set the sprite sheet """ self.sprite_sheet = pygame.image.load(file).convert() self.sprite_sheet_pos = (257, 12) self.sprite_sheet_size = (30, 57) self.sprite_offset = (0, 10) def get_sprite(self): """ Get the current sprite """ rect = pygame.Rect((self.sprite_sheet_pos[0], self.sprite_sheet_pos[1], \ self.sprite_sheet_size[0], self.sprite_sheet_size[1])) image = pygame.Surface(rect.size).convert() image.blit(self.sprite_sheet, (0, 0), rect) image.set_colorkey((255, 255, 255), pygame.RLEACCEL) return image def get_sprite_position(self): """ Get the current sprite's position """ return (self.position[0] + (self.size[0] - self.sprite_sheet_size[0]) // 2 + self.sprite_offset[0], \ self.position[1] + (self.size[1] - self.sprite_sheet_size[1]) // 2 + self.sprite_offset[1]) def check_for_death(self, level): """ Check if player has gone off screen, collided with an object, or collided with ceiling spikes """ if level.past_end(self) or level.collided_with_standing_object(self) or \ (self.can_roll and not self.is_rolling and level.collided_with_ceiling_spikes(self)): self.health = 0 self.speed = Speed.STOP def step(self, level): """ Update player's position """ super(Player, self).step(level) # Check if flag reached or death if level.flag_reached(self): self.speed = Speed.STOP self.winner = True elif level.past_end(self) or level.collided_with_standing_object(self) or \ (self.can_roll and not self.is_rolling and level.collided_with_ceiling_spikes(self)): self.health = 0 self.speed = Speed.STOP def jump(self, level): """ Set state to jumping """ if self.can_jump: self.is_jumping = True self.step(level) def run(self, level): """ Change speed to fast """ self.speed = Speed.RUN self.step(level) def walk(self, level): """ Change speed to slow """ self.speed = Speed.WALK self.step(level) def roll(self, level): """ Change to crouching roll """ if self.can_roll: self.is_rolling = True self.step(level)
5fce0c197cabb709c75775f5acc3cddd1d2411c1
BerilBBJ/scraperwiki-scraper-vault
/Users/N/NicolaHughes/dod-contracts.py
3,724
3.609375
4
import scraperwiki from bs4 import BeautifulSoup # documentation at http://www.crummy.com/software/BeautifulSoup/bs4/doc/ # Searching for "Minsitry of Defence" on contracts finder excluding tenders fewing 200 results per page search_page = "http://www.contractsfinder.businesslink.gov.uk/Search%20Contracts/Search%20Contracts%20Results.aspx?site=1000&lang=en&sc=3fc5e794-0cb4-4c10-be10-557f169c4c92&osc=db8f6f68-72d4-4204-8efb-57ceb4df1372&rb=1&ctlPageSize_pagesize=200&ctlPaging_page=" # We need to know how many result pages we have to scrape i.e. when to stop scraping. The number of results is on the first page # BeautifulSoup allows the programme to read html elements rather than seeing it as raw text html = scraperwiki.scrape(search_page + "1") soup = BeautifulSoup(html) # Finding the number of results # We isolate the html element containing the number of results max = soup.find(id="resultsfound") num = int(max.get_text().strip().split(" ")[2]) #print num # Calculating the last page number when we have asked for 200 results per page if num % 200 != 0: last_page = int(num/200) + 1 else: last_page = int(num/200) #print last_page # Paginate over pages up to last page for n in range(1,last_page + 1): # Extract html html = scraperwiki.scrape(search_page + str(n)) # Make it searchable by BeautifulSoup soup = BeautifulSoup(html) # Links to contracts have attribute "a" with class "notice-title" so pulling out all of those links = soup.find_all("a", "notice-title") #Adding ids to each row counter = (n -1 ) * 200 + 1 # Getting the individual links and saving them into ScraperWiki database for link in links: url = link['href'] data = {"URL": url, "id": counter} scraperwiki.sqlite.save(["URL"], data) # Increment the counter counter += 1 import scraperwiki from bs4 import BeautifulSoup # documentation at http://www.crummy.com/software/BeautifulSoup/bs4/doc/ # Searching for "Minsitry of Defence" on contracts finder excluding tenders fewing 200 results per page search_page = "http://www.contractsfinder.businesslink.gov.uk/Search%20Contracts/Search%20Contracts%20Results.aspx?site=1000&lang=en&sc=3fc5e794-0cb4-4c10-be10-557f169c4c92&osc=db8f6f68-72d4-4204-8efb-57ceb4df1372&rb=1&ctlPageSize_pagesize=200&ctlPaging_page=" # We need to know how many result pages we have to scrape i.e. when to stop scraping. The number of results is on the first page # BeautifulSoup allows the programme to read html elements rather than seeing it as raw text html = scraperwiki.scrape(search_page + "1") soup = BeautifulSoup(html) # Finding the number of results # We isolate the html element containing the number of results max = soup.find(id="resultsfound") num = int(max.get_text().strip().split(" ")[2]) #print num # Calculating the last page number when we have asked for 200 results per page if num % 200 != 0: last_page = int(num/200) + 1 else: last_page = int(num/200) #print last_page # Paginate over pages up to last page for n in range(1,last_page + 1): # Extract html html = scraperwiki.scrape(search_page + str(n)) # Make it searchable by BeautifulSoup soup = BeautifulSoup(html) # Links to contracts have attribute "a" with class "notice-title" so pulling out all of those links = soup.find_all("a", "notice-title") #Adding ids to each row counter = (n -1 ) * 200 + 1 # Getting the individual links and saving them into ScraperWiki database for link in links: url = link['href'] data = {"URL": url, "id": counter} scraperwiki.sqlite.save(["URL"], data) # Increment the counter counter += 1
60ffff6e36f65c3e85fed41153792313f2ede3c9
rojit1/python_assignment
/q15.py
354
4.25
4
# 15. Write a Python function to insert a string in the middle of a string. # Sample function and result : # insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]] # insert_sting_middle('{{}}', 'PHP') -> {{PHP}} def insert_sting_middle(s1, s2): middle = len(s1)//2 return s1[:middle]+s2+s1[middle:] print(insert_sting_middle('{{}}', 'PHP'))
4aab3e8608e1c8710b1f62c9dbfcb39cb03c060d
SudhuM/Cart-Manager
/CartManager.py
4,324
3.5
4
from tkinter import * from tkinter import messagebox from tkinter import Event from tkinter import Listbox # app initilaization app = Tk() app.title("Parts Manager") app.geometry('550x330') # keeps entries = [] # text_variable = StringVar() # entry addition to the list box with proper checking , whether the users # filled out all the fields. def add_entry(): data = (parts_entry.get(), Customer_entry.get(), Retailer_entry.get(), Price_entry.get()) if showerror(data): messagebox.showerror( 'Empty Fields', 'please enter all the required fileds') else: entries.append(data) list_box.insert(END, Entry_format(entries)) print(entries) clear_entry() # update elements command . def update_items(): data = (parts_entry.get(), Customer_entry.get(), Retailer_entry.get(), Price_entry.get()) if showerror(data): messagebox.showerror( 'Empty Fields', 'please enter all the required fields.') else: entries.remove(entries[index]) entries.insert(index, data) list_box.insert(END, Entry_format(entries)) # Items will removed when remove is pressed. # remove the elements from last. # can be changed - reverse the list befoe poping. def remove_items(): # entries.pop() entries.remove(value) clear_entry() Entry_format(entries) if len(entries) == 0: remove_button['state'] = 'disabled' update_button['state'] = 'disabled' # when button clear is pressed the entered values in the entry will be removed def clear_entry(): parts_entry.delete(0, END) Customer_entry.delete(0, END) Retailer_entry.delete(0, END) Price_entry.delete(0, END) def showerror(data): if not all(data): return True return False # styling the listbox entry def Entry_format(t): list_box.delete(0, END) for i in t: # list_box.insert( # END, '{} - {} -{} under {}'.format(i[1], i[2], i[3], i[0])) list_box.insert(END, i) remove_button['state'] = 'active' update_button['state'] = 'active' # event for getting the selected element data def onselect(event): global value, index w = event.widget index = int(w.curselection()[0]) value = w.get(index) populate(value) # print(index) # populate the entry values def populate(value): clear_entry() parts_entry.insert(0, value[0]) Customer_entry.insert(0, value[1]) Retailer_entry.insert(0, value[2]) Price_entry.insert(0, value[3]) # parts Name parts_name = Label(app, text='Parts Name') parts_name.grid(row=0, column=0, padx=5, pady=20, sticky=W) parts_entry = Entry(app, borderwidth=3) parts_entry.grid(row=0, column=1, padx=10) # Customer Name Customer_name = Label(app, text='Customer') Customer_name.grid(row=0, column=2, padx=5, sticky=W) Customer_entry = Entry(app, borderwidth=3) Customer_entry.grid(row=0, column=3) # Retailer Name Retailer_name = Label(app, text='Retailer') Retailer_name.grid(row=1, column=0, sticky=W, padx=5) Retailer_entry = Entry(app, borderwidth=3) Retailer_entry.grid(row=1, column=1, padx=10) # Price Price_name = Label(app, text='Price') Price_name.grid(row=1, column=2, sticky=W, padx=5) Price_entry = Entry(app, borderwidth=3) Price_entry.grid(row=1, column=3, pady=20) # ListBox list_box = Listbox(app, height=8, width=50, border=0) list_box.bind('<<ListboxSelect>>', onselect) list_box.grid(row=4, column=0, columnspan=3, rowspan=6, padx=20, pady=20) # scrollbar scrollbar = Scrollbar(app) scrollbar.grid(row=4, column=3, pady=30) # scrollbar configuration with listbox list_box.configure(yscrollcommand=scrollbar.set) scrollbar.configure(command=list_box.yview) # buttons add_button = Button(app, text="Add", width=10, command=add_entry) add_button.grid(row=2, column=0, padx=5) update_button = Button(app, text="Update", width=10, state='disabled', command=update_items) update_button.grid(row=2, column=1, padx=5) remove_button = Button(app, text="Remove", width=10, state='disabled', command=remove_items) remove_button.grid(row=2, column=2, padx=5) clear_button = Button(app, text="Clear", width=10, command=clear_entry) clear_button.grid(row=2, column=3, padx=5) app.mainloop()
a29ecb8b2d9f1f3971b4877bfd1eefa739bc47a8
Momotaro10000/Arithmetic-arranger
/arithmetic_arranger.py
1,819
3.765625
4
def arithmetic_arranger(problems, *args): if len(problems) > 5: return "Error: Too many problems." result = [] for problem in problems: operation = problem.split() if operation[0].isnumeric() is False or operation[2].isnumeric() is False: return "Error: Numbers must only contain digits." if len(operation[0]) > 4 or len(operation[2]) > 4: return "Error: Numbers cannot be more than four digits." if operation[1] != "+" and operation[1] != "-": return "Error: Operator must be '+' or '-'." longest_number = max(len(operation[0]), len(operation[2])) width = int(longest_number + 2) line1 = f"{operation[0]:>{width}}" line2 = operation[1] + f"{operation[2]:>{width -1}}" dashes = '-' * width operation_result = int(operation[0]) + int(operation[2]) if operation[1] == "+" else int(operation[0]) - int(operation[2]) operation_result = f"{operation_result:>{width}}" try: result[0] += (" " * 4) + line1 except IndexError: result.append(line1) try: result[1] += (" " * 4) + line2 except IndexError: result.append(line2) try: result[2] += (" " * 4) + dashes except IndexError: result.append(dashes) if args: try: result[3] += (" " * 4) + operation_result except IndexError: result.append(operation_result) arranged_problems = f"{result[0]}\n{result[1]}\n{result[2]}" arranged_problems = arranged_problems + f"\n{result[3]}" if args else arranged_problems return arranged_problems
23b678da96b21df5751eb1ff23c55f34aeac589c
maribelcuales/Intro-Python
/src/dicts.py
534
4.34375
4
# Make an array of dictionaries. Each dictionary should have keys: # # lat: the latitude # lon: the longitude # name: the waypoint name # # Make up three entries of various values. waypoints = [ { "lat": "33.888 S", "lon": "151.2093 E", "name": "Sydney" }, { 'lat': 106.7288, 'lon': 0.69622, 'name': 'Hawaii' }, ] # Write a loop that prints out all the field values for all the waypoints for name in waypoints: # print(name) print("The name of the waypoint is {0[name]}.".format(name))
b93bbd2068c67bc94239d28f81e6a2678915bb0b
valleyceo/code_journal
/1. Problems/i. Recursion & Backtrack/Template/d. Random - Random Subset.py
857
3.984375
4
# Compute a Random Subset ''' - Given a positive integer n and a size k <= n - Return a size-k subset from {0, 1, 2, ..., n-1} ''' # time: O(k) | space: O(k) def random_subset(n: int, k: int) -> List[int]: changed_elements: Dict[int, int] = {} for i in range(k): # Generate a random index between i and n - 1, inclusive. rand_idx = random.randrange(i, n) rand_idx_mapped = changed_elements.get(rand_idx, rand_idx) i_mapped = changed_elements.get(i, i) changed_elements[rand_idx] = i_mapped changed_elements[i] = rand_idx_mapped return [changed_elements[i] for i in range(k)] ''' - picks a random number and creates cyclic hash map - if same number gets picked, merges with parts - Note: this algorithm ends up creating unique numbers both in .first (0-k) and .second (0-n) in random orders '''
befc8b7ef2057879e52240ac09cb74bd51bb173e
ioannis-papadimitriou/snagger
/Classic_ML/DL/ANN/.ipynb_checkpoints/full_ann-checkpoint.py
3,577
3.515625
4
# Artificial Neural Network # Installing Theano # pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git # Installing Tensorflow # Install Tensorflow from the website: https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html # Installing Keras # pip install --upgrade keras # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] #get rid of one column to avoid dummy variable trap # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling (compulsory for ANN) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Part 2 - Now let's make the ANN! # Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense # Initialising the ANN classifier = Sequential() # Adding the input layer and the first hidden layer classifier.add(Dense(output_dim = 10, init = 'uniform', activation = 'relu', input_dim = 11)) # output_nod number of nodes of the hidden layer - tip: averge of the number of nodes in the input layer and the output layer # Adding the second hidden layer classifier.add(Dense(output_dim = 8, init = 'uniform', activation = 'relu')) # now input_dim is not needed # Adding the second hidden layer classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu')) # Adding the output layer classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid')) # Compiling the ANN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training set classifier.fit(X_train, y_train, batch_size = 10, epochs = 100) # Part 3 - Making the predictions and evaluating the model # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Applying k-Fold Cross Validation from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10) accuracies.mean() accuracies.std() # Applying Grid Search to find the best model and the best parameters from sklearn.model_selection import GridSearchCV parameters = [{'C': [1, 10, 100, 1000], 'kernel': ['linear']}, {'C': [1, 10, 100, 1000], 'kernel': ['rbf'], 'gamma': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]}] grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 10, n_jobs = -1) grid_search = grid_search.fit(X_train, y_train) best_accuracy = grid_search.best_score_ best_parameters = grid_search.best_params_
64022fc90de1ee460faef1ce06a76e7c41e21e19
wimbuhTri/Kelas-Python_TRE-2021
/P4/tugas3.py
115
3.9375
4
X=int(input("1: ")) Y=int(input("2: ")) P=X+Y if P >= 0: print("+") Q = X*Y else: print("-") Q = X/Y print(Q)
8437844878811a6676423a6c86dda682c14171a3
remixknighx/quantitative
/exercise/leetcode/validate_stack_sequences.py
1,062
3.75
4
# -*- coding: utf-8 -*- """ 946. Validate Stack Sequences @link https://leetcode.com/problems/validate-stack-sequences/ """ from typing import List class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: empty_stack = [] for push_word in pushed: empty_stack.append(push_word) if push_word == popped[0]: empty_stack.pop() popped.pop(0) while True: if empty_stack and empty_stack[len(empty_stack) - 1] == popped[0]: empty_stack.pop() popped.pop(0) else: break return len(empty_stack) == 0 and len(popped) == 0 if __name__ == '__main__': pushed = [1, 2, 3, 4, 5] popped = [4, 5, 3, 2, 1] print(Solution().validateStackSequences(pushed=pushed, popped=popped)) pushed2 = [1, 2, 3, 4, 5] popped2 = [4, 3, 5, 1, 2] print(Solution().validateStackSequences(pushed=pushed2, popped=popped2))
9eb2642f9f08989c3ddc5399f7a41c7946e9b0bf
FirelCrafter/Code_wars_solutions
/6_kyu/Your_order_please.py
153
3.5
4
def order(sentence): return ' '.join(sorted(sentence.split(), key=lambda a: next(b for b in a if b.isdigit()))) print(order('is2 Thi1s T4est 3a'))
763afd2ec62a37b7de57e7eb84c259c92d82060b
MurradA/pythontraining
/Challenges/P106.py
139
3.5
4
file = open("P106_Names.txt", "w") for i in range(0,5): name = input("Enter a name: ").strip() file.write(name+"\n") file.close()
533393575c6060207a283ff9f5ac46712180d1eb
DavidMarquezF/InfoQuadri2
/Exercicis Puntuables/Exercici Entregable 3 - Kursaal/Entrada.py
1,385
3.765625
4
class EntradaGeneral(object): def __init__(self, nom, preu = 10): self.galliner=True self.nom = nom self.__preu = preu def __eq__(self, other): return False def __str__(self): print "Entrada KURSAAL" if(self.galliner): return "Galliner. " + str(self.getPreu()) + " EUR" else: return "Platea. " def getPreu(self): return self.__preu class EntradaPlatea(EntradaGeneral): def __init__(self, nom, preu = 50, fila = 0, seient = 0): super(EntradaPlatea, self).__init__(nom,preu) self.galliner = False self.fila = fila self.seient = seient def __str__(self): return super(EntradaPlatea, self).__str__() + " Fila: "+ str(self.fila) + " Seient: " + str(self.seient) +" "+ str(self.getPreu()) +" EUR" def __eq__(self, other): if(isinstance(other, EntradaGeneral)): return False return self.seient == other.seient and self.fila == other.fila and self.nom == other.nom if(__name__ == "__main__"): e1 = EntradaGeneral("Trio Guarnieri", preu=23) print e1 e2 = EntradaPlatea("The Dubliners", preu=40, fila=3, seient=24) print e2 print e1.getPreu() print e2.getPreu() print EntradaPlatea("The Dubliners", fila=3, seient=24) == e2 print e1 == e2 print e1 == EntradaGeneral("dasda")
75a4784e4a2aab4095c2df618b19fc1fbf776369
grogsy/python_exercises
/other/memoization/tower_of_hanoi.py
336
3.734375
4
# This example(and other recursive examples in general) seem to benefit from memoization def hanoi(n): '''calculate the number of moves it costs to move disks among three needles in such a way that larger disks cannot be placed on top of smaller disks''' if n == 0: return 0 else: return 2 * hanoi(n-1) + 1
e3c593a994bd3f9677bac179f668bbeb2cadbdb2
yaswanth12365/coding-problems
/find largest number in a list.py
173
4.3125
4
# Python program to find largest # number in a list # list of numbers list1 = [10, 20, 4, 45, 99] # printing the maximum element print("Largest element is:", max(list1))
80d35e56201b616e3b6c7bd91849d84da5840cd8
anila-a/CEN-206-Data-Structures
/lab07/ex4.py
548
4.03125
4
''' Program: ex4.py Author: Anila Hoxha Last date modified: 05/08/2020 Given a Binary Search Tree. The task is to find the maximum element in this given BST. If the tree is empty, there is no minimum element, so print -1 in that case. ''' from bst import * n = input() n = list(map(int, n.split(" "))) # Split the string tree = BinarySearchTree(n[0]) # Create root for i in range(1, len(n)): # Iterate through node values tree.insert_node(n[i]) # Create child nodes print(tree.find_max()) # Print the node with the maximum value
1e520c233587ac1a817a29a8a04df0bcba727612
Shrimad-Bhagwat/DODGE-CAR-RACE
/main.py
11,189
3.78125
4
#Importing the library import pygame from car import Car,Bush import random from pygame import mixer pygame.init() #define some colors BLACK = (0,0,0,) WHITE = (255,255,255) GREEN = (0,255,0) DARK_GREEN = (0,100,0) RED = (255,0,0) GREY = (169,169,169) DARK_GREY = (71,71,71) # light shade of the button color_light = (180,180,180) # dark shade of the button color_dark = (100,100,100) # open a new window size = W,H=500,700 screen = pygame.display.set_mode(size) pygame.display.set_caption('Car Racing') #Caption for the Game icon = pygame.image.load('images/icon.png') # Game Icon pygame.display.set_icon(icon) # stores the width of the screen into a variable width = screen.get_width() # stores the height of the screen into a variable height = screen.get_height() # Creating List of all the sprites we will use all_sprites_list = pygame.sprite.Group() cars = ['images/car.png','images/enemy.png','images/enemy1.png','images/enemy2.png'] #List of all cars #All opponent cars List all_coming_cars = pygame.sprite.Group() #Creating a Player Car and giving its position playerCar = Car(RED,60,96,cars[0]) playerCar.rect.x = 270 playerCar.rect.y = 500 #Adding this Player car sprite to the list of sprites all_sprites_list.add(playerCar) #Creating a Enemy Car and giving its position def create_enemy(): '''Creates a enemy Car''' global enemyCar try: enemyCar = Car(RED,60,96,cars[random.randint(1,3)]) # Created a Car lane = random.randint(0,1) # Choosing a random lane if lane == 0: enemyCar.rect.x = random.randint(100,160) elif lane == 1: enemyCar.rect.x = random.randint(260,340) enemyCar.rect.y = random.randint(-150,-100) except: print("Error creating an enemy.") #Adding this car sprite to the list of sprites all_sprites_list.add(enemyCar) all_coming_cars.add(enemyCar) def background(): '''Creates a background for the Game''' # Background try: screen.fill(DARK_GREEN) except: print("Background fill not completed") # Road pygame.draw.rect(screen, DARK_GREY, [70, 0, 360, 700],0) pygame.draw.line(screen, WHITE, [70, 0], [70, 700], 4) pygame.draw.line(screen, WHITE, [250, 0], [250, 700], 4) pygame.draw.line(screen, WHITE, [430, 0], [430, 700], 4) def game_over(): '''Game Over!''' mixer.music.stop() #Game Over Window game_over_loop = True while game_over_loop: # Display the background screen.fill(GREY) #Game Over Message font = pygame.font.Font('freesansbold.ttf',50) status = font.render("Game Over",True,(255,0,0)) crash = font.render("CAR CRASHED",True,(255,0,0)) screen.blit(crash,(62,200)) screen.blit(status,(110,270)) score() pygame.display.flip() # Exiting controls for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close add_high_score() pygame.quit quit() def high_score(): ''' Displays High Score''' # try: font = pygame.font.Font('freesansbold.ttf',30) high_score = font.render("Highscore : "+(all_scores[-1]),True,BLACK) screen.blit(high_score,(10,40)) # except: # print("Error displaying High Score") def add_high_score(): '''Adds Highscore to a file''' try: with open('highscore.txt','a') as f: f.write(str(score_value)+',') except: print("Error adding highscore") def score(): ''' Displays score''' global all_scores try: font = pygame.font.Font('freesansbold.ttf',30) score = font.render("Score : "+str(score_value),True,BLACK) screen.blit(score,(10,10)) except: print("Error displaying Score") with open('highscore.txt','r') as f: x = f.read() all_scores = x.split(',') all_scores.sort() def off_road(): '''Displays message if car goes Off Road''' font = pygame.font.Font('freesansbold.ttf',30) score = font.render("Car going Off Road!",True,RED) screen.blit(score,(100,50)) def game_buttons(button_text): smallfont = pygame.font.SysFont('calibri',35) # button font quit_text = smallfont.render('Quit' , True , WHITE) # quit button text start_text = smallfont.render(button_text , True , WHITE) # start button text buttons = True while buttons: mouse = pygame.mouse.get_pos() # to get position of cursor for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close buttons = False # Terminate the loop pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: # quit button conditions if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.quit() # start button conditions elif width/2-140 <= mouse[0] <= width/2 and height/2 <= mouse[1] <= height/2+40: buttons = False else: pass try: # Quit button hover if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) else: pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) screen.blit(quit_text , (width/2+35,height/2+5)) # Start butto hover if width/2-140 <= mouse[0] <= width/2 and height/2 <= mouse[1] <= height/2+40: pygame.draw.rect(screen,color_light,[(width/2)-160,(height/2),155,40]) else: pygame.draw.rect(screen,color_dark,[(width/2)-160,(height/2),155,40]) screen.blit(start_text , (width/2-150,height/2+5)) pygame.display.update() # Updates the Screen except: print("Something went Wrong") def game_intro(): ''' Game Starts here. This is the Landing Page of the Game.''' intro = True while intro: # Display the background screen.fill(GREY) # Creates Background img = pygame.image.load("images/car main.png") # Intro Page Image screen.blit(img,(-90,30)) font = pygame.font.Font('freesansbold.ttf',40) # Intro Page Text start = font.render("Dodge Car Racing",True,RED) screen.blit(start,(72,300)) # Event Controller for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close intro = False # Terminate the loop pygame.quit() game_buttons('Start') intro = False carryOn = True def create_bush(): ''' Creates Roadside bushes''' global bush try: bush = Bush(50,50) lane_side = random.randint(0,1) if lane_side == 0: bush.rect.x = random.randint(0,30) elif lane_side == 1: bush.rect.x = random.randint(450,480) bush.rect.y = random.randint(-150,-100) #Adding this bush sprite to the list of sprites all_sprites_list.add(bush) except: print("Error Creating bush.") def game_loop(): '''Main Game loop''' global score_value,bush FPS = 120 # Frame rate at which The game will Play score_value = 0 # the score value # The clock will be used to control how fast the screen updates clock = pygame.time.Clock() # Creating Enemies and Bushes create_enemy() create_bush() #Game Begins game_intro() #background music mixer.music.load('sounds/bg-music.wav') mixer.music.play(-1) # -1 to play continuously # -------- Main Program Loop ----------- carryOn = True while carryOn: try: # Event Handler for event in pygame.event.get(): if event.type == pygame.QUIT: carryOn = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: carryOn = False keys = pygame.key.get_pressed() playerCar.changeSpeed(10) # Game Controls if keys[pygame.K_LEFT]: playerCar.moveLeft(2) if keys[pygame.K_RIGHT]: playerCar.moveRight(2) if keys[pygame.K_UP]: playerCar.moveForward(5) if keys[pygame.K_DOWN]: playerCar.moveBackward(5) except: print("Key Press not detected") #Check if there is a car collision car_collision_list = pygame.sprite.spritecollide(playerCar,all_coming_cars,False) for car in car_collision_list: print("Car crash!") # Crash Sound after Collision crash_sound = mixer.Sound('sounds/crash.wav') crash_sound.play() carryOn = False # After collision Main game loop terminates game_over() # Then display the Game over screen # Updating all the sprites that are added earlier all_sprites_list.update() #Creating Background background() #Draw sprites all_sprites_list.draw(screen) score() # Displaying score high_score() speed = 8 # Setting the value of speed # Conditions for Game difficulty if score_value ==0: speed = 7 if score_value > random.randint(60,100): speed+=2 if score_value > random.randint(150,200): speed+=3 # Setting speed and making them move for #Enemy enemyCar.changeSpeed(speed) enemyCar.continuous_move(speed) #Bush bush.changeSpeed(speed) bush.continuous_move(speed) # Increment score if enemy car passes without collision if enemyCar.rect.y > 700: create_enemy() # Creates another enemy Car score_value+=10 # Creates bush randomly if bush.rect.y > 800: create_bush() #Conditions to check if player car is going Off Road if playerCar.rect.x < 70 or playerCar.rect.x > 360: # print("Car going off road") off_road() #Displays message # If car gets off the road then Game ends. if playerCar.rect.x <60 or playerCar.rect.x>370: game_over() # Update the screen pygame.display.flip() # Frames clock.tick(FPS) if __name__ == '__main__': game_loop() add_high_score() pygame.quit()
ab74bd34811246804bd98f493714c643a5bd1d49
tdesfont/TensorFlow-DQN-CatMouseGame
/biocells/biocells_model.py
7,215
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ BIOCELLS MODEL: Set up the context for the agent, environment on learning and also the main methods as step, reward and possible actions. The environment is a square of 30 by 30. (Its left-down corner being the origin.) The prey is the agent controlled by our algorithm and has four actions available. The prey has 4 actions available (each parametrized by a step): 0: (0, step) - Up 1: (0, -step) - Down 2: (step, 0) - Right 3: (-step, 0) - Left Note that we are in a continuous dynamic space as the predator is moving toward the prey. The predator always has a deterministic greedy move as it goes straight to the prey. The speed of the predator and the prey are proportional. As the walk of the prey is at the beginning random, we set up its speed to 2 times the speed of the predator. Basically, the objective of the prey is to maximize its lifetime in the circle. The prey has a simple optimal strategy, which is to do a periodic move into the area near the borders followed indefinitely by the predator. Our goal is to make the prey/agent learn the optimal startegy. Our assumption is that this learning task is closely linked to an exploration-exploitation dilemna. Indeed, a basic strategy for the prey is to flee in the direct opposite direction of the predator meaning that it will be stuck in the corner in the longer-term. """ import numpy as np import random def random_corner(): """ Return a unitary random corner among the [up, down]x[left, right] (Cartesian space) """ random_horizontal = (random.random() > 0.5) * 2 - 1 random_vertical = (random.random() > 0.5) * 2 - 1 return np.array([random_horizontal, random_vertical]) class BioCells: def __init__(self, rewards={'nothing': -1, 'prey_eaten': +10}, verbose=0, step=1, speed_ratio=3, random_corner_init=False): """ Initialise the learning environment. Input: rewards: <dict> Reward given to the agent at each move. Need to check in our implementation: Cost=-Reward verbose: <int> Do a verbose simulation (Different from a display) step: <int> Size of the step for the random walk (to tune) """ self.verbose = verbose self.rewards = rewards self.canvas_size = 60 self.random_corner_init = random_corner_init # Define the possible actions for the prey/agent # Parametrization by the step is important, the less the step # the more random the walk and the more difficult the learning task self.step = step self.actions = { 0: (0, self.step), 1: (0, -self.step), 2: (self.step, 0), 3: (-self.step, 0) } # Define speed of predator and prey self.speed_predator = 1 self.speed_ratio = speed_ratio # Set the speed of the prey self.speed_prey = self.speed_ratio*self.speed_predator # Reset game context and environment self.reset() def reset(self): """ Reset the environment """ scale = self.canvas_size / 2 if self.random_corner_init: # Define initial position of the prey/agent self.position_prey = np.zeros((1, 2)) self.position_predator = scale*np.reshape(random_corner(), (1, 2)) else: self.position_prey = scale*(np.random.random((1,2))*2 - np.ones((1,2))) # Define initial position of predator in one of the corner of the area self.position_predator = scale*(np.random.random((1,2))*2 - np.ones((1,2))) if self.verbose: print("Initial predator position:", self.position_predator) # Define game events self.prey_eaten = False self.game_over = False # Store frames for display self.store_pos_prey = [] # position of prey self.store_pos_predator = [] # position of predator # Reset time count self.t = 0 def move(self, h_increment, v_increment): """ Update positions of predator and prey. The agent/prey has 4 moves available [Up, Down, Left, Right] The predator has a deterministic greedy move at each iteration Input: h_increment : <int> Horizontal increment v_increment : <int> Vertical increment Both takes value in [-step, 0, +step] """ # Update position of predator based on agent/prey's move direction_predator = np.angle((self.position_prey - self.position_predator) @ np.array([1, 1j])) self.position_predator += self.speed_predator * np.array([np.cos(direction_predator), np.sin(direction_predator)]).T # Enforce area constraints on the predator position self.position_predator = np.minimum(self.position_predator, np.ones(self.position_predator.shape) * self.canvas_size / 2) self.position_predator = np.maximum(self.position_predator, np.ones(self.position_predator.shape) * -self.canvas_size / 2) # Update position of agent/prey w.r.t. the input move self.position_prey += self.speed_prey * np.array([h_increment, v_increment]) # Enforce area constraints on the prey position self.position_prey = np.minimum(self.position_prey, np.ones(self.position_prey.shape) * self.canvas_size/2) self.position_prey = np.maximum(self.position_prey, np.ones(self.position_prey.shape) * -self.canvas_size/2) # Store the new positions self.store_frame() def play(self, action): """ Play the input action *action* and collect the reward Input: action : <int> Index of the designated action [0, 1, 2, 3] """ if self.verbose: print('Agent action:', action) # Collect horizontal and vertical increment (h_increment, v_increment) = self.actions[action] # Update prey and predator positions self.move(h_increment, v_increment) # Update lifetime self.t += 1 # Handle events in occurring in the game # Compute euclidian distance between position and prey pp_distance = np.sqrt((self.position_prey - self.position_predator)**2 @ np.ones((2,1))) if self.verbose: print('Distance prey-predator: {}'.format(pp_distance)) # Update event prey_eaten (Distance is critical if lower than 3) # This should be parametrized self.prey_eaten = pp_distance < 3 if self.prey_eaten: # Collect reward reward = self.rewards['prey_eaten'] if self.verbose: print('Prey eaten') # Set event game_over self.game_over = True else: # Collect reward reward = self.rewards['nothing'] return reward def store_frame(self): self.store_pos_prey.append(list(self.position_prey[0])) self.store_pos_predator.append(list(self.position_predator[0])) def check_game_is_over(self): return self.game_over
202bb65650e391ef309c456f3462b4637f4fb9fe
Igglyboo/Project-Euler
/Helper Functions/sieve.py
315
3.75
4
def sieve(upper_bound): prime = [False, False, True] + [True, False] * (upper_bound // 2) for p in range(3, int(upper_bound ** .5) + 1, 2): if prime[p]: for i in range(p * p, upper_bound, 2 * p): prime[i] = False return [p for p in range(2, upper_bound) if prime[p]]
116ce9cd9372af524a64ac79942219b88ecb98c0
martinmeagher/UCD_Exercises
/Module5_Data_Manipulation_Pandas/Inspecting_DataFrame.py
594
3.6875
4
# Import pandas using the alias pd import pandas as pd # import homelessness.csv homelessness = pd.read_csv("homelessness.csv") # Print the head of the homelessness data print(homelessness.head()) # Print information about homelessness print(homelessness.info()) # Print the shape of homelessness print(homelessness.shape) # Print a description of homelessness print(homelessness.describe()) # Print the values of homelessness print(homelessness.values) # Print the column index of homelessness print(homelessness.columns) # Print the row index of homelessness print(homelessness.index)
c5c7c7538dd9597a261f7686eb0bcc3bce532c83
furgot100/spd-hw
/Variable table/problem1.py
938
3.875
4
# Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length '''Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.''' nums = [1,1,2] class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ x = 1 if len(nums)==0: return 0 for i in range(1,len(nums)): if nums[i] != nums[i-1]: nums[x] = nums[i] x +=1 return x # given # =[1,1,2] should return 2 # start from the first 1 since it doesn't equal the value before it the counter is add 1 so x=1 # then go to the next 1, since it it the same the counter is the same so: x=1 # then go to the 2, 2 != 1 so the counter is added: x=2
96c5568a51e0f05a05736d04f2b5e1ebabf9a5df
abhishekk3/Practice_python
/encrypt_decrypt.py
559
3.828125
4
#Below function is to encrypt/decrypt the strings which are in the repititive sequence of characters from collections import OrderedDict def encrypt(): s='abbhhiiii' A=[] sub=list(s) for letter in OrderedDict.fromkeys(s): count=0 while letter in sub: count+=1 sub.remove(letter) A.append((letter+str(count))) print(''.join(A)) def decrypt(): s='a1b2c3d4' lst=list(s) A=[] for i in range(0,len(lst),2): a=str(lst[i]) b=int(lst[i+1]) c=a*b A.append(c) print (''.join(A)) decrypt()
ac9579b938c61e7262ad07d298d7ea903ba925e4
tatsuya-nagashima/atcoder
/abc219/a.py
155
3.59375
4
X = int(input()) if 0 <= X < 40: print(40 -X) elif 40<= X < 70: print(70 -X) elif 70<= X < 90: print(90 -X) elif X >=90: print('expert')
1e064dfb90d593d831ff07cbdc9df09ec3c3747b
cheykoff/thinkpython2e
/9-1-long-words.py
1,113
3.5625
4
def print_long_words(): fin = open('words.txt') count16 = 0 count17 = 0 count18 = 0 count19 = 0 count20 = 0 count21 = 0 count22andmore = 0 for line in fin: if len(line) > 15: if len(line) > 21: count22andmore = count22andmore + 1 elif len(line) == 21: count21 = count21 + 1 elif len(line) == 20: count20 = count20 + 1 elif len(line) == 19: count19 = count19 + 1 elif len(line) == 18: count18 = count18 + 1 elif len(line) == 17: count17 = count17 + 1 elif len(line) == 16: count16 = count16 + 1 print(line.strip()) print(count22andmore, "words have 22 or more letters") print(count21, "words have 21 letters") print(count20, "words have 20 letters") print(count19, "words have 19 letters") print(count18, "words have 18 letters") print(count17, "words have 17 letters") print(count16, "words have 16 letters") print_long_words()
00e6c94de6c0740e85ef17a56fdc583aca0aeae4
knotknull/python_beyond_basics
/list1.py
2,856
4.40625
4
#!/usr/bin/python3.5 # list : heterogeneous mutable sequences of bytes # get a list from split s = "eenie meenie minie moe piggie . .. ...".split() print(s) # use a negative index to get piggie # -8 -7 -6 -5 -4 -3 -2 -1 # "eenie meenie minie moe piggie . .. ..." print("s[-4] = {}".format(s[-4])) # NOTE: 0 == -0 print("what is s[0] = {}".format(s[0])) print("what is s[-0] = {}".format(s[-0])) # Let's slice it up, positive and negative indexes print("s[1:4] = {}".format(s[1:4])) print("s[1:-1] = {}".format(s[1:-1])) # start and stop indexes are optional print("s[3:] = {}".format(s[3:])) # from 3 to end of list print("s[:3] = {}".format(s[:3])) # from start to 2 # no indexes used for copying (shallow copy) # shallow copy = new list with same obj references as source list # NOTE: could also copy like copy=s.copy() or copy=list(s) s.append([0, "list"]) copy = s[:] print("copy = {}".format(copy)) print("s = {}".format(s)) print("copy == s {}".format(copy == s)) print("copy is s {}".format(copy is s)) # example of shallow copy: lets change the list at the end of s and see what # happens to the list at the end of copy print("s[-1].append(5) # appending to list in s also affect list in copy") s[-1].append(5) # appending to list in s also affect list in copy print("s = {}".format(s)) print("copy = {}".format(copy)) # list repetition rep = [5, 10] print("rep={} rep*3={}".format(rep, rep * 3)) # list repetition is used to initialize a known quantity to an initial value # i.e. initialize an array of 1000 to 0 # NOTE: repetition is shallow bigrep = [0] * 9 for idx, val in enumerate(bigrep): print("idx={} val={}".format(idx, val)) # find an item using index print(" moe is at {}".format(s.index('moe'))) # print(" ziggy is at {}".format(s.index('ziggy'))) # Give ValueError # get count and check for membership print ("moe count = {}".format(s.count('moe'))) print (". in s = {}".format('.' in s)) print ("~ in s = {}".format('~' in s)) # delete using del or remove goody = "All Good Boys Do Fine".split() print(goody) del goody[-1] print(goody) goody.remove('Do') print(goody) # Now insert goody.insert(0, 'Maybe') print(goody) # Add to list with += or append goody += ['Do'] print(goody) goody.extend(['Fine']) print("goody = ", goody) print("s= ", s) # reverse and sort in place goody.reverse() print("goody.reverse() = ", goody) goody.sort() print("goody.sort() = ", goody) # to sort and reverse without affecting the list directly use # sorted() and reversed() test = [' ', 'B', 'a', 'Z', 'z', 'j', 'M', 'p'] print("test = ", test) print("sorted(test) = ", sorted(test)) print("test = ", test) print("reversed(test) = ", reversed(test)) # reverse returns an iterator print("list(reversed(test)) = ", list(reversed(test))) # change back to a list print("test = ", test)
2574175046e0a625d8714c44b48b92a2b043314e
FIRESTROM/Leetcode
/Python/251__Flatten_2D_Vector.py
674
3.625
4
class Vector2D(object): def __init__(self, vec2d): """ Initialize your data structure here. :type vec2d: List[List[int]] """ self.list = [] for lst in vec2d: self.list += lst self.length = len(self.list) self.index = -1 def next(self): """ :rtype: int """ self.index += 1 return self.list[self.index] def hasNext(self): """ :rtype: bool """ return self.index + 1 < self.length # Your Vector2D object will be instantiated and called as such: # i, v = Vector2D(vec2d), [] # while i.hasNext(): v.append(i.next())
997e508d2cfc920519cdf571728fceecbaedf9c4
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
/students/smitco/lesson06/calculator/calculator/subtracter.py
207
3.859375
4
"""Subtracts two numbers""" class Subtracter(): """Class for subtracter""" @staticmethod def calc(operand_1, operand_2): """Perform subtraction""" return operand_1 - operand_2
b9839e6a28b1c4b2250f5ed6097ebfb0d4e2038a
iamkissg/leetcode
/interview/华为/最大子数组和.py
389
3.5
4
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: ans = nums[0] sub_max = nums[0] for n in nums[1:]: sub_max = max(sub_max+n, n) if sub_max > ans: ans = sub_max return ans if __name__ == "__main__": sol = Solution() print(sol.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
4f14e68fac0be5a0f5515f968c58c1ffdde9062e
xiebinhome/python--
/作业/010列表增加成员.py
253
3.75
4
print("列表增加数字") member = ['小甲鱼', 88, '黑夜', 90, '迷途', 85, '怡静', 90, '秋舞斜阳', 88] count = 0 length = len(member) for each in range(len(member)): if each%2 == 0: print(member[each], member[each+1])
7329a151bc179c0a79ad54770d400e90082955ad
Kori3a/M-PT1-38-21
/Tasks/Eugen Laikovski/tasks/home_work_0/hw_1_2.py
531
4.15625
4
from math import pow def calculation(): """ calculate the interest on the deposit """ try: start_sum = int(input('Enter your sum: ')) period = int(input('Enter your period (Years): ')) interest_rate = float(input('Interest rate %: ')) except ValueError: print('You values must be integer. Try again please') calculation() else: result = start_sum * (pow((1 + (interest_rate / 100) / 12), period * 12)) print(f'TOTAL SUM: {round(result, 2)} BYN') calculation()
b5246111c25c997ab3562d547c3e051ffd022d79
BONK1/Python
/complexConditionalStatements.py
803
4.1875
4
#Gender Liking Machine name = input("What's your name?") print(f'Hello {name},') print("NOTE: Type M (for male)") print(" Type F (for female)") print(" Type MF (for both)") gender = input("Your gender: ").upper() like = input("Your like: ").upper() if gender == 'M' and like == 'F': print(f'Congrats {name}, You are Straight') elif gender == 'F' and like == 'M': print(f'Congrats {name}, You are Straight') elif gender == 'M' and like == 'M': print(f'Congrats {name}, You are Gay') elif gender == "F" and like == 'F': print(f'Congrats {name}, You are Lesbian') elif gender == "M" and like == "MF": print(f'Congrats {name}, You are Bisexual') elif gender == "F" and like == "MF": print(f'Congrats {name}, You are Bisexual') else: print("You are an Alien!")
bebab37fd04e3828651ca886b2fcd0dae32b603b
henhuaidehaorena/magedu_python
/average_value.py
304
4.09375
4
#要求:輸入n個數,計算每次輸入后的平均值 # -*- coding: UTF-8 -*- #coding=utf-8 #等同於上面的聲明方式 #避免中文編碼異常 n=0 sum=0 while 1: digit=int(input('please input a digit:')) n=n+1 sum=sum+digit average=sum/n print('average value=',average)
83156a4fc5043ed962146b148befc038b38216ea
ThirdPartyNinjas/AdventOfCode2016
/day2a.py
435
3.78125
4
def clamp(n, smallest, largest): return max(smallest, min(n, largest)) def main(): x = 1 y = 1 movement = {'L' : {'x': -1, 'y': 0}, 'R' : {'x': 1, 'y': 0}, 'U' : {'x': 0, 'y': -1}, 'D' : {'x': 0, 'y': 1}} with open('day2a_input.txt') as f: for line in f: for c in line.strip(): x = clamp(x + movement[c]['x'], 0, 2) y = clamp(y + movement[c]['y'], 0, 2) button = y * 3 + x + 1 print(button, end='') main()
7b2942db76cd6d35eb8683b2cec7323a8c34a19f
Shiv2157k/leet_code
/goldman_sachs/find_pivot_index.py
777
3.890625
4
from typing import List class Array: def find_pivot_index(self, nums: List[int]) -> int: """ Approach: Prefix Sum Time Complexity: O(N) Space Complexity: O(1) :param nums: :return: """ # total_sum = sum(nums) total_sum = left_sum = 0 for num in nums: total_sum += num for pivot, num in enumerate(nums): if left_sum == total_sum - left_sum - num: return pivot left_sum += num return -1 if __name__ == "__main__": array = Array() print(array.find_pivot_index([1, 7, 3, 6, 5, 6])) print(array.find_pivot_index([2, -1, 1])) print(array.find_pivot_index([2, 1, 2])) print(array.find_pivot_index([1, 1]))
522dced09ef4108e65b43358b1f8f6d3f3e3e230
MakeSchool-17/twitter-bot-python-DennisAleynikov
/dictionary_words.py
580
4
4
import random import sys # Function for making a capitalized sentence of len words out of wordlist dict def random_sentence(dict, len): words = random.sample(dict, len - 1) sentence = " " + " ".join(words) + "." sentence = random.choice(dict).title() + sentence return sentence if __name__ == '__main__': # Obtain list of words from system wordlist dictionary = open('/usr/share/dict/words').read().splitlines() # Get length of generated "sentence" length = int(sys.argv[1]) sentence = random_sentence(dictionary,length) print(sentence)
ee8a94bffefd1683ffb1ba7a45b3d59fe279c329
nickbuker/python_practice
/src/lowercase_count.py
121
4.09375
4
from string import lowercase def lowercase_count(strng): return len([char for char in strng if char in lowercase])
ade51906917d4bb1deaf414f6847224e4ab3f135
renukamallade10/Python-problems
/Two dimensional list/lectures/spiralPrinting.py
1,025
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 12:50:33 2020 @author: cheerag.verma """ def spiralPrinting(arr): rowStart = 0 rowEnd = n colStart = 0 colEnd = m while rowStart<rowEnd and colStart<colEnd: for j in range(colStart,colEnd): print(arr[rowStart][j],end = " ") rowStart+=1 for i in range(rowStart,rowEnd): print(arr[i][colEnd-1],end=" ") colEnd-=1 for j in range(colEnd-1,colStart-1,-1): print(arr[rowEnd-1][j],end=" ") rowEnd-=1 for i in range(rowEnd-1,rowStart-1,-1): print(arr[i][colStart],end=" ") colStart+=1 return arr inputString = input().split(" ") n,m = int(inputString[0]),int(inputString[1]) inputList = inputString[2:] input2DList = [[int(inputList[m*i+j]) for j in range(m)]for i in range(n)] spiralPrinting(input2DList)
682b7c9db6a6319c6e2f8313d6f4437d0886c671
esagiev/Multi-Agent_RL_with_PHC
/games.py
2,207
3.859375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Developed by Erkin Sagiev, esagiev.github.io # Version on 15 September 2019. import numpy as np # To avoid "np is not defined" error. class matrix_game(): agent_num = 2 def agent_set(self): """ Returns the set of agents. """ return np.arange(self.agent_num) def action_set(self): """ Returns the set of actions. """ return np.arange(self.paymat.shape[0]) def payoff(self): """ Returns payoff matrices. """ return np.asarray([self.paymat, self.paymat]) def best_resp(self, actions): """ Returns both agents' best response to another agent's action. """ try: return np.argmax( self.payoff()[self.agent_set(), :, np.flip(actions)], 1 ) except: return print('Wrong input. Array with values in {0,1}.') class wrap(matrix_game): """ Two agent game created from given data. Takes two payoff matrices. """ def __init__(self, paymat_1, paymat_2): self.paymat_1 = paymat_1 self.paymat_2 = paymat_2 def payoff(self): """ Returns payoff matrices. """ return np.asarray([self.paymat_1, self.paymat_2]) class matching_pennies(matrix_game): """ Matching Pennies game with two agents. Actions are Head and Tail. """ paymat = np.array([[1, -1],[-1, 1]]) def payoff(self): """ Returns payoff matrices. """ return np.asarray([self.paymat, -self.paymat]) class prisoner_dilemma(matrix_game): """ Prisoner's dilemma game with two agents. Actions are Defect and Confess. """ paymat = np.array([[-1, -3],[0, -2]]) class stag_hunt(matrix_game): """ Stag hunt game with two agents. Actions are Stag or Hare. """ paymat = np.array([[3, 0],[2, 1]]) class RPS(matrix_game): """ Rock-Paper-Scissors game. Actions are Rock, Paper, and Scissors. """ paymat = np.array([[0, -1, 1],[1, 0, -1],[-1, 1, 0]]) class hawk_dove(matrix_game): """ Hawk and dove game. Actions are Dare (Hawk) and Chicken (Dove). """ paymat = np.array([[0, -1],[1, -2]])
abcc8722c224c7099e733180f4a6bcc6cab69d13
jiangliu888/DemoForSpeed
/CI/python-coroutine/yield_8/test.py
215
3.53125
4
# -*- encoding=utf-8 -*- from yieldloop import coroutine,YieldLoop @coroutine def test1(): sum = 0 for i in range(1,10001): if i % 2 == 1: sum += yield i print('sum =', sum)
58391c43919d1f41ba60aee29fba2114c0336904
kimujinu/Introduction-to-Programming
/Turtle6.py
312
3.71875
4
import turtle t=turtle.Turtle() t.shape("turtle") while True : cmd = input("명령을 입력하시오: ") if cmd =="I": t.left(90) t.fd(100) elif cmd == "R": #else if t.right(90) t.fd(100) else : print("명령어는 I 또는 R 두가지입니다.")
a20790a6d13489fce95e3111fa21776f8ffe7c90
Antoshka-m/filter_sig
/flattening.py
1,290
3.5625
4
from scipy.stats import linregress import numpy as np def flattening(data, dt, chunk_l): """ Make flattening of raw data using windows (time chunks) of given size Parameters ------- data: list or np.array timeseries data (deflection magnitude) dt: float time resolution of data chunk_l: float length of the chunk (in seconds) Returns ------- data_fit: np.array fitting line data_flat: np.array flattened data """ # get chunk length in datapoints instead of seconds chunk_l = int(chunk_l//dt ) # get size of output flattened data (cut out remaining part after division) flat_data_size = len(data)//chunk_l data_fit = np.empty((flat_data_size, chunk_l)) for chunk_i in range(flat_data_size): start_i = chunk_i*chunk_l end_i = (chunk_i+1)*chunk_l y = data[start_i:end_i] # make linear regression for each chunk k_coef, b_coef, _, _, _ = linregress([i for i in range(len(y))], y) yfit = k_coef * np.array([i for i in range(len(y))]) + b_coef data_fit[chunk_i] = yfit data_flat = data[:(flat_data_size*chunk_l)]-data_fit.flatten() return data_fit, data_flat
dbb600d47f61ce8d7d83a00872c885047bc5e90d
angelasl/everything
/cyoa.py
1,826
4.125
4
start= "In a far away kingdom, there lived three orphan royals. Two twin sisters and an older brother named Timothy. You are the combined minds of the two sisters. You are plotting to kill Timothy to fight for the throne." print (start) #one print ("Do you want to choose the villager or poison. Type 'villager' or 'poison' to choose") user_input = input() #one.1 if user_input == "villager": print ("You have two villagers to choose from: Elzabeth and Mary. Elizabeth is a 16 year old who needs the money to care for her younger siblings. Mary is a 20 year old who is expecting. Type 'Elizabeth to choose Elizabeth or''Type Mary to choose Mary'") user_input = input() #one.1.1 if user_input == "Elizabeth": print ("Should Elizabeth kill Tim while he is sleeping or awake? Type 'sleeping'or 'awake'.") #one.1.1.1 user_input = input() if user_input == "sleeping": print ("Tim sleep walks and runs away. FAIL! Game over.") #one.1.1.2 if user_input == "awake": print ("Elizabeth wasn't as sneaky as she thought and got killed by a knights") #one.1.2 user_input= input() if user_input == "Mary": print ("Will Mary risk her and her future son's life? 'Type yes or no' ") user_input = input() #one.1.2.1 if user_input == "yes": print ("Mary got caught and is sent to prison until she has her baby") #one.1.2.2 elif user_input == "no": print ("Mary stays safe but still lives in the slums") else: print: "Not a valid choice. Try again." #two.1 user_input = input() if user_input == "poison": print ("Do you want to kill him slowly over a week or instantly? Type 'slowly'or 'instantly'. ") #two.1.2 user_input = input() if user_input == "instantly": print ("Do you want to put the poison in steak or pizza? Type 'steak' or 'pizza'. ")
4d4a735e6116a426eb0515fdfcc60c3b5d9a3f7d
JPeterson462/SettlersOfCatan
/gameserver/tile.py
986
3.5
4
from enum import Enum class TileType(Enum): MOUNTAINS = 1 PASTURE = 2 FOREST = 3 FIELDS = 4 HILLS = 5 UNKNOWN = 6 DESERT = 7 def get_tile_name(t): if t == TileType.MOUNTAINS: return ["Mountains", "Ore"] if t == TileType.PASTURE: return ["Pasture", "Wool"] if t == TileType.FOREST: return ["Forest", "Lumber"] if t == TileType.FIELDS: return ["Fields", "Wheat"] if t == TileType.HILLS: return ["Hills", "Brick"] if t == TileType.DESERT: return ["Desert", "Unknown"] return "Unknown" def get_tile_type(t): # L O B S W D if t == "L": return TileType.FOREST if t == "O": return TileType.MOUNTAINS if t == "B": return TileType.HILLS if t == "S": return TileType.PASTURE if t == "W": return TileType.FIELDS if t == "D": return TileType.DESERT return TileType.UNKNOWN class Tile: def __init__(self, type, roll): self.type = type self.roll = roll def __repr__(self): name = get_tile_name(self.type) return name[0] + " " + str(self.roll)
62a3d9600f4e83e0cba558a3e1b53c235c2a6f9a
gapigo/CEV_Aulas_Python
/Exercícios - Mundo 2/Ex050.py
174
4.0625
4
print('Digite 6 números: ') soma = 0 for c in range(0, 6): num = int(input('-> ')) if num % 2 == 0: soma += num print('A soma dos números pares foi', soma)
fa561ac96c7645933af1eaed678d3ae379135655
Dev2050/Python
/data_analysis_re_urlilib.py
1,514
3.515625
4
Python 3.7.0a1 (v3.7.0a1:8f51bb4, Sep 19 2017, 18:50:29) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import re >>> import urllib.request >>> def getStock(): url="https://finance.google.com/finance?q=" stock=input("Please enter the stock market name? ") url=url+stock d1=urllib.request.urlopen(url).read() d2=d1.decode('utf-8') ##location data d3l=re.search('meta itemprop="price"', d2) st1=d3l.start() ed1=d3l.end()+23 ###obtained elements containing the values d3=d2[st1:ed1] ##location data for the hidden content attribute d4l=re.search('content="',d3) st2=d4l.end() ##the actual value stock_value=d3[st2:] print("The stock market value for " +stock+ " is " +stock_value) >>> >>> getStock() Please enter the stock market name? FB The stock market value for FB is 170.8 >>> getStock() Please enter the stock market name? Total Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> getStock() File "<pyshell#3>", line 9, in getStock st1=d3l.start() AttributeError: 'NoneType' object has no attribute 'start' >>> getStock <function getStock at 0x02CC6270> >>> getStock() Please enter the stock market name? TACI The stock market value for TACI is 0.210 >>> getStock() Please enter the stock market name? IPC The stock market value for IPC is 0.590 >>> getStock() Please enter the stock market name? TSEC The stock market value for TSEC is 10,38 >>>
50c0034251204e8cafe13a80454012558f13fc8b
daniel-reich/turbo-robot
/od6i73gJxc6xGFzsz_5.py
653
4.34375
4
""" A number is considered _slidey_ if for every digit in the number, the next digit from that has an absolute difference of one. Check the examples below. ### Examples is_slidey(123454321) ➞ True is_slidey(54345) ➞ True is_slidey(987654321) ➞ True is_slidey(1123) ➞ False is_slidey(1357) ➞ False ### Notes * A number cannot slide properly if there is a "flat surface" (example #4), or has gaps (example #5). * All single digit numbers can be considered _slidey numbers_! """ def is_slidey(n): s=str(n) L=[int(x) for x in s] return all(abs(L[i]-L[i+1])==1 for i in range(len(L)-1))
86458ac4d721ae084863b401570f5b143a5adaaa
yyl2016000/algorithms_design
/BubbleSort.py
810
4.0625
4
def BubbleSort_raw(in_list : list): for i in range(len(in_list), 1, -1): for j in range(1, i): if in_list[j] < in_list[j-1]: in_list[j-1], in_list[j] = in_list[j], in_list[j-1] def BubbleSort_better(in_list : list): for i in range(len(in_list), 1, -1): flag = 1 for j in range(1, i): if in_list[j] < in_list[j-1]: in_list[j-1], in_list[j] = in_list[j], in_list[j-1] flag = 0 if flag == 1: break if __name__ == '__main__': in_list = list(map(int, input("Please input a num list, splitted by ' ':").split())) mode = int(input("Please select mode:\n1.raw\n2.better\n")) BubbleSort_raw(in_list) if mode == 1 else BubbleSort_better(in_list) print("Sorted list is", in_list)
24cc943bd56170a09df1993ca21fad8390185110
vierth/hcs
/booleannonnum.py
201
3.796875
4
# Are two strings the same? "a" == "b" # False print ("a" is "a") # True a = ["hello"] b = ["hello"] print(a == b) # True print(a is b) # False print(id(a), id(b)) c = a print(a is c) # true
453477d13e090f22020a602cd4509a8ff30d020c
masadmalik71/Guess_Game
/main.py
1,693
3.90625
4
from replit import clear import random def game(number, attempts): game_countine = False while not game_countine: guessed_number = int(input(f"You have {attempts} remaining to guess the number.\nMake a guess: ")) if guessed_number == number: print(f"You got it! The answer was :{number}") game_countine = True elif guessed_number > number: print("Too high.") attempts -= 1 if attempts == 0: print("You lose.") game_countine = True elif guessed_number < number: print("Too Low.") attempts -= 1 if attempts == 0: print("You lose.") game_countine = True gamey = False while not gamey: actual_number = random.randint(1,100) print("I'm thinking of a number between 1 and 100.") is_input_right = False while not is_input_right: level = input("Choose a difficulty. Type 'easy' or 'hard': ") if level == 'easy' or level == 'e' or level == 'hard' or level == 'h': is_input_right = True elif level != 'easy' and level != 'e' and level != 'hard' and level != 'h': print("You enter the wrong input please type again.") if level == 'easy' or level == 'e': attempts = 10 game(actual_number, attempts) elif level == 'hard' or level == 'h': attempts = 5 game(actual_number, attempts) play_agai1 = False while not play_agai1: play_again = input("Want to play again? Type 'y' or 'n': ") if play_again == 'y': play_agai1 = True clear() elif play_again == 'n': clear() play_agai1 = True gamey = True elif play_again != 'y' and play_again != 'n': print("You entered the wrong key.")
ddc3327049e9a8eee828d70fe054849ed09c835b
hongcho7/Machine-Learning-Algo
/cross_validation.py
2,550
3.765625
4
''' df = data + target ''' import pandas as pd df = pd.read_csv("winequality-red.csv") ''' random shuffle - when you want to shuffle randomly - add the code inside/outside the loop ''' df = df.sample(frac=1).reset_index(drop=True) ''' holdout validation - also known as common splitting ''' df = df.sample(frac=1).reset_index(drop=True) df_train = df.head(1000) df_test = df.tail(599) ''' k-fold cross-validation - split randomly before k-fold cross-validation ''' import pandas as pd from sklearn import model_selection if __name__ == "__main__": # used to execute some code only if the file was run directly, and not imported df = pd.read_csv("train.csv") # create a new column and fill it with -1 df['kfold'] = -1 # randomize the rows of the data df = df.sample(frac=1).reset_index(drop=True) kf = model_selection.KFold(n_splits=5) # fill the new kfold column for fold, (trn_, val_) in enumerate(kf.split(X=df)): df.loc[val_, 'kfold'] = fold df.to_csv("train_folds.csv", index = False) ''' stratified k fold for classification ''' import pandas as pd from sklearn import model_selection if __name__ == "__main__": # used to execute some code only if the file was run directly, and not imported df = pd.read_csv("train.csv") # create a new column and fill it with -1 df['kfold'] = -1 # randomize the rows of the data df = df.sample(frac=1).reset_index(drop=True) kf = model_selection.StratifiedKFold(n_splits=5) # fill the new kfold column for fold, (trn_, val_) in enumerate(kf.split(X=df)): df.loc[val_, 'kfold'] = fold df.to_csv("train_folds.csv", index = False) ''' using stratrified Kfold for regression Step 1: Make Bins using Sturge Rule Step 2: imply stratified Kfold ''' import numpy as np import pandas as pd from sklearn import datasets from sklearn import model_selection def stratified_kfolds_reg(data): data['kfold'] = -1 data = data.sample(frac=1).reset_index(drop=True) # cacluate the number of bins by Sturge Rule num_bins = int(np.round(1 + np.log2(len(data)))) data.loc[:, 'bins'] = pd.cut(data['target'], bins = num_bins, labels = False) kf = model_selection.StratifiedKfold(n_splits=5) for f, (t_, v_) in enumerate(kf.split(X=data, y=data.bins.values)): data.loc[v_, 'kfold'] = f data = data.drop("bins", axis = 1) return data
9181406d3c62da8aecdf98e73ef3736b1c6a7a53
Jacksonleste/exercicios-python-curso-em-video
/ex063.py
314
4.09375
4
print('''{} SEQUÊNCIA DE FIBONACCI {}'''.format(12 * '=-', 12 * '=-')) num = int(input('insira um número:')) cont = 2 n1 = 0 n2 = 1 print('{} → {} → '.format(n1, n2), end='') while cont != num: n3 = n1 + n2 n1 = n2 n2 = n3 print('{} → '.format(n3), end='') cont = cont + 1 print('FIM')
0c59a8cab98f2b0ea7fdddb55cea77267f8bc82e
SaloniSwagata/Practice-Python
/palindrome.py
205
3.890625
4
def palin(text): if len(text)<=1: print("Palindrome") else: if text[0]==text[-1]: palin(text[1:-1]) else: print("Not a Palindrome") palin("Mysore")
91d68bc97a4e942d40f23c95adcc4768ac10ec0d
yangxicafuc/HardwayPython
/ex16.py
761
3.875
4
from sys import argv script, filename = argv print(f"We're going to erase {filename}.") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.") input("?") print("Open the file...") target = open(filename, 'w') print("Trucating the file. Goodbye!") #target.truncate() print("Now I'm going to ask you for three lines.") line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") print("I'm going to write these to the file.") target.write(line1 + "\n") target.write(line2 + "\n") target.write(line3 + "\n") print("And finally, we close it.") target.close() tmp = open(filename) str = tmp.read() print(f"{filename} content is: ") print(f"{str}") tmp.close()
31c7e99a30b0f4d76ae802e5c9fd6fd3a81abac9
aacharyakaushik/i_code_in_python
/leetcode/48_rotate_image.py
743
3.921875
4
""" @author: Kaushik Acharya """ from typing import List def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ for i in range(len(matrix)): for j in range(i, len(matrix)): # temp = matrix[i][j] # matrix[i][j] = matrix[j][i] # matrix[j][i] = temp matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # this takes advantage of the cache, rather than another loop matrix[i] = matrix[i][::-1] # for i in range(len(matrix)): # # temp = matrix[i] # matrix[i] = matrix[i][::-1] return matrix input_1 = [ [1,2,3], [4,5,6], [7,8,9] ] p = rotate(rotate, input_1) print(p)
e5ca8c9906fcae06b2ffb6bcd3540aa22beb3e11
jbteves/git_practice
/sub.py
163
3.53125
4
def sub(a,b): ans = float(a - b) return ans def main(): a = float(input()) b = float(input()) sub(a,b) if __name__ == '__main__': main()
b3f0a32cccc84098f33b714ae047285ff473e2b1
sai-gopi/gitpractice
/vs practice/swaping.py
83
3.75
4
a = int(input("enter a:")) b = int(input("enter b: ")) a,b = b,a print(a) print(b)
36f71d297dfdd0fdb0c2ba70d3c8780aab5f9dd4
arrimurri/simu
/chase.py
18,330
3.609375
4
import random import math import simu # Consult python documentation in http://www.python.org ######################################################################## # Put all your code for the chaser agent into this class. You have # to implement the execute method, but you can also add other methods # as well. Just make sure that the method names are different from # those of the agent class in the simu module. class chaser_agent(simu.agent): # Do not add parameters to the call of this method, i.e. # the agents must be initialized with only name and color # parameters. def __init__(self, name, color): super(chaser_agent, self).__init__(name, color) # Add possible initialization below this line. At this # point many of the properties of the agent are not fully # initilized yet. E.g. you cannot get the position of the # agent yet, etc. self.wall_positions = {} # This is the method everybody has to implement. The execution # of code is not fully deterministic, meaning all the agents # are executed in random order at each time point. def execute(self): # Some examples below. # You should implement your agents using only the methods # shown in the examples below. You can also implement your # own helper methods using standard python API. You CAN NOT # change anything in the simu.py file or use methods found # in there if they are not listed in the examples below. # My name is this string. #self.name # My id is this integer. #self.id # Get names of all other agents in the system as a python list. #agents = self.get_agent_names() # Get id of an agent of name NAME, e.g. #NAME = 'target' #ID = self.get_agent_id(NAME) # Get the sensor data as a python numpy array. -1 means # obstacle (wall), 0 means the position is free # and 1, 2, 3, ... means the position is occupied by an # agent of that id. The order of cells is clockwise starting # from the upper left corner of the 3x3 grid. # See the wall following agent example follow_wall.py. #sd = self.get_sensor_data() # Get my own position as a tuple (x, y) #position = self.get_position() # Get agent chaser0 position as a tuple (x, y) #position = self.get_position('chaser0') # Get the target position as a tuple (x, y) #position = self.get_position('target') # Talk to agent chaser3. The message can be any python object. #self.talk('chaser3', 1) # Retrieve possible messages from other agents. Returns # a dictionary as { 'sender0' : msg, sender1 : msg }, where # senders probably are chaser0, chaser1, ... #msgs = self.listen() # Do something with the possible message from chaser2 #if msgs.has_key('chaser2'): # msg2 = msgs['chaser2'] # self.helper_method(msg2, 0) # Store some info for the next execution. some_key and # some_info can be any python object, e.g. #some_key = 'ASDF' #some_info = (1, 2, 3) #self.params[some_key] = some_info # Retrieve some info stored earlier. some_key and # some_info can be any python object. #if self.params.has_key(some_key): # some_info = self.params[some_key] # Clear all the earlier stored info. #self.params.clear() # If your agent(s) have reached their objective, you can # stop the simulator as below. #self.stop() # Call your helper method #self.helper_method(1, 2) # For loop in python #for i in range(10): # print i # Send wall positions to other agents self.update_and_send_wall_positions() # Get wall positions from other agents self.get_wall_positions_from_others() # Get target positions target_pos = self.get_position('target') own_pos = self.get_position() if self.target_surrounded(): self.stop() if target_pos in self.get_neighbours(own_pos): return # If the distance is long, then make it so that the search doubles the heuristic # value of each node. This makes astar function more lika a depth first search. This # change makes the algorithm a lot faster with greater distances (although it is not optimal, # but good enough for long distances. if self.euclid_distance > 20: list_of_moves = self.astar(target_pos, double_heuristic = True) else: list_of_moves = self.astar(target_pos) if not list_of_moves: print 'Astar returned false' return next_pos = list_of_moves.pop() direction = '' if next_pos == self.pos_up(): direction = 'up' if next_pos == self.pos_down(): direction = 'down' if next_pos == self.pos_left(): direction = 'left' if next_pos == self.pos_right(): direction = 'right' self.move(direction) # All extra methods should be inside the class. # All class methods have self as their first parameter. # self is a reference of the instance of the class. def helper_method(self, param0, param1): # Do nothing pass def target_surrounded(self): target_pos = self.get_position('target') neighbour_positions = self.get_neighbours(target_pos) chasers = self.get_agent_names() chaser_positions = [self.get_position(c) for c in chasers] chaser_positions.append(self.get_position()) for pos in neighbour_positions: if pos not in chaser_positions and pos not in self.wall_positions: return False return True def astar(self, target, double_heuristic = False): start_pos = self.get_position() openlist = [start_pos] closedmap = {} parent_node = {} path_weight = {} heuristic_weight = {} sum_weight = {} path_weight[start_pos] = 0 heuristic_weight[start_pos] = self.euclid_distance(target) sum_weight[start_pos] = 0 while len(openlist) > 0: openlist.sort(key = lambda x: sum_weight[x], reverse = True) node = openlist.pop() if node == target: return self.backtrack_route(node, parent_node) closedmap[node] = True for neighbour in self.get_neighbours(node): if closedmap.has_key(neighbour): continue calc_score = path_weight[node] + 1 if neighbour not in openlist: insert_stats = True openlist.append(neighbour) elif calc_score < path_weight[neighbour]: insert_stats = True else: insert_stats = False if insert_stats: parent_node[neighbour] = node path_weight[neighbour] = calc_score heuristic_weight[neighbour] = self.euclid_distance(target, neighbour) if double_heuristic: heuristic_weight[neighbour] *= 2 sum_weight[neighbour] = path_weight[neighbour] + heuristic_weight[neighbour] return False def backtrack_route(self, node, parent_node): retlist = [] while parent_node.has_key(node): retlist.append(node) node = parent_node[node] return retlist def get_neighbours(self, node): neighbours = [] if node[0] < 0 or node[1] < 0: return neighbours if not self.wall_or_another_chaser(self.pos_right(node)): neighbours.append(self.pos_right(node)) if not self.wall_or_another_chaser(self.pos_left(node)): neighbours.append(self.pos_left(node)) if not self.wall_or_another_chaser(self.pos_up(node)): neighbours.append(self.pos_up(node)) if not self.wall_or_another_chaser(self.pos_down(node)): neighbours.append(self.pos_down(node)) return neighbours def wall_or_another_chaser(self, node): chaser_positions = [self.get_position(x) for x in self.get_agent_names() if x != 'target'] if node in chaser_positions: return True if node in self.wall_positions: return True return False def get_wall_positions_from_others(self): msgs = self.listen() chasers = self.get_agent_names() wall_pos = [] for c in chasers: if msgs.has_key(c): if msgs[c].has_key('wall_positions'): for pos in msgs[c]['wall_positions']: self.wall_positions[pos] = True def update_and_send_wall_positions(self): sd = self.get_sensor_data() wall_pos = [] for i, s in enumerate(sd): if s == -1: coords = self.get_coords_of_sensor(i) wall_pos.append(coords) self.wall_positions[coords] = True chasers = self.get_agent_names() for c in chasers: self.talk(c, {'wall_positions': wall_pos}) def get_coords_of_sensor(self, index): pos = self.get_position() # Return -1 if index is not in range 0 to 7 if index < 0 and index > 10: return -1 if index == 0: return (pos[0] - 1, pos[1] + 1) elif index == 1: return (pos[0], pos[1] + 1) elif index == 2: return (pos[0] + 1, pos[1] + 1) elif index == 3: return (pos[0] + 1, pos[1]) elif index == 4: return (pos[0] + 1, pos[1] - 1) elif index == 5: return (pos[0], pos[1] - 1) elif index == 6: return (pos[0] - 1, pos[1] - 1) else: return (pos[0] - 1, pos[1]) def pos_left(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0] - 1, own_pos[1]) def pos_right(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0] + 1, own_pos[1]) def pos_up(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0], own_pos[1] + 1) def pos_down(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0], own_pos[1] - 1) def euclid_distance(self, target_pos, chaser_pos = None): if chaser_pos == None: chaser_pos = self.get_position() distance = math.sqrt((target_pos[0] - chaser_pos[0])**2 + (target_pos[1] - chaser_pos[1])**2) return distance ######################################################################## # Put all your code for the target agent into this class. You have # to implement the execute method, but you can also add other methods # as well. Just make sure that the method names are different from # those of the agent class in the simu module. class target_agent(simu.agent): def __init__(self, name, color): super(target_agent, self).__init__(name, color) # Add possible initialization below this line self.wall_positions = {} def update_wall_positions(self): sd = self.get_sensor_data() wall_pos = [] for i, s in enumerate(sd): if s == -1: coords = self.get_coords_of_sensor(i) wall_pos.append(coords) self.wall_positions[coords] = True def get_coords_of_sensor(self, index): pos = self.get_position() # Return -1 if index is not in range 0 to 7 if index < 0 and index > 10: return -1 if index == 0: return (pos[0] - 1, pos[1] + 1) elif index == 1: return (pos[0], pos[1] + 1) elif index == 2: return (pos[0] + 1, pos[1] + 1) elif index == 3: return (pos[0] + 1, pos[1]) elif index == 4: return (pos[0] + 1, pos[1] - 1) elif index == 5: return (pos[0], pos[1] - 1) elif index == 6: return (pos[0] - 1, pos[1] - 1) else: return (pos[0] - 1, pos[1]) def get_chaser_positions(self): agent_names = self.get_agent_names() return [self.get_position(x) for x in agent_names if x != 'target'] def sort_neighbours(self, neighbours): n_plus_points = [] chaser_pos = self.get_chaser_positions() for n in neighbours: tmp_dict = {} tmp_dict[n] = 0 if not self.wall_positions.has_key(n) and n not in chaser_pos: for n2 in self.get_neighbour_positions(n): if self.wall_positions.has_key(n2): tmp_dict[n] = tmp_dict[n] + 1 if n2 in chaser_pos: tmp_dict[n] = tmp_dict[n] + 1 else: tmp_dict[n] = 5 n_plus_points.append((n, tmp_dict[n])) n_plus_points.sort(key = lambda x: x[1]) return n_plus_points def get_neighbour_positions(self, pos = None): if not pos: pos = self.get_position() neighbours = [] neighbours.append(self.pos_left(pos)) neighbours.append(self.pos_right(pos)) neighbours.append(self.pos_up(pos)) neighbours.append(self.pos_down(pos)) return neighbours def pos_left(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0] - 1, own_pos[1]) def pos_right(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0] + 1, own_pos[1]) def pos_up(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0], own_pos[1] + 1) def pos_down(self, own_pos = None): if not own_pos: own_pos = self.get_position() return (own_pos[0], own_pos[1] - 1) def euclid_distance_to_chasers(self, pos): chaser_positions = self.get_chaser_positions() return sum([self.euclid_distance(x, pos) for x in chaser_positions]) def get_shortest_distance(self, values): ret_val = values[0] ret_distance = self.euclid_distance_to_chasers(ret_val[0]) for i, v in enumerate(values): if i == 0: continue if self.euclid_distance_to_chasers(v[0]) > ret_distance: ret_val = v ret_distance = self.euclid_distance_to_chasers(v[0]) return ret_val def euclid_distance(self, target_pos, chaser_pos = None): if chaser_pos == None: chaser_pos = self.get_position() distance = math.sqrt((target_pos[0] - chaser_pos[0])**2 + (target_pos[1] - chaser_pos[1])**2) return distance def execute(self): # Do not remove the line below or the test below that. sd = self.get_sensor_data() # Test whether there are any possible moves and if not # do nothing, i.e. chasers have won unless they are stupid. if sd[1] != 0 and sd[3] != 0 and sd[5] != 0 and sd[7] != 0: return # Do not remove the lines above. # Put all your code for the execute method below this line. self.update_wall_positions() num_of_chasers = len(self.get_agent_names()) - 1 if self.euclid_distance_to_chasers(self.get_position()) > 5 * num_of_chasers: self.move(random.choice(['up', 'down', 'left', 'right'])) return sorted_list = self.sort_neighbours(self.get_neighbour_positions()) print sorted_list best_value = sorted_list[0][1] values_with_best_value = [x for x in sorted_list if x[1] == best_value] print values_with_best_value next_pos = self.get_shortest_distance(values_with_best_value) direction = '' if next_pos[0] == self.pos_up(): direction = 'up' if next_pos[0] == self.pos_down(): direction = 'down' if next_pos[0] == self.pos_left(): direction = 'left' if next_pos[0] == self.pos_right(): direction = 'right' print direction self.move(direction) # self.move(random.choice(['up', 'down', 'left', 'right'])) #sd = self.get_sensor_data() #if sd[1] == -1 and sd[3] != -1 or sd[7] == sd[1] == -1: #self.move('right') #elif sd[3] == -1 and sd[5] != -1 or sd[1] == sd[3] == -1: #self.move('down') #elif sd[5] == -1 and sd[7] != -1 or sd[3] == sd[5] == -1: #self.move('left') #elif sd[7] == -1 and sd[1] != -1 or sd[5] == sd[7] == -1: #self.move('up') #elif sd[0] == -1: #self.move('up') #elif sd[6] == -1: #self.move('left') #elif sd[4] == -1: #self.move('down') #elif sd[2] == -1: #self.move('right') #else: #self.move(random.choice(('up', 'right', 'down', 'left'))) # Initialize the simulator and define the obstacles in the environment. # The obstacles (walls) can only be horizontal or vertical. S = simu.simu(walls = [[13, 25, 30, 25], [10, 15, 25, 15], [11, 5, 11, 16], [24, 5, 24, 16]], W = 600, H = 600) # Add the target agent to position (39, 39) # Do not change the name of the agent. S.add_agent(target_agent('target', (255, 0, 0)), (39, 39)) # Add chaser agents to the bottom of the window starting from origo. # Do not change the name of the agents. The names are chaser0, chaser1, ... # These are the names that agents can use if/when communicating. for i in xrange(4): S.add_agent(chaser_agent('chaser' + str(i), (255, 255, 255)), (i, 0)) # Run the simulation S.run()
45caca991f0a4eba7d807e7205d75634f62ca126
vlad0-0/lab8
/task1.py
104
3.671875
4
a = int(input()) b = int(input()) if a != b: a = max(a, b) else: a = 0 b = a print(str(a)+" "+str(b))
3773d3e877488ab71902ec8b465c7825439b6edc
UjjwalDhakal7/basicpython
/inputstatement.py
1,089
4.1875
4
#Wap to read data from employee from the keyboard and print the data. ''' eno = int(input('Enter employee number :')) ename = input('Enter Employee name :') esal = float(input('Enter Employee salary : ')) eadd = input('Enter Employee address :') estatus = eval(input('Enter marriage status? [True|False] :')) print('Please confirm entered info') print('Your entered info : \n', eno, ename, esal, eadd, estatus) ''' # reading multiple value from the keyboard in a single line : ''' a,b = [int(x) for x in input('Enter 2 numbers : ').split()] # .split() splits a string based on space by default print('Sum : ',a+b) ''' #WAP to read 3 float values from the key board with ',' separation and print the sum. a,b,c = [float(x) for x in input('Enter 3 float numbers:').split(',')] print('Sum: ', a+b+c) # eval() fuction : # This function evaluates entered input and return their corresponding datatypes. # If an expression is provided then it will convert values internally and return the output. x = eval(input('Enter something: ')) print(type(x))
0faa84125695775e3c487120e92116539034185b
laxmanlax/Programming-Practice
/MiscGlassdoor/fb.py
1,994
3.609375
4
#!/usr/bin/env python import sys # Without just doing: return max(arr) def get_max(arr): if len(arr) < 2: return arr return sorted(arr)[-1] # Without sorting. def get_max2(arr): if len(arr) < 2: return arr max_yet = arr[0] for e in arr: if e > max_yet: max_yet = e return max_yet assert get_max([1, 3, 7, 2]) == 7 assert get_max([2, 2]) == 2 assert get_max([]) == [] assert get_max2([1, 3, 7, 2]) == 7 assert get_max2([2, 2]) == 2 assert get_max2([]) == [] def min_diff(arr): if len(arr) < 2: return 0 arr = sorted(list(set(arr))) # Can't be 0 because that could be the minimum difference. min_diff = sys.maxint # Can't be arr[0] because 0 could be min diff, again. prev = arr[1] for i, e in enumerate(arr): diff = abs(e - prev) if diff < min_diff: min_diff = diff prev = arr[i] return min_diff assert min_diff([4, 10, 7, -2, 3]) == 1 assert min_diff([2, 10]) == 8 # Sort then work inward. O(n log n) time, O(1) space. # Output will be the pairs. # Assume can remove dupes. def get_pairs_sum_to_k(arr, k): if len(arr) < 2: return None arr = sorted(set(arr)) out_arr = [] i, j = 0, len(arr) - 1 while i < j: cand = arr[i] + arr[j] if cand == k: out_arr.append((arr[i], arr[j])) i += 1 elif cand > k: j -= 1 elif cand < k: i += 1 return sorted(out_arr, key = lambda x: x[0]) # Do it in one pass, O(N) time, using a hash table, O(N) space. def get_pairs_sum_to_k2(arr, k): if len(arr) < 2: return None complements = {} arr = list(set(arr)) out_arr = [] for e in arr: if k - e in complements: out_arr.append((e, k-e)) else: complements[e] = 1 return out_arr assert get_pairs_sum_to_k([0, 3, 2, 1, 4, 9], 5) == [(1, 4), (2, 3)] assert get_pairs_sum_to_k2([0, 3, 2, 1, 4, 9], 5) == [(3, 2), (4, 1)]
cf5cde753dd29eb41c1bb2a795654b99fa3bd364
andrewc91/Python_Fundamentals
/Python/sum_list.py
141
3.640625
4
a = [1, 2, 5, 10, 255, 3] print sum(a) #or a = [1, 2, 5, 10, 255, 3] total = 0 for numbers in a: total = total + numbers print total
eae62a24872283c0071f4103a48bdf5d4f5db202
Kevinpsk/LT614N
/load/packages/exercises/package_init_solution/main.py
267
3.8125
4
from conversion import * def main(): print(f"3 km is {distance.km_to_miles(3):.2f} miles") print(f"3 kg is {weight.kg_to_lbs(3):.2f} lbs") print(f"100 deg C is {temperature.celsius_to_fahrenheit(100):.0f} deg F") if __name__ == "__main__": main()
ba02a02c3b195fcb04e1639347e84d331c87de30
vyxxr/python3-curso-em-video
/Mundo1/007.py
262
3.890625
4
''' Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média ''' n1 = float(input('Entre com a primeira nota: ')) n2 = float(input('Entre com a segunda nota: ')) print('A média ente {} e {} é: {:.1f}'.format(n1, n2, (n1+n2)/2))
029920342a56756633c84c2b95a9cd9cbe1bffd7
asheed/tryhelloworld
/excercise/ex099.py
494
3.671875
4
#!/usr/bin/env python # -*- coding: utf8 -* # 099 구구단 출력하기 (홀수만 출력하기) # # 사용자로부터 2~9 사이의 숫자를 입력 받은 후 해당 숫자에 대한 구구단을 출력하는 프로그램을 작성하라. 단, 구구단의 결과값이 홀수인 경우만 출력하라. # # 구구단: 3 # 3x1 = 3 # 3x3 = 9 # 3x5 = 15 # 3x7 = 21 # 3x9 = 27 dan = int(input('구구단: ')) for i in range(1, 10, 2): print(str(dan) + 'x' + str(i) + ' = ' + str(dan*i))
4fe7b46f83a0bcfaa8413db48c9012cf1146270d
xUlqx/Programacion-1
/Parcial-1/parrafos.py
468
3.578125
4
class Parrafo(): def __init__(self): self.lineas = [] def agregar_lineas(self, nombre): entry = input("\nIngrese parrafo. Para terminar ingresesolamente '.': \n") while entry != ".": self.lineas.append(entry) entry = input("") self.lineas = '\n'.join(self.lineas) f = open(nombre, 'a') f.writelines(self.lineas + "\n\n") f.close()
59dcbbd08b53d168688366c702058cab6421b14d
jairajsahgal/DailyByte
/Uncommon_words.py
217
3.890625
4
def fun(s1,s2): s1=set(s1.split()) s2=set(s2.split()) print("S1: ",s1,"\nS2",s2) # print(s1-s2) return (s1.union(s2))-(s1&s2) def main(): s1=input("Enter s1") s2=input("Enter s2") print(fun(s1,s2)) main()
fcc7722e09fdd051c89a86bbc0eba53719aa7e71
huiqi2100/python2013lab4
/compress.py
984
3.53125
4
# Filename: compress.py # Author: Koh Hui Qi # Date created: 14 Feb 2013 # Description: Compress large textual documents # http://rosettacode.org/wiki/LZW_compression#Python def compress(uncompressed): """Compress a string to a list of output symbols.""" # Build the dictionary. dict_size = 256 dictionary = {chr(i): chr(i) for i in range(dict_size)} w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) # Add wc to the dictionary. dictionary[wc] = dict_size dict_size += 1 w = c # Output the code for w. if w: result.append(dictionary[w]) return result try: infile = open("flintstones.txt", 'r') lines = infile.readlines() for line in lines: compressed = compress(line) print(compressed) except IOError: print("ERROR! Unable to read file")
40607519a1b88c7249f468075870f5b1f2430c57
alinalimov/pythonProject
/pythonApp/alina.py
1,004
4.0625
4
#birth_year = input("enter birth year:") #import datetime #now = datetime.datetime.now() #age = now.year - int(birth_year) #print (age) #zodiac_sign = input("what month were you born?") month = input("what month were you born?") day = input("on what day were you born?") if int(month) == 1 and int(day) < 20: print ("capricorn") elif int(month) == 1 and int(day) > 19: print ("aquarius") elif int(month) == 2 and int(day) < 19: print ("aquarius") elif int(month) == 3 and int(day) > 20: print ("pices") elif int(month) == 3 and int(day) < 20: print ("Pices") elif int(month) == 4: print("aries") elif int(month) == 5: print("Taurus") elif int(month) == 6: print ("Gemini") elif int(month) == 7: print ("cancer") elif int(month) == 8: print("leo") elif int(month) == 9: print ("virgo") elif int(month) == 10: print("libra") elif int(month) == 11: print("scorpio") elif int(month) == 12: print ("Sagittarius") else: print("something else")
ce8e9adefc5ce80b8c31add4fd33a76b6014084f
ArhamChouradiya/Python-Course
/12function.py
217
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 3 23:06:37 2019 @author: arham """ def calc(a,b): x=a+b y=a-b z=a*b u=a/b return x,y,z,u for i in calc(10,5): print(i)
8f1ef8ab928bf8160cf2fe3e8e4b9c9c0feea21c
Thefloor075/ProjectEuler
/ProblemeEuler32.py
1,337
3.71875
4
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ from math import * def problem32(): s = 0 for i in range(10000): for j in range(10000): b = i*j if problem(b,i,j) == True: print(b,i,j) s += b return s def problem(b,i,j): L = [] x = str(i) y = str(j) z = str(b) dfg = len(x) + len(y) + len(z) if dfg < 9 or dfg > 9: return False else: for k in range(len(x)): L.append(int(x[k])) for k in range(len(y)): L.append(int(y[k])) for k in range(len(z)): L.append(int(z[k])) B = [1,2,3,4,5,6,7,8,9] for i in range(len(L)): if L[i] not in B: return False else: B.remove(L[i]) return True print(problem32())
d04e2dcc8f0ca2c236d98bc8cf7bfdca648eef24
Infinidrix/competitive-programming
/Take 2 Contests/Contest 4/q2.py
1,045
4
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isEvenOddTree(self, root: TreeNode) -> bool: path = collections.deque() path.append((root, 0)) prev = None level = -1 while path: node = path.popleft() if node[0].val % 2 == node[1] % 2: return False if node[1] != level: level = node[1] elif prev == node[0].val or ((node[0].val - prev > 0 and node[1] % 2 == 1) or (node[0].val - prev < 0 and node[1] % 2 == 0)): return False prev = node[0].val if node[0].left: path.append((node[0].left, level + 1)) if node[0].right: path.append((node[0].right, level + 1)) return True
948ac629318f91e18673ef8f98f5ca62639f2822
guolei0601/leetcode
/206.py
646
3.8125
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 206.py # @Author: guolei # @Time : 20/07/2019 2:59 PM # @Desc :反转链表 # @Ans :迭代法,创建一个节点存储下一个位置 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ pre = None cur = head while cur: next = cur.next cur.next = pre pre = cur cur = next return pre
5ec5c4ebc922d97073797b9b838e12421f1202db
MargitStar/python_course
/HW_1/Bobkova_Margarita.py
855
4.15625
4
input_string = "Не знаю как там в Лондоне, я не была."\ "Может, там собака - друг человека."\ "А у нас управдом - друг человека!" print("Original string: ", input_string) print("The amount of symbles: ", len(input_string)) print("Reversed string: ", input_string[::-1]) print("Capitilized string: ", input_string.title()) print("Uppercased string: ", input_string.upper()) amount_of_nd = input_string.count("нд") amount_of_or = input_string.count("ор") print("Amount of 'нд' in string: ",amount_of_nd, input_string.count("о"),input_string.count("ам")) print("Amount of 'ам' in string: ", input_string.count("ам")) print("Amount of 'о' in string: ", input_string.count("о")) print("Is amount of 'нд' higher than 'ор': ", amount_of_nd > amount_of_or)
cd6be002b265fed6014dbf985feddfda1c2856c4
BobbySweaters/Python-for-Everybody-Class-Labs
/1. Programming for Everybody/Chapter_3.2_Try_Accept_L.py
380
4.21875
4
# in this exercise we are going to include try/except protecton for traceback errors # when inputs are strings hrs = input("Enter Hours: ") rate = input("Enter Rate: ") try: h = float(hrs) r = float(rate) except: print("Error, please enter numeric input!") quit() pay = h * r if h <= 40: print(pay) elif h >40: print(40*r + (h-40)*1.5*r)
9bed7c7813a309ac8a19d5afce79958f4ff37b4c
ReejoJoseph1244/Hacktober2021-cpp-py
/BubbleSort.py
882
4.46875
4
#Bubble Sort Program implementation in Python, where the List is input by the user during the runtime. #This code is Contributed by Reejo. def Bubblesort(l,n): #BubbleSort function for i in range(0,n): for j in range(0,n-i-1): if l[j]>l[j+1]: l[j],l[j+1]=l[j+1],l[j] n=int(input("Enter the Number of Elements to Insert:-")) l=[ ] #Creating a list print("\n----Enter the Elements of the List----\n") for i in range(0,n): #Inserting the Elements of the List. print("Enter ",i+1," Element:-",end="") temp=int(input()) l.append(temp) print("Before BubbleSorting the List is:-") print(l) Bubblesort(l,n) #Calling bubble sort. print("After BubbleSorting the List is:-") print(l)
6fd131e3367378db3c9e0dd3e4673e80a8b0f0ab
Rayman96/LeetCode
/35_Search Insert Position.py
293
3.796875
4
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: if target > nums[-1]: return len(nums) else: for index, number in enumerate(nums): if number == target or number > target: return index
29a921b99690829a69a1d1d86563e62911dfc463
Mohit-007/MACHINE-LEARNING
/Part 2 - Regression/Section 7 - Support Vector Regression (SVR)/svr.py
2,847
3.59375
4
# SVR # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd class SVR: def __init__(self, learning_rate=0.001, lambda_param=0.01, n_iters=1000): self.lr = learning_rate self.lambda_param = lambda_param self.n_iters = n_iters self.w = None self.b = None def fit(self, X, y): n_samples, n_features = X.shape self.w = np.zeros(n_features) self.b = 0 for _ in range(self.n_iters): for idx, x_i in enumerate(X): self.w -= self.lr * (2 * self.lambda_param * self.w - np.dot(x_i, y[idx])) self.b -= self.lr * y[idx] def predict(self, X): approx = np.dot(X, self.w) - self.b return approx # Importing the dataset dataset = pd.read_csv('Position_Salaries.csv') X = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values # Splitting the dataset into the Training set and Test set """from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)""" """ note : here feature scaling applied in the dependent variable """ # Feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() sc_y = StandardScaler() X = sc_X.fit_transform(X) y = sc_y.fit_transform(y) mean_value = sum(y)/len(y) max_value = max(y) y = (y - mean_value)/max_value """ note : *** -> import SVR class by a svm library of sklearn -> make regressor and call constructor filling the parameter 1) kernel = 'rbf' -> fit the regressor model in the independent and dependent variable """ """ # Fitting SVR to the dataset from sklearn.svm import SVR regressor = SVR(kernel = 'rbf') regressor.fit(X, y) """ regressor = SVR() regressor.fit(X, y) """ note : To predict the value for a independent varible value in division apply -> np.array[value] note : -> as feature scaling applied in y then y_pred will get feature scaled value -> to get actual value apply object.inverse_transform(y_pred) """ # Predicting a new result y_pred = regressor.predict(np.array[[6.5]]) y = y*max_value + mean_value y_pred = sc_y.inverse_transform(y_pred) # Visualising the SVR results plt.scatter(X, y, color = 'red') plt.plot(X, regressor.predict(X), color = 'blue') plt.title('Truth or Bluff (SVR)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() # Visualising the SVR results (for higher resolution and smoother curve) X_grid = np.arange(min(X), max(X), 0.01) # choice of 0.01 instead of 0.1 step because the data is feature scaled X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') plt.title('Truth or Bluff (SVR)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show()
17fa1615c486d37e855be31b802ba07e7af4fd39
Pantufas42/Curso_Guanabara
/ex019.py
327
3.796875
4
from random import choice a1 = str(input('Nome do primeiro candidato: ')) a2 = str(input('Nome do segundo candidato: ')) a3 = str(input('Nome do terceiro candidato :')) a4 = str(input('Nome do quarto candidato :')) lista = (a1, a2, a3, a4) escolhido = choice(lista) print('O aluno escolhido foi: {}'.format(escolhido))
f2faa18407a8b641aa603507f561a8b2f5200dd2
shsh9888/leet
/stack_implementation/sol.py
937
3.90625
4
class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack=[] self.topmost =-1 def push(self, x): """ :type x: int :rtype: void """ if self.topmost is -1: self.stack.append((x,x)) else: self.stack.append((x,min(x, self.stack[self.topmost][1]))) self.topmost +=1 def pop(self): """ :rtype: void """ if self.topmost > -1: popped = self.stack[-1] self.stack = self.stack[:(len(self.stack))-1] self.topmost -= 1 return popped def top(self): """ :rtype: int """ if self.topmost >= -1: return self.stack[-1][0] def getMin(self): """ :rtype: int """ if self.topmost > -1: return self.stack[-1][1]
4f5a57e46e334b40a37a33f6489761d85de2f7fb
codesyariah122/MyPython
/classes/lat7.py
758
3.78125
4
class Kendaraan(object): def __init__(self, nama): self.nama = nama self.penumpang = [] def tambah_penumpang(self, nama_penumpang): self.penumpang.append(nama_penumpang) # membuat class mobil yang merupakan turunan dari class kendaraan class Mobil(Kendaraan): pintu_terbuka = False pintu_tertutup = False def buka_pintu(self): self.pintu_terbuka = True def tutup_pintu(self): self.pintu_tertutup = True mobnas = Mobil("MobilSaya") # mobnas akan memiliki properti dari kendaraan mobnas.tambah_penumpang("Raisa") print("Penumpang : "+str(mobnas.penumpang)) # dan memiliki properti mobil mobnas.buka_pintu() print("Pintu terbuka : "+str(mobnas.pintu_terbuka)) mobnas.tutup_pintu() print("Pintu tertutup : "+str(mobnas.pintu_tertutup))
eeb50c7fe51e4fef82d981dda947fc0ca991daba
shankar7791/MI-10-DevOps
/Personel/pooja/Assesment/16march/substring.py
204
4
4
def check(string, sub_string): if string.find(sub_string) == -1: print("no") else: print("yes") string = 'my name is pooja' sub_string = 'pooja' print(check(string, sub_string))
8bbdc722c6f02db6b7bfcc3e3da9487d47db77b9
adilhussain540/scheduling_algorithms
/FCFS.py
3,680
3.765625
4
class process: def __init__(self): self.id = 0 self.arrival_time = 0 self.burst_time = 0 self.start_time = 0 self.finish_time = 0 self.waiting_time = 0 self.turnaround_time = 0 def display(self): print(self.id, end=" "*20) print(self.arrival_time, end=" "*20) print(self.start_time, end=" "*15) print(self.finish_time, end=" "*15) print(self.waiting_time, end=" "*20) print(self.turnaround_time, end="") def displayProcessList(processes, n): print("Process ID | Arrival Time | Start Time | Finish Time | Waiting Time | Turnaround Time") for i in range(n): processes[i].display() print() def sortProcessList(processes, n): for i in range(0,n-1): for j in range(i+1,n): if processes[j].arrival_time < processes[i].arrival_time: processes[j], processes[i] = processes[i], processes[j] def allProcessCompleted(bursts, n): check = True for i in range(n): if bursts[i] != 0: check = False return check # main code starting here allProcesses = [] readyProcesses = [] bursts = [] process_index = 0 avg_waiting_time = 0 avg_turnaround_time = 0 clock = 0 count = int(input("Enter Number of Processes: ")) #taking input from user and inserting in our process array for index in range(int(count)): temp = process() temp.arrival_time = int(input("\nEnter Arrival Time: ")) temp.burst_time = int(input("Enter Burst Time: ")) temp.id = index bursts.append(temp.burst_time) allProcesses.append(temp) #sorting processes on bases of arrival time sortProcessList(allProcesses,count) print("\n. = idle\n- = running\nC = completed\n\n") while allProcessCompleted(bursts, count) == False: #new processes while process_index < count and allProcesses[process_index].arrival_time == clock: readyProcesses.append(allProcesses[process_index]) process_index = process_index + 1 if not readyProcesses: print(". ", end="") clock = clock + 1 elif readyProcesses: #processes started execution if readyProcesses[0].burst_time == bursts[readyProcesses[0].id]: for i in range(count): if readyProcesses[0].id == allProcesses[i].id: allProcesses[i].start_time = clock bursts[readyProcesses[0].id] = bursts[readyProcesses[0].id] - 1 clock = clock + 1 print("- ", end="") #processes completed execution if bursts[readyProcesses[0].id] == 0: for i in range(count): if readyProcesses[0].id == allProcesses[i].id: allProcesses[i].finish_time = clock + 1 allProcesses[i].waiting_time = allProcesses[i].finish_time - allProcesses[i].arrival_time - allProcesses[i].burst_time allProcesses[i].turnaround_time = allProcesses[i].finish_time - allProcesses[i].arrival_time avg_waiting_time = avg_waiting_time + allProcesses[i].waiting_time avg_turnaround_time = avg_turnaround_time + allProcesses[i].turnaround_time print("P",readyProcesses[0].id,"(C)", end="", sep="") readyProcesses.pop(0) print("\n\n") avg_waiting_time = float(avg_waiting_time)/float(count) avg_turnaround_time = float(avg_turnaround_time)/float(count) displayProcessList(allProcesses,count) print("\nAverage Waiting Time : ", avg_waiting_time) print("Average Turnaround Time : ", avg_turnaround_time)
55105a82a7dc3b9adf0a398535ccdc5a23bf42fb
prakriti-singh/University-Projects
/Ex1_PrakritiSingh.py
2,333
3.84375
4
import math pi = math.pi def MyArcTan(x,N): #Function to calculate arctan n= 0 sum = 0 while n <= N: sum += ((((-1)**n) * (x**((2*n)+1))) / ((2*n) + 1)) n+=1 return sum def FinalAnswer(x,N): #Funtion to calculate arctan for different values of x if abs(x) <= 1: final = (MyArcTan(x,N)) elif abs(x) > 1: if x>0: final = ((pi/2) - MyArcTan((1/x),N)) elif x<0: final = (-(pi/2) - MyArcTan((1/x),N)) return final MyInput = '0' while MyInput != 'q': MyInput = input('Enter a choice, "a", "b" or "q" to quit: ') print('You entered the choice: ',MyInput) if MyInput == 'a': print('You have chosen part (a)') Input_x = input('Enter a value for x (floating point number): ') x = float(Input_x) #Next piece of code makes sure user enters an Integer and a positive value while True: Input_N = input('Enter a value for N (positive integer): ') if Input_N.isdigit(): N = int(Input_N) break print ('Arctan(', x, ') = ', FinalAnswer(x,N)) elif MyInput == 'b': print('You have chosen part (b)') x=2 #Next piece of code makes sure user enters an Integer and a positive value while True: Input_N = input('Enter a value for N (positive integer): ') if Input_N.isdigit(): #isdigit() checks if all the characters in the string are digits, a negative sign and a decimal point are considered non-digits N = int(Input_N) break print (' x | MyArctan function ans | Arctan funtion ans | Difference') while x <= 2 and x>=(-2): difference = abs(FinalAnswer(x,N) - math.atan(x)) print (x, " "*(4-len(str(x))),'|',(FinalAnswer(x,N))," "*(20-len(str(FinalAnswer(x,N)))),'|', math.atan(x)," "*(20-len(str(math.atan(x)))),'|', difference, " "*(20-len(str(difference)))) x-=0.1 #decreases the value of x by 0.1 x = round(x,1) #rounds the float value of x to one digit elif MyInput != 'q': print('This is not a valid choice') print('You have chosen to finish - goodbye.')
be31f760227073e57e300fd34729d67e19edfcd2
pauleclifton/GP_Python210B_Winter_2019
/examples/office_hours_code/class_property.py
597
3.5
4
class DrivingRules: def __init__(self, minimum_age, drivers_age): #self.minimum_age = minimum_age self._minimum_age = minimum_age #self.drivers_age = drivers_age self._drivers_age = drivers_age @property def minimum_age(self): return self._minimum_age @minimum_age.setter def minimum_age(self, age): self._minimum_age = age @property def drivers_age(self): return self._drivers_age def can_drive(self): if self.drivers_age >= self.minimum_age: return True return False