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
49440bee99fe5e5c623f13d0e2a8932bbf9ecc6d
humana42/curso_em_video_Python
/ex055.py
198
3.953125
4
pesos = [ ] for p in range(0,5): peso = float(input('Digite o peso: ')) pesos.append(peso) print('O maior peso é {}Kg' .format(max(pesos))) print('O menor peso é {}Kg' .format(min(pesos)))
0c465df382bbaa53b7ac968e51b8af3d86d58d51
srea8/cookbook_python
/08/ExtendPropertyInSubClass.py
2,446
3.96875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Srea # @Date: 2019-12-05 21:57:21 # @Last Modified by: srea # @Last Modified time: 2019-12-05 22:27:00 #****************************# #基本的@property使用,可以把函数当做属性用,@property的set,deleter,get # # #****************************# ####@property demo1 class Person: def __init__(self, name): self.name = name # Getter function @property def name(self): return self._name # Setter function @name.setter def name(self, value): if not isinstance(value, str): raise TypeError('Expected a string') self._name = value # Deleter function @name.deleter def name1(self): raise AttributeError("Can't delete attribute") a = Person('11') print(Person.name) a.name = 'xiaoming' print(a.name) print(Person('lihua').name) print(a._name) # print(Person._name) # print(a._name) # del a.name ####@property demo2 class Goods(object): def __init__(self): #原价 self.original_price = 100 #折扣 self.discount = 0.8 @property def price(self): #实际价格=原价*折扣 new_price = self.original_price*self.discount return new_price @price.setter def price(self,value): self.original_price = value @price.deleter def price(self): del self.original_price obj = Goods() print(obj.price) obj.price = 200 print(obj.price) #调用的price.setter 设置的original_price del obj.price # print(obj.price) #此处已经删除了obj.price(已屏蔽) ####property demo3 class Foo(object): def get_name(self): print('get_name') return 'laowang' def set_name(self, value): '''必须两个参数''' print('set_name') return 'set value' + value def del_name(self): print('del_name') return 'laowang' NAME = property(get_name, set_name, del_name, 'description.') print(Foo().NAME) Foo().NAME = 'Alex' print(Foo().NAME.__doc__) print(Foo().NAME) ####property demo4 class Person(object): def __init__(self, age): self.__age = age def set_age(self, value): self.__age = value def get_age(self): return self.__age AGE = property(get_age, set_age) person = Person(15) print(str(person.AGE)) person.AGE = 20 print(str(person.AGE))
e812b84659a74be5a2b78d1b4dc419530a39fe86
marczakkordian/python_code_me_training
/03_collections_homework/03_dictionary/04.py
284
3.71875
4
# Utworz tabliczkę mnożenia jako zagnieżdżoną listę o rozmiarze 10 x 10, wypełnioną wynikami mnożenia wiersz × kolumna. multi_table = [] for i in range(1, 11): multi_table.append([]) for j in range(1, 11): multi_table[i-1].append([i*j]) print(multi_table)
0ea71547f5e32639ad36c92e23ee5904e5ce3b7d
hugostubler/projet_RO
/tme2.py
4,468
3.78125
4
#!/usr/bin/env python # coding: utf-8 # ### kcore decomposition # # In this notebook, you will find the python code for kcore decomposition (tme2). You can load any graph using the first function, which turns a txt file (usually a graph presented in list of edges) into a dictionnary structure of graph, which corresponds to the adjacency array. # In[1]: def load_graph (input): file = open(input,"r") file = file.readlines() G = dict() for line in file: try: s,t = map(int,line.split()) try: G[s].append(t) except: G[s]=[t] try: G[t].append(s) except: G[t]=[s] except: pass # pour passer quand la ligne n'est pas au bon format return G def load_graph2 (input): # Same, but we load the graph with its number of edges, which is way easier to compute using the # initial data file = open(input,"r") file = file.readlines() G = dict() nb_edges = 0 for line in file: try: s,t = map(int,line.split()) try: G[s].append(t) nb_edges+=1 except: G[s]=[t] try: G[t].append(s) except: G[t]=[s] except: pass # pour passer quand la ligne n'est pas au bon format return (G, nb_edges) # In[43]: G, nb_edges = load_graph2('net.txt') #G, nb_edges = load_graph2('com-amazon.ungraph.txt') # Loading one of the suggested graphs, e.g. the amazon network #G, nb_edges = load_graph2('com-jl.ungraph.txt') # In[44]: def core_decomposition(G): vertices = list(G.keys()) edges = G i = len(list(vertices)) # Number of nodes c = 0 core = {} first = True while len(vertices) > 0: # compute a dict with the degrees of nodes in vertices if first: # we build the dictionnary of degrees only one time then we will reduce it step by step deg = {} for e in vertices: deg[e] = len(G[e]) for v in G[e]: deg.setdefault(v,0) deg[v]+=1 first = False degree = deg # find a vertex with minimum degree vertices.sort(key = lambda x: deg[x]) v = vertices[0] print(v) c = max(c,deg[v]) # updating deg del deg[v] for neighbour in edges[v]: deg[neighbour]-=1 #updating edges del edges[v] vertices.sort() for s in vertices[:vertices.index(v)]: tmp = edges[s] try: del (edges[s])[tmp.index(v)] except: pass #updating vertices del vertices[vertices.index(v)] core[v] = i i = i-1 print(i) return(core, c, degree) # Returning the core values list for every vertex and the core value of the graph, and the list of degrees # In[4]: import math from math import factorial def density(G, nb_edges): # simple function to return the average degree density and the edge density of a graph number_of_nodes = len(list(G.keys())) max_number_of_edges = math.factorial(nb_edges) avg_deg_density = nb_edges/number_of_nodes edge_density = nb_edges/max_number_of_edges # Rk : for a real world graph, the edge density is going to be 0, since a lot of links do not exist. The edge_density # is useful for a subgraph when you want to see if it is denser than another subgraph for example, which is our problem return (avg_deg_density, edge_density) # In[45]: core, c, degree = core_decomposition(G) # Do not try this, it will take several hours with the amazon graph because of Python's pace... # I tried but I stopped after getting 15,000 nodes deleted from the initial list out of 287000 in 1h30 # In[58]: # Now we want to see the the coreness of each node as a function of the degree and see if there are outliers import pandas as pd import matplotlib.pyplot as plt ID = pd.read_csv("ID.txt", sep = "\t", names = ['names'], low_memory=False) ID['names'] = ID['names'].apply(lambda x: x.split(" ",1)[1]) #now each line corresponds to a node and its name plt.plot(degree,core) # in order to check the outliers
6cec76d04ce015e5d162c6b2f2512be3f49db355
Andre-300/pdsnd_github
/bikeshare.py
7,814
4.21875
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs # this function is called at the bottom in the main function def get_user_input_city(prompt): cities = ['chicago', 'new york city', 'washington'] while True: city = input(prompt).strip().lower() if city in cities: return city elif input('Please select any of the following: Chicago,New York and Washington'): if city in cities: return city # TO DO: get user input for month (all, january, february, ... , june) def get_user_input_month(prompt): months = ['all', 'jan', 'feb', 'mar', 'apr', 'may', 'jun'] while True: month = input(prompt).strip().lower() if month in months: return month elif input("Data can only be displayed for 'all', Jan', 'Feb', 'Mar', 'Apr', 'May', and 'Jun': "): if month in months: return month # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) def get_user_input_day(prompt): while True: day = str(input(prompt).strip().lower()) if day in ('all','0','1', '2', '3', '4', '5', '6'): return day # this will prit dashed lines after the execution of the function print('-'*40) def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] = df['Start Time'].dt.month df['week_day'] = df['Start Time'].dt.weekday_name df['hour'] = df['Start Time'].dt.hour df['start_end_combo'] = "starting at" + df['Start Station'] + ' and ending at ' + df['End Station'] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # TO DO: display the most common month common_month = df['month'].mode()[0] print('The Most Common Month is ',common_month) # TO DO: display the most common day of week common_day = df['week_day'].mode()[0] print('The Most Common Day is ',common_day) # TO DO: display the most common start hour common_hour = df['hour'].mode()[0] print('The Most Common Hour is ',common_hour) # important point to check run time of a particular function print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # TO DO: display most commonly used start station popular_start_station = df['Start Station'].mode()[0] print('The Most Popular Start Station is ', popular_start_station) # TO DO: display most commonly used end station popular_end_station = df['End Station'].mode()[0] print('The Most Popular End Station is ', popular_end_station) # TO DO: display most frequent combination of start station and end station trip popular_start_end_combo = df['start_end_combo'].mode()[0] print('The Most Popular Start/End Combination is ', popular_start_end_combo) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # TO DO: display total travel time total_trip_duration = df['Trip Duration'].sum() print('Total Trip Duration is ', total_trip_duration) # TO DO: display mean travel time avg_trip_duration = df['Trip Duration'].mean() print('Average Trip Duration is ', avg_trip_duration) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types user_types = df['User Type'].value_counts() print(user_types) # TO DO: Display counts of gender try: user_genders = df['Gender'].value_counts() except: user_genders = 'Washington does not have user gender data' print(user_genders) # TO DO: Display earliest, most recent, and most common year of birth try: oldest_rider_birth = 'The oldest rider was born in ' + str(df['Birth Year'].min()) except: oldest_rider_birth = 'Washington does not have rider year of birth data' print(oldest_rider_birth) try: youngest_rider_birth = 'The youngest ride was born in ' + str(df['Birth Year'].max()) except: youngest_rider_birth = 'Washington does not have rider year of birth data' print(youngest_rider_birth) try: most_common_rider_birth = 'The year in which the most riders were born in is ' + str(df['Birth Year'].mode()[0]) except: most_common_rider_birth = 'Washington does not have rider year of birth data' print(most_common_rider_birth) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def raw_data(df): #function gives the user the ability to look at the first 5 rows and then gives them the option to iterate through 5 lines at a time if they'd like to inspect further. #used a while loop to keep iterating as long as user continues to answer "yes" or exit and move on when they don't. i = 0 data = input("\nwould you like to view the first 5 lines of raw bikeshare data?\n").lower() if data != 'yes': print("skipping raw data display.") else: while True: window = df[(i * 5):5 +(i * 5)] print(window) i += 1 five_raw = input("\nWould you like to see the next 5 rows of raw data?\n") if five_raw.lower() != 'yes': break def main(): while True: city = get_user_input_city("Which city would you like to explore? Please select Chicago, New York City, or Washington: ") month = get_user_input_month("What months we could choose from? Please select 'all', Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun: ") day = get_user_input_day("Which day of the week would you like to look at? Please select 'all' days or a day using the corresponding day of the week, starting with Sunday=0 and ending with Saturday: ") df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) raw_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
eaa13fa8f6bb2ab287196082e24d121b399326ba
orange-eng/Leetcode
/middle/22_Generate_Parentheses.py
574
3.546875
4
# Leetcode practice # author: orange # date: 2021/6/8 # 递归法(还是学不会呀) class Solution: def generateParenthesis(self, n: int): ans = [] def DFS(s,L,R): if L<R or L>n or R>n: return if L == n and R == n: ans.append(str(s)) return # 左括号 DFS(s+"(",L+1,R) # 右括号 DFS(s+")",L,R+1) DFS("",0,0) return ans example = Solution() output = example.generateParenthesis(2) print(output)
b3ac0fbaf398833737607940fede0714d6f6d41d
duanyiting2018/learning_python
/bounce_ball_game.py
1,418
3.6875
4
from tkinter import * import time,random tk=Tk() tk.title("Bounce ball game") tk.resizable(0,0) tk.wm_attributes("-topmost",1) c=Canvas(tk,width=500,height=450,bd=0,highlightthickness=0) c.pack() tk.update() class ball: def __init__(self,ca,co): self.ca=ca self.id=ca.create_oval(10,10,30,30,fill=co) self.ca.move(self.id,245,100) starts=[-3,-2,-1,1,2,3] random.shuffle(starts) self.x=starts[0] self.y=-3 self.c_h=self.ca.winfo_height() self.c_w=self.ca.winfo_width() def draw(self): self.ca.move(self.id,self.x,self.y) pos=self.ca.coords(self.id) if pos[1]<=0: self.y=3 #print(self.y,"y") if pos[3]>=self.c_h: self.y=-3 #print(self.y,"y") if pos[0]<=0: self.x=3 #print(self.x,"x") if pos[2]>=self.c_w: self.x=-3 #print(self.x,"x") class paddle: def __init__(s,ca,co): self.id=ca.create_rectangle(0,0,100,20,fill=co) self.ca.move(self.id,200,300) def draw(self): pass ball=ball(c,"green") paddle=paddle(c,"orange") while True: ball.draw() paddle.draw() tk.update_idletasks() tk.update() time.sleep(0.03)
d7d55d52218f76b7a5585ed5c31e661a8c8a3c49
PanMaster13/Python-Programming
/Week 3/Practice files/Week 3, Practice 3.py
179
3.5
4
list1 = ["Winter","Summer","Autumn"] list2 = ["Winter","Spring"] list3 = ["Spring"] set1 = set(list1) set2 = set(list2) set3 = set(list3) answer = set1-set2-set3 print(answer)
0bee54c17cd22b4b91adb298c30a0a0c4d9304c9
conleyl9125/Conley_Liam
/PYLesson_02/Lab_2.py
259
3.578125
4
x=8 y=9 print(x*y) name = "Liam Conley" address = "13579" address2 = " Main Street" city = "San Diego" zipcode = " 92130" state=", CA" print(name) print(address + address2) print(city + state + zipcode) w = 37 l = 54 h = 76 print((w * l + h * l + h * w) * 2)
28dd35a6107f76352bb81002ad917d5cfe938112
HenDGS/Aprendendo-Python
/python/while_4.py
355
3.75
4
respostas={} booleano=True while booleano: nome = input("Qual é o seu nome? ") resposta = input("Qual é o seu animal favorito? ") respostas[nome]=resposta a=input("Vai deixar outra pessoas responder? (sim / não) ") if a=="não": booleano=False for x, y in respostas.items(): print ("O animal favorito do(a) " + x.title() + " é o " + y)
205e8956f53247180fdc0efc367b1c7a72d06591
pedrocolon93/JPythonLex
/Python Lexical Analyzer/LexicalAnalyzerPython/files/blablafile.py
1,011
3.59375
4
def srep(p): '''Print the coefficient list as a polynomial.''' # Get the exponent of first coefficient, plus 1. exp = len(p) # Go through the coefs and turn them into terms. retval = '' while p: # Adjust exponent. Done here so continue will run it. exp = exp - 1 coef = p[0] p = p[1:] # If zero, leave it out. if coef == 0: continue # If adding, need a + or -. if retval: if coef >= 0: retval = retval + ' + ' else: coef = -coef retval = retval + ' - ' # Add the coefficient, if needed. if coef != 1 or exp == 0: retval = retval + str(coef) if exp != 0: retval = retval + '*' # Put the x, if we need it. if exp != 0: retval = retval + 'x' if exp != 1: retval = retval + '^' + str(exp) # For zero, say that. if not retval: retval = '0' return retval
ab9d413b9c55b83fbae3cf3dc7e966f287a1dd70
emma-rose22/practice_problems
/leet_commonchars.py
1,444
4.03125
4
''' Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. You may return the answer in any order. Example 1: Input: ["bella","label","roller"] Output: ["e","l","l"] Example 2: Input: ["cool","lock","cook"] Output: ["c","o"] ''' class Solution: def commonChars(self, A: List[str]) -> List[str]: #make a dictionary for each word that counts the letters #add all letters to a set #use set to search through dicts #if letter in all and count is same in all, #print letter that many times #if letter and all but count is different, print lowest count #else print nothing storage = list() word_count = [] answer = [] for word in A: split = set(word) count = Counter(word) word_count.append(count) storage.append(split) u = set.intersection(*storage) for letter in u: letter_count = [] for cache in word_count: letter_count.append(cache[letter]) answer += list(letter * min(letter_count)) return answer
a57df7ea5ff8ed90b9460e5ff5f07f4ea2a29920
ATSGlobe/DataScienceTraining
/nihad/python_crash_course.py
1,161
3.90625
4
s = 'Hi there Sam!' print(s.split()) planet = "Earth" diameter = 12742 print("The diameter of {} is {} kilometers.".format(planet,diameter)) lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7] print(lst[3][1][2][0]) d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]} print(d['k1'][3]['tricky'][3]['target'][3]) def domainGet(email): return email.split('@')[-1] print(domainGet('user@domain.com')) def findDog(st): return 'dog' in st.lower().split() print(findDog('Is there a dog here?')) def countDog(st): count = 0 for word in st.lower().split(): if word == 'dog': count += 1 return count print(countDog('This dog runs faster than the other dog dude!')) seq = ['soup','dog','salad','cat','great'] print(list(filter(lambda word: word[0]=='s',seq))) def caught_speeding(speed, is_birthday): if is_birthday: speeding = speed - 5 else: speeding = speed if speeding > 80: return 'Big Ticket' elif speeding > 60: return 'Small Ticket' else: return 'No Ticket' print(caught_speeding(81,True)) print(caught_speeding(81,False))
2afd744e5550c94f06e19429be2693b128aafc5e
gtycody/Python-learning-plan
/dict_demo.py
259
4.0625
4
dict1 = {"brand": "Ford", "model": "Mustang", "year": 2016, "price": 50000} print(dict1) print(len(dict1)) print(type(dict1)) for x in dict1.keys(): print(x) for x, y in dict1.items(): print(x, y) print(dict1["brand"])
229692176cf112497c996ed64973a0496723be0b
arielt/HackerRank
/word-break.py
831
3.71875
4
# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ if not s: return False if not wordDict: return False words = set(wordDict) lens = set() for w in words: lens.add(len(w)) sl = len(s) dp = [False] * (sl + 1) dp[0] = True for i in range(1, (sl + 1)): for l in lens: if i>=l and dp[i-l] and s[i-l:i] in words: dp[i] = True break return dp[sl]
3ed8dfd1371d7ff78887df378d706bca1c1c54e9
Micky143/LPU_Python
/tuple,packing,dic etc..py
2,012
3.984375
4
rollno=[1,3,8,2,7] print(rollno) seating=[] rollno.sort() seating=rollno print(seating) #List : finite,ordered,mutable sequence of elements #extend,insert,remove,clear(),count(),index(value,[start,[stop]]),pop([index]) #sort(key=None,reverse=False) #Dictionary : Mutable map from hashable values to arbitrary objects empty={} print(type(empty)) print(type==dict()) a=dict(one=1,two=2,three=3) b={"one":1,"two":2,"three":3} print(a==b) print(a) print(b) myself={"name":"harsha","age":23,"course":"MCA","achievement":"gold medal"} print(myself) print(myself['name']) #print(myself['rollno']) #it gives KeyError myself['name']="resham" print(myself) myself['college']="LPU" print(myself) #Dictionary using list d={"ABC":[1,2,3],"XYZ":[4,5]} print(d) print(d.get("ABC")) print(d.get("XYZ")) print(d.get("PQR")) #used to avoid "not a KeyError" eng=d.get("English",[]) num_eng=len(eng) print(num_eng) del myself['achievement'] print(myself) print(myself.pop("college")) print(myself) print(myself.popitem()) print(myself) c={"one":1,"two":2,"three":3} print(c.keys()) print(c.values()) print(c.items()) print(len(c.keys())) print(('one',1) in c.items()) for value in c.values(): print(value) for key in c.keys(): print(key) #key_list=list[(c.keys)] #print(key_list) x=c.copy() print(x) #Tuple : immutalble sequences, collection of heterogenous data like struct in c #freeze sequences to ensure hashability t=("harsha","MCA","03-06-1995") print(t) print(t[0]) print(len(t)) print(t[1:]) #slicing function print("harsha" in t) t1=1234,'ABC',1.2 #packing print(t1) print(type(t1)) x,y,z=t1 #unpacking print(x) print(y) print(z) x1=10 y1=9 print(x1,y1) x1=x1^y1 y1=x1^y1 x1=x1^y1 print(x1,y1) x1,y1=y1,x1 #tuple packing print(x1,y1) for index,color in enumerate(['red','green','blue']): print(index,color)
657359c0f798ff7d67d5b754fbcf541777afaac5
raoweijin/python
/palindrome.py
672
3.515625
4
class Solution: """ @param: s: A string @return: A list of lists of string """ def isPalindrome(self, s): for i in range(len(s)): if s[i] != s[len(s)-1-i]: return False return True def dfs(self, s, stringlist): if len(s) == 0: self.res.append(stringlist) for i in range(1, len(s)+1): #if self.isPalindrome(s[:i]): if True: self.dfs(s[i:], stringlist+[s[:i]]) def partition(self, s): self.res = [] self.dfs(s, []) return self.res data="123" print(data) mySolution=Solution() res = mySolution.partition(data) print(res)
b76169e5e14a49bcc7a185bba82b749eefc4662c
kiryong-lee/Algorithm
/Codility/15-2.CountDistinctSlices.py
860
3.578125
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") # https://app.codility.com/demo/results/trainingPJZWAM-CXM/ def solution(M, A): # write your code in Python 3.6 N = len(A) if N == 1: return 1 flag = [False] * (M + 1) result = 0 start, end, add = 0, 0, 0 while start < N and end < N: a = A[start] b = A[end] # not appeared then increase add if flag[b] == False: flag[b] = True end += 1 add += 1 # appeared then add add to result and decrease add else: flag[a] = False start += 1 result += add add -= 1 # add remaining result += add * (add + 1) // 2 if result > 1000000000: result = 1000000000 return result
0508c92f1a209530711641cd9e283f44040a2e76
nana0calm/PythonLabs
/PyLab1/task11Lab1.py
392
4.125
4
# Напишите генератор frange как аналог range() с дробным шагом. #Пример вызова: #for x in frange(1, 5, 0.1): print(x) # выводит 1 1.1 1.2 1.3 1.4 … 4.9 def frange(start, end, step): while start<=end-0.2: start +=step yield start for x in frange(1, 5, 0.1): print(round(x,1))
cb9da4c2698cc8a191e8d75f83bce02f35e5b32b
Niteshraiss/python
/python_module1/week7/small.py
248
3.734375
4
small = None for i in [10, 1, 1, 0, 4, 5, 2, 9]: if small is None: small = i print('value of small', small) elif i < small: print('value of i', i) small = i print(small, '\t', i) print('Smallest', small)
6cf1aa1d471ac3381d62ece02288576dc715ad4d
aclogreco/lpthw
/ex17.py
604
3.8125
4
# ex17.py """ Exercise 17 -- Learn Python the Hard Way -- Zed A. Shaw A.C. LoGreco """ from sys import argv from os.path import exists # unpack cmd line arguments script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) in_file = open(from_file) indata = in_file.read() #print "The input file is %d bytes long" % len(indata) #print "Does the output file exist? %r" % exists(to_file) #print "Ready, hit ENTER (RETURN) to continue, CTRL-C to abort." #raw_input() out_file = open(to_file, 'w') out_file.write(indata) #print "Alright, all done." out_file.close() in_file.close()
f77db93cc190d7ed677d61aa96f9851b0fe1e4af
pfcskms1997/osscap2020
/source_code/catchmind_ver2.py
2,183
4
4
#아직 해결 못한거:LED 출력, 음성인식 #공룡게임으로 얻은 색깔 블럭 갯수를 colorlistcnt #색(빨주노초파보흰) colorlist #colorlist=["red","orange","yellow","green","blue","purple","gray"] colorlist=["black","red","green","yellow","blue","purple","skyblue"] #colorlistcnt=[0,2,3,0,4,2,3] colorlistcnt=[1,2,3,1,4,2,3] from turtle import* import time import led_display as led import threading kkk=input("그릴 것을 입력하세요") def LED_init(): t=threading.Thread(target=led.main, args=()) t.setDaemon(True) t.start() return #시작시간 측정 start=time.time() pencolor("black") title("Catch my drawing") #화면 설정 setup(1600,800) hideturtle() speed(100000) pensize(5) #평행선 h=-350 for i in range(15): up() goto(-800,h) down() forward(1600) h+=50 #수직선 v=-750 setheading(-90) for i in range(31): up() goto(v,-400) down() backward(800) v+=50 #색깔 별로 화면에 색칠해주기 def drawColor(color,b): pensize(30) pencolor(color) up() goto(725,b) down() goto(725,b-15) #화면에 색깔의 존재 나타내기 for i in range(0,7,1): if colorlistcnt[i]>0: drawColor(colorlist[i],335-i*50) #프로그램(창) 종료 def endP(): bye() while(1): mmm=input("정답을 입력하시오 : ") answer(mmm) if mmm==kkk: break #정답 def answer(mmm): if mmm==kkk: print("걸린 시간:",time.time()-start) else: print("정답이 아닙니다.") #클릭에 따라 색칠하기 def drawShape(x, y): ledcolor = 2 if 700<=x<=750: for k in range(0,7,1): if 300-50*k<y<=350-50*k: if colorlistcnt[k]>0: pencolor(colorlist[k]) ledcolor = k a=x-x%50+25 b=(y//50+1)*50 up() goto(a,b-15) down() goto(a,b-30) led.set_pixel(int((a+775)/50), int((400-b)/50), ledcolor) onkey(endP,"space") listen() LED_init() while True: onscreenclick(drawShape) mainloop() #음성인식해서 정답일 시
6a4130e2d71d6885f630a6c784ff05ec7cf81085
johndamen/streamplot2d
/streamplot2d.py
4,070
3.734375
4
from matplotlib import streamplot, pyplot as plt import numpy as np from scipy.interpolate import griddata def streamplot2d(ax, X, Y, U, V, nx=None, ny=None, color=None, linewidth=None, scale=1, **kw): """ Create a streamplot from an uneven grid :param ax: Axes instance :param X: multidimensional array of x positions :param Y: multidimensional array of y positions of same shape as X array :param U: multidimensional array of u components of same shape as X array :param V: multidimensional array of v components of same shape as X array :param nx: number of points along x for interpolation :param ny: number of points along y for interpolation :param color: line color also allows array of same shape as inputs or "magnitude" to use vector magnitude :param linewidth: line width also allows array of same shape as inputs or "magnitude" to use vector magnitude :param scale: line width scaling factor when using an array or "magnitude" for linewidths :param kw: keyword arguments (see matplotlib.streamplot.streamplot) :return: see matplotlib.streamplot.streamplot """ # define grid x = np.linspace(X.min(), X.max(), nx) y = np.linspace(Y.min(), Y.max(), ny) # interpolation coords gX, gY = np.meshgrid(x, y) u = np.ma.masked_invalid( griddata((X.flatten(), Y.flatten()), U.flatten(), (gX, gY), method='linear')) v = np.ma.masked_invalid( griddata( (X.flatten(), Y.flatten()), V.flatten(), (gX, gY), method='linear')) # set linewidths if isinstance(linewidth, np.ndarray): if linewidth.shape == U.shape: linewidth = scale*np.ma.masked_invalid( griddata( (X.flatten(), Y.flatten()), linewidth.flatten(), (gX, gY), method='linear')) elif linewidth == 'magnitude': linewidth = scale*np.absolute(u + 1j*v)**.5 if linewidth is not None: kw['linewidth'] = linewidth # set colors if isinstance(color, np.ndarray): if color.shape == U.shape: color = np.ma.masked_invalid( griddata( (X.flatten(), Y.flatten()), color.flatten(), (gX, gY), method='linear')) elif color == 'magnitude': color = np.absolute(u + 1j*v)**.5 if color is not None: kw['color'] = color # execute streamplot with equally spaced grid return ax.streamplot(x, y, u, v, **kw) if __name__ == '__main__': x = np.linspace(-3, 3, 30) y = np.linspace(-3, 3, 30) X, Y = np.meshgrid(x, y) X = X + .1 * Y Y = Y + .1 * X U = -1 - X ** 2 + Y V = 1 + X - Y ** 2 plt.figure(figsize=(12, 10)) ax = plt.subplot(231) ax.pcolor(X, Y, np.absolute(U + 1j * V), cmap='gray') ax.quiver(X, Y, U, V) ax = plt.subplot(232) ax.pcolor(X, Y, np.absolute(U+1j*V), cmap='gray') streamplot2d(ax, X, Y, U, V, nx=500, ny=500, linewidth='magnitude', density=1, scale=.8) ax = plt.subplot(233) ax.pcolor(X, Y, np.absolute(U + 1j * V), cmap='gray') streamplot2d(ax, X.flatten(), Y.flatten(), U.flatten(), V.flatten(), nx=500, ny=500, linewidth='magnitude', density=1, scale=.8) ax = plt.subplot(235) ax.pcolor(X, Y, np.absolute(U + 1j * V), cmap='gray') streamplot2d(ax, X, Y, U, V, nx=500, ny=500, color='magnitude', density=1) ax = plt.subplot(236) ax.pcolor(X, Y, np.absolute(U + 1j * V), cmap='gray') streamplot2d(ax, X.flatten(), Y.flatten(), U.flatten(), V.flatten(), nx=500, ny=500, color='magnitude', density=1) plt.show()
eb72cfba09bd4fa36fd277830afea0f5e482fa78
nikhil-sethi/courses
/Algorithmic Toolbox-Coursera/Algorithmic Warm Up/Last Digit of the Sum of Fibonacci Numbers Again/last_digit_of_the_sum_of_fibonacci_numbers_again.py
1,227
3.75
4
# python3 def last_digit_of_the_sum_of_fibonacci_numbers_again_naive(from_index, to_index): assert 0 <= from_index <= to_index <= 10 ** 18 if to_index == 0: return 0 fibonacci_numbers = [0] * (to_index + 1) fibonacci_numbers[0] = 0 fibonacci_numbers[1] = 1 for i in range(2, to_index + 1): fibonacci_numbers[i] = fibonacci_numbers[i - 2] + fibonacci_numbers[i - 1] return sum(fibonacci_numbers[from_index:to_index + 1]) % 10 def fib(n): # find nth fibonacci number F = [0, 1] if n == 0: return F[0] if n == 1: return F[1] for i in range(2, n + 1): F.append(F[i - 2] + F[i - 1]) return F[-1] def last_digit_of_the_sum_of_fibonacci_numbers_again(from_index, to_index): assert 0 <= from_index <= to_index <= 10 ** 18 F = [fib(from_index), fib(from_index+1)] s = sum(F) % 10 for i in range(from_index+2, to_index+1): F = [F[-1], (F[-1] + F[-2]) % 10] # [1,1], [1,2], [2,3] # print(F) s += F[-1] s = s % 10 return s if __name__ == '__main__': input_from, input_to = map(int, input().split()) print(last_digit_of_the_sum_of_fibonacci_numbers_again(input_from, input_to))
0b2617a207beb4799f12a40a3229b8bf10ba6a95
pegasus-dyh/pyqt5_GUI
/learn/table_tree/DataLocation.py
2,952
3.984375
4
''' 在表格中快速定位到特定的行 1. 数据的定位:findItems 返回一个列表 2. 如果找到了满足条件的单元格,会定位到单元格所在的行:setSliderPosition(row) Python笔记: python字符串格式化有两种方法 https://www.cnblogs.com/poloyy/p/12443158.html 1 % 2 format(功能更强大) 1 %示例 %o:oct 八进制 %d:dec 十进制 %x:hex 十六进制 输入 print("整数:%d,%d,%d" % (1, 22.22, 33)) print("整数不足5位,左边补空格 %5d " % 22) print("整数不足5位,左边补0 %05d " % 22) print("整数不足5位,右边补空格 %-5d " % 22, "end") print("八进制 %o" % 222) print("十六进制 %x" % 12) 输出 整数:1,22,33 整数不足5位,左边补空格 22 整数不足5位,左边补0 00022 整数不足5位,右边补空格 22 end 八进制 336 十六进制 c 输入 print("浮点数:%f,%f " % (1, 22.22)) print("浮点数保留两位小数:%.2f " % 22.222) print("浮点数保留两位小数,宽5位,不足补0:%05.2f " % 2.222) 输出 浮点数:1.000000,22.220000 浮点数保留两位小数:22.22 浮点数保留两位小数,宽5位,不足补0:02.22 输入 print("字符串:%s,%s,%s" % (1, 22.22, [1, 2])) print("字符串不足5位,左边补空格 %5s " % '2') print("字符串不足5位,右边补空格 %-5s " % '2', "end") print("字符串宽10位,截取两位 %10.2s " % "hello.world") 输出 字符串:1,22.22,[1, 2] 字符串不足5位,左边补空格 2 字符串不足5位,右边补空格 2 end 字符串宽10位,截取两位 he 2 format 示例 ''' import sys from PyQt5.QtWidgets import * from PyQt5 import QtCore from PyQt5.QtGui import QColor, QBrush class DataLocation(QWidget): def __init__(self): super(DataLocation,self).__init__() self.initUI() def initUI(self): self.setWindowTitle("QTableWidget 例子") self.resize(600, 800); layout = QHBoxLayout() tableWidget = QTableWidget() tableWidget.setRowCount(40) tableWidget.setColumnCount(4) layout.addWidget(tableWidget) for i in range(40): for j in range(4): itemContent = '(%d,%d)' %(i,j) tableWidget.setItem(i,j,QTableWidgetItem(itemContent)) self.setLayout(layout) # 搜索满足条件的Cell text = '(1' items = tableWidget.findItems(text,QtCore.Qt.MatchStartsWith) if len(items) > 0: item = items[0] item.setBackground(QBrush(QColor(0,255,0))) item.setForeground(QBrush(QColor(255,0,0))) row = item.row() # 定位到指定的行 tableWidget.verticalScrollBar().setSliderPosition(row) if __name__ == '__main__': app = QApplication(sys.argv) example = DataLocation() example.show() sys.exit(app.exec_())
d536ad106a052cef9d1a2fcffddfa3b357d2c225
harishbharatham/Python_Programming_Skills
/Prob12_3.py
661
3.71875
4
from account import account, atm for i in range (10): accountlist = [] accountlist.append(account(id1 = i)) def main1(): print(atmSim.mainMenu()) choiceInput = eval(input("Enter a choice:" )) if choiceInput == 1: print(atmSim.GetBalance()) main1() elif choiceInput == 2: d = eval(input("Enter amount to withdraw: ")) atmSim.withdraw(d) main1() elif choiceInput == 3: d = eval(input("Enter amount to deposit: ")) atmSim.withdraw(d) main1() else: None idInput = eval(input("Input your ID: ")) atmSim = atm(idInput) main1()
26cf7ccddb79917d66208c37d678de4179958df4
EpsilonHF/Leetcode
/Python/103.py
1,242
4.03125
4
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ans = [] if root is None: return ans pre = -1 nodes = [(root, 0)] for node, level in nodes: if node.left: nodes.append((node.left, level+1)) if node.right: nodes.append((node.right, level+1)) if level == pre: ans[-1].append(node.val) else: pre = level ans.append([node.val]) for i in range(len(ans)): if i % 2: ans[i] = ans[i][::-1] return ans
9f3f233f82f608ad663ed4b87f03b84f6c156638
NilPatil7087/Python_Practice
/linkedlist.py
2,329
4.0625
4
class Node: def __init__(self, value): self.data = value self.next = None def get_data(self): return self.data def get_next(self): return self.next def set_data(self, value): self.data = value def set_next(self, next_node): self.next = next_node class LinkedList: def __init__(self): self.head = None def is_empty(self): return self.head is None # adds new node to the head of the list def add(self, item): temp = Node(item) temp.set_next(self.head) self.head = temp def size(self): current = self.head count = 0 while current is not None: count += 1 current = current.get_next() return count def display(self): current = self.head print("List contents : ", end='') while current is not None: print(current.get_data(), " ", end='') current = current.get_next() print("\n") def search(self, item): current = self.head while current is not None: if current.get_data() == item: return True else: current = current.get_next() return False def remove(self, item): current = self.head previous = None found = False while not found: if current.get_data() == item: found = True else: previous = current current = current.get_next() if found: if previous is None: self.head = current.get_next() else: previous.set_next(current.get_next()) my_list = LinkedList() print("size =", my_list.size()) my_list.display() my_list.add(10) print("size =", my_list.size()) my_list.display() my_list.add(20) my_list.add(30) my_list.add(40) print("size =", my_list.size()) my_list.display() print("Is 30 present ? ", my_list.search(30)) print("Is 50 present ? ", my_list.search(50)) print("Before removing") my_list.display() my_list.remove(20) print("After removing") my_list.display() my_list.remove(30) my_list.display() my_list.add(70) my_list.display() my_list.remove(40) my_list.display() print("size=", my_list.size())
3110557b32b40cc509140cf26667c32829dbd31e
diego-guisosi/python-norsk
/02-beyond-the-basics/03-decorators/08-decorators_instances.py
748
4
4
# Applying an instance as a decorator calls the instance # This kind of decorators are useful to create collections of decorated functions, which can dinamically be # controlled class Trace: def __init__(self): self.enabled = True def __call__(self, f): def wrap(*args, **kwargs): if self.enabled: print('Calling {}'.format(f)) return f(*args, **kwargs) return wrap tracer = Trace() @tracer def rotate_list(l): return l[1:] + [l[0]] if __name__ == '__main__': l = [1, 2, 3] print(l) l = rotate_list(l) print(l) l = rotate_list(l) print(l) tracer.enabled = False l = rotate_list(l) print(l) l = rotate_list(l) print(l)
9e76abd642b7c3525728c933709f7d8365074374
KochetovNicolai/Python_822
/gulevich/review_1/dfs_generator.py
1,744
3.75
4
import random from abc import ABC, abstractmethod from Maze import Maze, Cell, State from Maze_generator import MazeGenerator class DfsGenerator(MazeGenerator): used = [] @classmethod def get_neighbours(cls, cell, width, height): # записывает в neighbours непосещённых соседей cell neighbours = [] x = cell.x y = cell.y if x + 2 < height and cls.used[x+2][y] == 0: neighbours.append(Cell(x+2, y)) if y + 2 < width and cls.used[x][y+2] == 0: neighbours.append(Cell(x, y+2)) if x - 2 >= 0 and cls.used[x-2][y] == 0: neighbours.append(Cell(x-2, y)) if y - 2 >= 0 and cls.used[x][y-2] == 0: neighbours.append(Cell(x, y-2)) return neighbours @classmethod @abstractmethod def create(cls, width, height, rand): maze = Maze(width, height) stack = [Cell(1, 1)] for i in range(maze.height): cls.used.append([0 for i in range(maze.width)]) cls.used[1][1] = 1 curr = Cell(1, 1) while len(stack) > 0: neighbours = cls.get_neighbours(curr, maze.width, maze.height) if len(neighbours) > 0: stack.append(curr) k = neighbours[random.randint(0, len(neighbours) - 1)] new = Cell((curr.x + k.x) // 2, (curr.y + k.y) // 2) # стена между двумя клетками maze.set(new, State.space) cls.used[k.x][k.y] = 1 curr = k else: curr = stack.pop() maze.set_doors(rand) cls.used = [] return maze
bbb5869d16e172a6b4fd0452382aa6bae315e0b7
khadafyb/all-labs-
/lab6quest4.py
157
3.703125
4
def check_list(list1): new2=[] new1=[] for i in list1: if i==i: new2.append(i) print(new2) return list1
270d8d8805e82ce027b65cd9c5afe46b725236ca
xiaoyaoshuai/-
/作业/7.20/058数字排序倒序.py
92
3.703125
4
info = [1,2,3,4,5] info.sort(reverse=True) print(info) s = [1,2,3,4,5] b = s[::-1] print(b)
5fc28ce60be375b986e43fc8874791204ca3879e
MaratNurzhan/WD
/week_8/informatics/if_else/D1.py
84
3.59375
4
x=int(input()) if x<0: output=-1 elif x==0: output=0 elif x>0: output=1
fde925f0273ba18b21932a416de07bf85bbb3346
Senlian/LeetCode
/v18.py
980
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d , 使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。 注意: 答案中不可以包含重复的四元组。 示例: 给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/4sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def fourSum(self, nums: 'List[int]', target: int) -> 'List[List[int]]': i, j, left, right = 0, 1, 2, len(nums)-1 if __name__ == '__main__': nums = [1, 0, -1, 0, -2, 2] target = 0 s = Solution() print(s.fourSum(nums, target))
b490af36be7c268f0025d286948bbe5188831333
LuLuuD/MSAI-Learn
/CV-Emmahuu/Code/Python basic practice/action13_0421.py
1,420
4
4
# -*- coding:utf-8 -*- #@Time: 2020/4/21 #@Author: EmmaHuu #@File: action13_0421 """ """ # def searchInsert2(nums:list, target:int, result = 0) -> int: # def splitNum(nums, target, middle): # global result # if target <= nums[middle] and target >= nums[middle - 1]: # result += middle # splitNum(nums[middle - comp::flag][::flag], target, middle) # middle = len(nums) // 2 # comp = target < nums[middle] # if len(nums) == 0: return 0 # if len(nums) == 1: return len(nums) - comp # else: # flag = 1 if target > nums[middle] else -1 # splitNum(nums, target, middle) # return result def searchInsert0(nums:list, target:int) -> int: left, right = 0, len(nums) - 1 while left <= right: pivot = (right - left) // 2 if target > nums[pivot]: left = pivot + 1 elif target < nums[pivot]: right = pivot - 1 else: return pivot return -1 def searchInsert(nums:list, target:int) -> int: if target in nums: return nums.index(target) left, right = 0, len(nums) - 1 while left <= right: #只剩一个“left == right" 也需要比较大小,直到全部比完,left > right, 结束while,返回此时记录的结果变量 pivot = left + (right - left) // 2 if target > nums[pivot]: left = pivot + 1 else: right = pivot - 1 return left print(searchInsert([1,3,5,6], 2)) print(searchInsert([1,3,5,6], 5)) print(searchInsert([1,3,5,6], 7)) print(searchInsert([1,3,5,6], 0))
fa472d74173aed424e1f1e30058f03c4d9930290
gupongelupe/ExerciciosFeitosPython
/ex007.py
149
3.609375
4
n1 = float(input('Digite sua nota: ')) n2 = float(input('Digite sua nota: ')) media = (n1 + n2) / 2 print('Sua média é: {:.2f}'.format(media))
37da6d72b69936af2bd08ba8634183b7eb72cc48
stubentiger/prog_task
/prog_task.py
971
3.96875
4
from collections import defaultdict import csv def main(): with open("product.template.csv") as opned_file: reader = csv.reader(opned_file) # skip header next(reader, None) # empty dict, when using for the first time sets default value of int (0) groups = defaultdict(int) # Each row read from the csv file is returned as a list of strings for row in reader: # for the first occurence of the group name # the key will be auto created and 0 + row[7] will be put as a value # if we already have the key simply accumulate the values groups[row[9]] += int(row[7]) # get a list of tuples instead of a dict (for sorting) groups_list = groups.items() #sorting by the second item in tuple (item[1]) + selecting the first 3 top3_gropus = sorted(groups_list, key=lambda item: item[1])[:3] print(top3_gropus) if __name__ == "__main__": main()
c91d9442f3203da1ca4cf43b7f4a982335595692
s-zhang/puzzlehunt-tools
/puzzle-utils/words/wordsearch.py
4,518
3.8125
4
from .utils.dictionary import get_current_dictionary class WordSearchResult: def __init__(self, word, row, column, direction): self.word = word self.row = row self.column = column self.direction = direction def wordsearch_reduce(grid, words): """ Finds the provided words in the grid and produces an grid with the letters that were not used. Example: >>> grid = [ 'MHEL', 'LOOS', 'WOOU', 'RLDN' ] >>> words = ['moon', 'sun'] >>> wordsearch_reduce(grid, words) ['HEL', 'LO', 'WO', 'RLD'] """ results = wordsearch_find(grid, words) working_grid = [] for row in grid: working_grid.append(list(row)) for result in results: row = result.row column = result.column row_increment, column_increment = direction_to_increment_mapping[result.direction] for _ in result.word: working_grid[row][column] = None row += row_increment column += column_increment reduced_grid = [] for row in range(len(working_grid)): reduced_grid.append('') for char in working_grid[row]: if char != None: reduced_grid[row] += char return reduced_grid def wordsearch_reduce_sentence(grid, words): """ Finds the provided words in the grid and produces string with the letters that were not used. Example: >>> grid = [ 'MHEL', 'LOOS', 'WOOU', 'RLDN' ] >>> words = ['moon', 'sun'] >>> wordsearch_reduce_sentence(grid, words) 'HELLOWORLD' """ reduced_grid = wordsearch_reduce(grid, words) return ''.join(reduced_grid) def wordsearch_find(grid, words): """ Finds the provided words and returns their location and direction in the grid. Example: >>> grid = [ 'MHEL', 'LOOS', 'WOOU', 'RLDN' ] >>> words = ['moon', 'sun'] >>> wordsearch_find(grid, words) """ normalized_words = [] for word in words: normalized_words.append(word.lower()) return wordsearch_grid(grid, wordsearch_find_function, normalized_words) def wordsearch_find_function(word, row, column, direction, words): if word in words: return WordSearchResult(word, row, column, direction) def wordsearch_brute(grid, min_length): """ Finds all words and returns their location and direction in the grid. Example: >>> grid = [ 'MHEL', 'LOOS', 'WOOU', 'RLDN' ] >>> min_length = 4 >>> wordsearch_find(grid, min_length) """ return wordsearch_grid(grid, wordsearch_brute_function, min_length) def wordsearch_brute_function(word, row, column, direction, min_length): if len(word) >= min_length and word in get_current_dictionary().words: return WordSearchResult(word, row, column, direction) def wordsearch_grid(grid, function, parameters): results = [] for row in range(len(grid)): for column in range(len(grid[row])): results += wordsearch_point(grid, row, column, function, parameters) return results def wordsearch_point(grid, row, column, function, parameters): results = [] for direction in direction_to_increment_mapping: results += wordsearch_point_direction(grid, row, column, direction, function, parameters) return results def wordsearch_point_direction(grid, row, column, direction, function, parameters): results = [] word = '' row_current = row column_current = column row_increment, column_increment = direction_to_increment_mapping[direction] while row_current > -1 and row_current < len(grid) and column_current > -1 and column_current < len(grid[row_current]): word += grid[row_current][column_current].lower() row_current += row_increment column_current += column_increment result = function(word, row, column, direction, parameters) if result != None: results.append(result) return results direction_to_increment_mapping = { 'n': [-1, 0], 'ne': [-1, 1], 'e': [0, 1], 'se': [1, 1], 's': [1, 0], 'sw': [1, -1], 'w': [0, -1], 'nw': [-1, -1] }
0e7c519ed9d42a9f94d828e2c53a0d8310b6115d
L0ganhowlett/Python_workbook-Ben_Stephenson
/18 Volume of cylinder.py
236
4.0625
4
#18 Volume of Cylinder #Asking for radius and height r = float(input("Enter the radius = ")) h = float(input("Enter the height = ")) import math #Volume of cylinder(v) print("Volume of cyliner = ",math.pi * h * (r ** 2)," sq.m")
38bf6ab07e3cdc2d86723b60173e5c5a329b4534
yongxuUSTC/challenges
/longest-common-subsequence-find-one.py
2,685
3.796875
4
#Question: Given two sequences find a Longest Common Subsequence (LCS) ''' A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. So a string of length n has 2^n different possible subsequences. References 1. http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/ 2. Tushar Roy - https://www.youtube.com/watch?v=NnD96abizww 3. Tushar Roy - https://github.com/mission-peace/interview/blob/master/src/com/interview/dynamic/LongestCommonSubsequence.java 4. WSLabs - https://www.youtube.com/watch?v=RUckZMzqUcw 5. Lec 15 | MIT 6.046J - https://www.youtube.com/watch?v=V5hZoJ6uK-s ''' #Print two dimensional matrix def PrintMatrix(Table): for row in range(0,len(Table)): for col in range(0,len(Table[row])): print("%d" % (Table[row][col]),end=" ") print("") #Time Complexity: O(mn), Space Complexity: O(mn) #Bottom-up (Dynamic Programming) #Start with the lowest values of the input and keep building the solutions for higher values def LCS(X, Y): m = len(X) #rows n = len(Y) #cols # An (m+1) times (n+1) matrix C = [[0 for j in range(n+1)] for i in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if X[i-1] == Y[j-1]: C[i][j] = C[i-1][j-1] + 1 else: C[i][j] = max(C[i][j-1], C[i-1][j]) #PrintMatrix(C) return C #Traverse the two dimensional matrix to find one LCS #Iterative def backTrackIterative(Table,X,Y,x,y): result = "" while x != 0 and y != 0: #Up if Table[x][y] == Table[x - 1][y]: x -= 1 #left elif Table[x][y] == Table[x][y - 1]: y -= 1 #diagonal else: assert X[x - 1] == Y[y - 1] #print("Substring match .... %s at position A[%d] = B[%d]" %(X[x - 1],x-1,y-1)) result = X[x - 1] + result x -= 1 y -= 1 return result #Traverse the two dimensional matrix to find one LCS #Recursive def backTrackRecursive(C, X, Y, i, j): if i == 0 or j == 0: return "" elif X[i-1] == Y[j-1]: #print ("adding ....", X[i-1]) return backTrackRecursive(C, X, Y, i-1, j-1) + X[i-1] else: if C[i][j-1] > C[i-1][j]: return backTrackRecursive(C, X, Y, i, j-1) else: return backTrackRecursive(C, X, Y, i-1, j) X = "ABCBDAB" Y = "BDCABA" m = len(X) n = len(Y) C = LCS(X, Y) print("Input strings => %s %s" % (X,Y)) #print("LCS (recursive): '%s'" % backTrackRecursive(C, X, Y, m, n)) print("LCS (iterative): '%s'" % backTrackIterative(C, X, Y, m, n))
b7bb6a67411c62ff52bc3defd2743b2d060a5583
ArunRamachandran/Problem-Solving-With-Algorithms-and-Datastructers
/Chapter5/selection_sort.py
566
3.828125
4
""" More improved version of sorting, instead of exchanging the pos of each element in every pass, only one element will be shifted to its corresponding position in each pass. """ def selection_sort(a_list) : for fill_sloat in range(len(a_list) - 1, 0, -1) : pos_max = 0 for location in range(1, fill_sloat + 1) : if a_list[location] > a_list[pos_max] : pos_max = location temp = a_list[fill_sloat] a_list[fill_sloat] = a_list[pos_max] a_list[pos_max] = temp a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] selection_sort(a_list) print a_list
009c40ed1d44ccbe2a1548f82f50e76ba9b35367
RNTejas/programming
/Functions_An_Introduction/Functions/15.Guessing game in while loop.py
706
4.0625
4
import random def get_integer(prompt): while True: temp = input(prompt) if temp.isnumeric(): return int(temp) # else: print("Please choose an Integer") highest = 1000 answer = random.randint(1, highest) print(answer) guess = 0 print("Please choose a number between 1-{}: ".format(highest)) while guess != answer: guess = get_integer(": ") if guess == 0: print("Game Over") break if guess == answer: print("Well done, You guessed it") break else: if guess > answer: print("Please chose lower") else: print("Please chose higher")
d0186cbe01e8cf3dbaedd5f31369b8231bbc2d04
PVequalnRT/Python_Study
/Python Lab/calculate_video_time/calculate_video_time0.py
1,150
3.578125
4
# 유튜브 영상 배속하면 총 걸리는 시간 계산 #시간 계산 함수 def calc(*times): a = float(input("배속을 입력해 주세요 :")) i = len(times) - 1 result = list() while(i >= 0): if i == len(times) - 1: result.append(round(times[i] / a, 2)) print(result) else: temp = str(round(times[i] / a, 1)).split('.') result[len(result) - 1] += int(temp[1]) * 6 result.append(int(temp[0])) i -= 1 result.reverse() return result # 사용자가 시간을 입력 # 시간 : 분 : 초 형태로 입력 # 분:초 형태 target = list(map(int,input("영상 시간을 입력해주세요 :").split(':'))) if len(target) == 3: #시 분 초 형식으로 입력 되면 result = calc(target[0],target[1],target[2]) print(result[0],"시간",result[1],"분",result[2],"초 걸립니다.") elif len(target) == 2: #분 초 형식으로 입력 되면 result = calc(target[0], target[1]) print(result[0],"분",result[1],"초 걸립니다.") else: print("입력 형식이 틀렸습니다. 콤마를 이용해주세요.")
95640f09cb6136344b6942ffc4bbc49aa0e8c1c4
khrithik0624/python
/minesweeper.py
4,426
3.671875
4
import random import re class Board: def __init__(self, dim_size, num_bombs): self.dim_size = dim_size self.num_bombs = num_bombs #helper function make_board to create board and plant bombs self.board = self.make_board() #assigns values to the board abot the bombs in neighbouring squares self.assign_val() #set to keep record of the places already dug self.dug = set() #if we dig at 0,0 then self.dug = {(0,0)} def make_board(self): board = [[None for _ in range(self.dim_size)] for _ in range(self.dim_size)] #planting bombs bombs_planted = 0 while bombs_planted < self.num_bombs: loc = random.randint(0,self.dim_size**2 - 1) #random loaction from 0-99 row = loc // self.dim_size col = loc % self.dim_size if board[row][col] == '*': continue else: board[row][col] = '*' bombs_planted +=1 return board def assign_val(self): for r in range(self.dim_size): for c in range(self.dim_size): if self.board[r][c] == '*': continue self.board[r][c] = self.get_num_neighbouring_bombs(r,c) def get_num_neighbouring_bombs(self,row,col): num_bombs =0 for r in range( max(0,row-1), min(self.dim_size - 1, row +1 ) +1 ): ####### for c in range ( max(0,col-1), min(self.dim_size - 1, col+1 ) +1 ): ###### if r==row and c==col: continue if self.board[r][c] == '*': num_bombs +=1 return num_bombs def dig(self, row, col): #dig at a location # return true on successful dig and false if a bomb is dug #few scenarios # hit a bomb --> GAME OVER # dig at location with neighouring bombs --> finish dig # dig at location with no neighbouring bombs --> recursively dig neighbours self.dug.add((row,col)) # to keep track of locations if self.board[row][col] == '*': return False elif self.board[row][col] > 0: return True for r in range( max(0,row-1), min(self.dim_size - 1, row + 1) + 1 ): ####### for c in range ( max(0,col-1), min(self.dim_size - 1, col + 1) + 1): ###### if (r,c) in self.dug: continue self.dig(r,c) return True def __str__(self): visible_board = [[None for _ in range(self.dim_size)] for _ in range(self.dim_size)] for row in range(self.dim_size): for col in range(self.dim_size): if (row,col) in self.dug: visible_board[row][col] = str(self.board[row][col]) else: visible_board[row][col] = ' ' s=' ' s +=' ' +' '.join(str(i) for i in range(self.dim_size))+'\n' for r in range(self.dim_size): s +=f' {r}' for c in range(self.dim_size): s +=f'| {visible_board[r][c]}' s +='|\n' return s def play(dim_size = 10, num_bombs = 10): #create board board = Board(dim_size, num_bombs) #show user board and ask them where to dig #if loaction is a bomb GAME OVER #if location is not bomb dig recursively until each square is atleast next to a bomb #repeat steps until there are no more places to dig safe = True while len(board.dug) < board.dim_size **2 - num_bombs: print(board) user_input = re.split(',(\\s)*',input("where would you like to dig? input as row,col: ")) row, col = int(user_input[0]) , int(user_input[-1]) if row<0 or row>=board.dim_size or col<0 or col>=board.dim_size: print("Invalid Input, Try Again!") continue safe = board.dig(row,col) if not safe: break if safe: print("VICTORY :)") else: print("GAME OVER") board.dug = [(r,c) for r in range(board.dim_size) for c in range(board.dim_size)] print(board) if __name__ == '__main__': play()
537df707873607f1ee44f726566c7a25b48f4882
csbailey5t/python-typing-koans
/koans/py/100-easy-variable-wrong-type.py
292
3.671875
4
""" Koan to learn the variable type annotation. """ # msg variable is wrongly annotated as int, annotate proper type msg: str = "hello world!" # salary is annotated as int, annotate proper type salary: float = 2345.67 # Set is_active as integer, annotate proper type is_active: bool = True
8af6169c216ef5ae7e39bb7ac62ff9f4e474f6af
ganluannj/Python_practice
/classes/Coordinate.py
1,420
4.21875
4
import math def sq(x): return x*x class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "<"+str(self.x)+","+str(self.y)+">" def distance(self,other): return math.sqrt(sq(self.x - other.x) + sq(self.y - other.y)) c = Coordinate(3,4) Origin = Coordinate(0,0) #%% class Clock(object): def __init__(self, time): self.time = time def print_time(self): print (self.time) boston_clock = Clock('5:30') paris_clock = boston_clock boston_clock.time = '10:30' paris_clock.print_time() boston_clock.print_time() #%% class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y def getX(self): # Getter method for a Coordinate object's x coordinate. # Getter methods are better practice than just accessing an attribute directly return self.x def getY(self): # Getter method for a Coordinate object's y coordinate return self.y def __str__(self): return '<' + str(self.getX()) + ',' + str(self.getY()) + '>' def __eq__(self, other): return (self.getX()==other.getX() and self.getY()==other.getY()) def __repr__(self): return ("Coordinate(%d, %d)" %(self.getX(), self.getY())) c1=Coordinate(15,18) c2=Coordinate(15,18) print (c1==c2) print(repr(c1))
e545b81fc3ff0bcc9d64b0c02c09858daa0dcd7b
rik0/rk-exempla
/algorithms/python/ilog2.py
736
3.578125
4
def ilog2(n): ''' Return binary logarithm base two of n. >>> ilog2(0) Traceback (most recent call last): ... ValueError: math domain error >>> ilog2(-10) Traceback (most recent call last): ... ValueError: math domain error >>> [ilog2(i) for i in range(1, 10)] [0, 1, 1, 2, 2, 2, 2, 3, 3] >>> [ilog2(2**i) for i in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [ilog2((2**i)+1) for i in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [ilog2((2**i)-1) for i in range(1,10)] [0, 1, 2, 3, 4, 5, 6, 7, 8] ''' if n <= 0: raise ValueError('math domain error') return len(bin(n)) - 3 if __name__ == '__main__': import doctest doctest.testmod()
698f0ada0d591a9dd1033f3251a0866832ba1356
pravishyatech/python_code
/fun2.py
836
4.1875
4
#wap to create a calculator using functions def get_value(): x = int(input("Enter the first value : ")) y = int(input("Enter the second value : ")) return (x, y) def add(): x,y = get_value() print(x+y) def subtract(): x,y = get_value() print(x-y) def multiply(): x,y = get_value() print(x*y) def divide(): x,y = get_value() print(x/y) def menu(): op = int(input("Menu : \n 1.Add \n 2.Subtract \n 3.Multiply \n 4.Divide \n 0.Exit \nEnter an option : ")) if op == 1: add() menu() elif op == 2: subtract() menu() elif op == 3: multiply() menu() elif op == 4: divide() menu() elif op == 0: exit() else: print ("Invalid option") menu()
26ea76fdbaf5bf2bba5e1eb3775cb2eec1c96258
Minification/exercism-track-python
/isogram/isogram.py
142
3.5625
4
def is_isogram(string: str) -> bool: letters = [s for s in string.casefold() if s.isalpha()] return len(letters) == len(set(letters))
0ad7c8fc162cb6c40315cab59723379464ec7e3f
huicheese/Bootcamp
/Lab3/Lab 3 Example 4.py
113
3.765625
4
x=16 if (x<15): if(x>8): print ('apple') else: print ('banana') else: print ('chiku')
14c83fa1dbb1e5c91cdcf2169723a47b0c7b0b60
munyumunyu/Python-for-beginners
/python-exercises/guessing.py
289
4.0625
4
# #This is a simple guessing game in Python. from random import * number = randint(1,10) while True: guess = input('Pick a number from 1 to 10: ') guess = int(guess) if guess < number: print('Its too low') elif guess > number: print('its to high') else: print('You Won') break
46c6cd1b6a62cb2f9733f32899ed553f1f00740f
pvr30/Python-Tutorial
/GUI Developement/labels_and_fields.py
504
3.71875
4
import tkinter as tk from tkinter import ttk def greet(): print(f"Hello {user_name.get() or 'World'} ") root = tk.Tk() root.title('Labels') user_name = tk.StringVar() name_label = ttk.Label(root, text='Name:') name_label.pack(side='left', padx=(0,10)) name_entry = ttk.Entry(root, width=20, textvariable=user_name) name_entry.pack(side='left') name_entry.focus() enter_button = ttk.Button(root, text='Enter', command=greet) enter_button.pack(side='left', fill='x', expand=True) root.mainloop()
c1ab3793193f34464a05b0b227f4dbd27e14c2b7
Dfmaaa/transferfile
/Python31/Sameer_database.py
5,158
3.53125
4
print("░██████╗░█████╗░███╗░░░███╗███████╗███████╗██████╗░  ░█████╗░░█████╗░██╗░░██╗██╗░░██╗░█████╗░██████╗░██╗░██████╗") print("██╔════╝██╔══██╗████╗░████║██╔════╝██╔════╝██╔══██╗  ██╔══██╗██╔══██╗██║░░██║██║░░██║██╔══██╗██╔══██╗╚█║██╔════╝") print("╚█████╗░███████║██╔████╔██║█████╗░░█████╗░░██████╔╝  ███████║██║░░╚═╝███████║███████║███████║██████╦╝░╚╝╚█████╗░") print("░╚═══██╗██╔══██║██║╚██╔╝██║██╔══╝░░██╔══╝░░██╔══██╗  ██╔══██║██║░░██╗██╔══██║██╔══██║██╔══██║██╔══██╗░░░░╚═══██╗") print("██████╔╝██║░░██║██║░╚═╝░██║███████╗███████╗██║░░██║  ██║░░██║╚█████╔╝██║░░██║██║░░██║██║░░██║██████╦╝░░░██████╔╝") print("╚═════╝░╚═╝░░╚═╝╚═╝░░░░░╚═╝╚══════╝╚══════╝╚═╝░░╚═╝  ╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░░░░╚═════╝░") print("██████╗░░█████╗░████████╗░█████╗░██████╗░░█████╗░░██████╗███████╗") print("██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝") print("██║░░██║███████║░░░██║░░░███████║██████╦╝███████║╚█████╗░█████╗░░") print("██║░░██║██╔══██║░░░██║░░░██╔══██║██╔══██╗██╔══██║░╚═══██╗██╔══╝░░") print("██████╔╝██║░░██║░░░██║░░░██║░░██║██████╦╝██║░░██║██████╔╝███████╗") print("╚═════╝░╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝╚═════╝░╚═╝░░╚═╝╚═════╝░╚══════╝") print("Type the password to enter the database.") imp=input() if imp==("sameersameer123"): print("Successfully entered database.") print("Type passwords to see the passwords.") x=input() if x==("passwords"): print("Which website? if you are not sure which website you want to see the password of then type sites.") inp=input() if inp==("sites"): print("Chess.com") print("twitter") print("gmail") print("roblox") print("hackthissite") print("MS Teams") print("stackoverflow") print("hackthebox") inp2=input() if inp2==("Chess.com"): print("The password of chess.com is chess270") if inp2==("gmail"): print("The password of gmail is inf-inf=pi") if inp2==("twitter"): print("The password of twitter is log2(-8)=3") if in2p==("stackoverflow"): print("The password of stackoverflow is stackoverflow270") if inp2==("hackthissite"): print("The password of hackthissite is samsam") if inp2==("MS Teams"): print("The password of Ms Teams is Micro$270") if inp2==("hackthebox"): print("The password of hackthebox is hackbox270") if inp==("Chess.com"): print("The password of chess.com is chess270") if inp==("gmail"): print("The password of gmail is inf-inf=pi") if inp==("twitter"): print("The password of twitter is log2(-8)=3") if inp==("stackoverflow"): print("The password of stackoverflow is stackoverflow270") if inp==("hackthissite"): print("The password of hackthissite is samsam") if inp==("MS Teams"): print("The password of Ms Teams is Micro$270") if inp==("hackthebox"): print("The password of hackthebox is hackbox270") elif(imp!=("sameersameer123")): print("Wrong password. please try again.") import Sameer_database
3efda02b44eccafad3858e02b2818e870573edc7
ToxicMushroom/bvp-python
/practicum1/piramideblokjes.py
1,135
3.90625
4
volume = 0 # variabele voor het volume van de piramide in bij te houden, geinitialiseerd op 0 omdat een piramide begint vanaf 0 zijde = -1 # variabele voor de huidige zijde in bij te houden, geinitialiseerd op -1 zodat de while lus kan beginnen vorige_zijde = -1 # variabele om de vorige zijde in bij te houden, geinitialiseerd op -1 maar heeft niet veel effect while zijde != 0: # zolang dat de ingegeven zijde verschilt van 0: zijde = int(input()) # lees het nieuw aantal blokjes van de zijde voor de volgende laag in if zijde > vorige_zijde: # als de ingegeven zijde groter is dan de vorige zijde dan beginnen we een nieuwe piramide volume = 0 # volume op 0 dus een nieuwe piramide if zijde > 0: # als de zijde groter is dan 0 volume += zijde * zijde # dan verhogen we het volume met zijde * zijde aantal blokjes ( kon ook zijde**2 ) vorige_zijde = zijde # vorige zijde wordt nu naar de huidige zijde veranderd omdat we een nieuwe zijde in de volgende iteratie zullen opvragen # ingegeven zijde was 0, we zijn uit de while lus print(volume) # print het volume van de ingegeven piramide
912b6944e58cae6f0c3db04ffe9a6810e759bf7a
ASAD5401/PYTHON-CODE
/intro to sets(hackerank).py
302
3.796875
4
def average(array): # your code goes here a=set(array) b=list(a) w=sum(b) y=len(b) t=w/y x="{0:.3f}".format(t) return x if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
51db4f241cb477db6046a5b21754f531f0679bd4
eltinawh/flotbioinfo
/modules/nbautoeval/exercice_regexp.py
4,475
3.78125
4
# -*- coding: utf-8 -*- from __future__ import print_function import re from .exercice_function import ExerciceFunction class ExerciceRegexp(ExerciceFunction): """ With these exercices the students are asked to write a regexp which is transformed into a function that essentially takes an input string and returns a boolean that says if the *whole* string matches or not """ @staticmethod def regexp_to_solution(regexp, match_mode): def solution(string): if match_mode in ('match', 'search'): if match_mode == 'match': match = re.match(regexp, string) else: match = re.search(regexp, string) if not match: return False else: return match.group(0) == string # findall returns strings, while finditer returns match instances elif match_mode == 'findall': return re.findall(regexp, string) elif match_mode == 'finditer': return [ match.span() for match in re.finditer(regexp, string)] return solution def __init__(self, name, regexp, inputs, match_mode='match', *args, **keywords): """ a regexp exercice is made with . a user-friendly name . a regexp string for the solution . a list of inputs on which to run the regexp . match_mode is either 'match', 'search' or 'findall' . additional settings from ExerciceFunction """ solution = ExerciceRegexp.regexp_to_solution(regexp, match_mode) ExerciceFunction.__init__(self, solution, inputs, *args, **keywords) self.regexp = regexp self.name = name self.match_mode = match_mode self.render_name = False def correction(self, student_regexp): student_solution = ExerciceRegexp.regexp_to_solution(student_regexp, self.match_mode) return ExerciceFunction.correction(self, student_solution) ############################## class ExerciceRegexpGroups(ExerciceFunction): """ With these exercices the students are asked to write a regexp with a set of specified named groups a list of these groups needs to be passed to construct the object the regexp is then transformed into a function that again takes an input string and either a list of tuples (groupname, found_substring) or None if no match occurs """ @staticmethod def extract_group(match, group): try: return group, match.group(group) except: return group, "Undefined" @staticmethod def regexp_to_solution(regexp, groups, match_mode): if match_mode != 'match': # only tested with 'match' so far print("WARNING: ExerciceRegexpGroups : match_mode {} not yet implemented" .format(match_mode)) def solution(string): if match_mode in ('match', 'search'): if match_mode == 'match': match = re.match(regexp, string) else: match = re.search(regexp, string) return match and [ExerciceRegexpGroups.extract_group(match, group) for group in groups] # findall returns strings, while finditer returns match instances elif match_mode == 'findall': return re.findall(regexp, string) elif match_mode == 'finditer': matches = re.finditer(regexp, string) return [ [ExerciceRegexpGroups.extract_group(match, group) for group in groups] for match in matches ] return solution def __init__(self, name, regexp, groups, inputs, match_mode='match', *args, **keywords): solution = ExerciceRegexpGroups.regexp_to_solution(regexp, groups, self.match_mode) ExerciceFunction.__init__(self, solution, inputs, *args, **keywords) self.name = name self.regexp = regexp self.groups = groups self.match_mode = match_mode self.render_name = False def correction(self, student_regexp): student_solution = ExerciceRegexpGroups.regexp_to_solution(student_regexp, self.groups, match_mode=self.match_mode) return ExerciceFunction.correction(self, student_solution)
9b6dc68ddd81b5211e727f8f3cee6f334978eaff
auttij/aoc2020
/2/exercise.py
1,098
3.53125
4
filepath = "input.txt" def read_file_to_arr(filepath): arr = [] with open(filepath) as fp: lines = fp.readlines() for line in lines: arr.append(line.strip()) return arr def exercise1(arr): results = [] for line in arr: result = check_row1(line) results.append(result) return sum(results) def exercise2(arr): results = [] for line in arr: result = check_row2(line) results.append(result) return sum(results) def check_row1(row): parts = row.split() low, high = [int(s) for s in parts[0].split("-") if s.isdigit()] char = parts[1][:-1] password = parts[2] count = password.count(char) if low <= count and count <= high: return 1 else: return 0 def check_row2(row): parts = row.split() low, high = [int(s) for s in parts[0].split("-") if s.isdigit()] char = parts[1][:-1] password = parts[2] txt = f"{password[low - 1]}{password[high - 1]}" if txt.count(char) == 1: return 1 else: return 0 if __name__ == "__main__": arr = read_file_to_arr(filepath) result = exercise1(arr.copy()) print(result) result = exercise2(arr.copy()) print(result)
82e4fa52d5d913e992dfd267b8b24e244f5ede5b
ioef/PPE-100
/Level3/q7.py
317
4.28125
4
#!/usr/bin/env python ''' Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use lambda to define anonymous functions. ''' li = [1,2,3,4,5,6,7,8,9,10] squaredElements = map(lambda x: x**2, li) print squaredElements
a2bdd5fa2632c772d69c9f6c636555bbaa7b8e79
louisspaghetti/ArminaCollab
/script.py
1,288
4.25
4
import random running = True level = 0 moves_remaining = 0 starting_value = 1 operator = 2 operation_list = ["addition", "subtraction", "multiplication", "division"] #recursive function that applies random operations to a base number to scramble it def apply_operations(base, operator = 2, iterations = 1, index = random.randint(0,3)): operation = operation_list[index] if iterations == 0: return base if operation == "addition": return apply_operations(base + operator, operator, iterations - 1) elif operation == "subtraction": return apply_operations(base - operator, operator, iterations - 1) elif operation == "multiplication": return apply_operations(base * operator, operator, iterations - 1) elif operation == "division": return apply_operations(base / operator, operator, iterations - 1) return while running: if moves_remaining <= 0: level += 1 current_value = apply_operations(starting_value, operator, level, random.randint(0,3)) moves_remaining = level print(level) print(moves_remaining) print(current_value) print("Enter the operation") current_value = apply_operations(current_value, operator, 1, operation_list.index(input())) moves_remaining -= 1
9c936a7493bf972fc57d28e8bef54ad808445d2d
mattsuri/unit3
/fri13.py
410
3.8125
4
#Matthew Suriawianta #3/1/18 #fri13.py - prints out the next 10 Friday the 13th from datetime import date yearNow = date.today().year monthNow = date.today().month dayNow = date.today().day monthAdd = 0 yearAdd = 0 if (dayNow > 13 and yearNow == 12): if dayNow > 13: monthAdd = 1 else: monthAdd = 0 while True: if weekday(yearNow + ye arAdd, monthNow +monthAdd, 13) == 4: print(
da89a798b3999f24b168e03bf4de36210db1fcec
AliE99/speech-assistant
/main.py
1,306
3.515625
4
import speech_recognition as sr import webbrowser import time r = sr.Recognizer() def record_audio(ask=False): with sr.Microphone() as source: if ask: print(ask) audio = r.listen(source) voice_data = '' try: voice_data = r.recognize_google(audio) except sr.UnknownValueError: print("Sorry, I didn't get that !") except sr.RequestError: print("Sorry, my speech service is down !") return voice_data def response(voice): if 'what is your name' in voice: print("I'm Batman !") if 'what time is it' in voice: print(time.asctime(time.localtime(time.time()))) if 'search' in voice: search = record_audio('What do you wanna search for ?') url = 'https://google.com/search?q=' + search webbrowser.open(url) print('Here is what I found for ' + search) if 'location' in voice: location = record_audio('Where do you wanna go ?') url = 'https://google.nl/maps/place/' + location + '/&amp;' webbrowser.open(url) print('Here is what I found for ' + location) if 'exit' in voice: exit() time.sleep(1) print("How can I Help you ?") while 1: voice_data = record_audio() response(voice_data)
7eb6e2fd5a853eeaa6fe0ba23d3f7c4a8ff20fcd
acc-cosc-1336/cosc-1336-spring-2018-Miguelh1997
/src/homework/main/main_homework7.py
743
3.71875
4
#write import statement for homework 7 file from src.homework.homework7 import pdistance, pdistance_matrix ''' Write a main function to... Read p_distance.dat file From the file data, create a two-dimensional list like the following example: [ ['T','T','T','C','C','A','T','T','T','A'], ['G','A','T','T','C','A','T','T','T','C'], ['T','T','T','C','C','A','T','T','T','T'], ['G','T','T','C','C','A','T','T','T','A'] ] Pass the list to the get_p_distance_matrix function as an argument Display the p distance matrix to screen ''' def main(): file = open('p_distance.dat', 'r') f = [] for line in file.readlines(): f.append(line.split()) file.close() return pdistance_matrix(f)
16cc704cb10dc4acb83823c5e4defddb91b16e5d
kaiwensun/leetcode
/1501-2000/1993.Operations on Tree.py
1,857
3.515625
4
class LockingTree: def __init__(self, parent: List[int]): N = len(parent) self.parent = parent self.locked_by = [None] * N self.locked_subtrees = [set() for _ in range(N)] def lock(self, num: int, user: int) -> bool: if self.locked_by[num] is None: self.locked_by[num] = user p = self.parent[num] while p != -1: self.locked_subtrees[p].add(num) num, p = p, self.parent[p] return True return False def unlock(self, num: int, user: int) -> bool: if self.locked_by[num] == user: self.locked_by[num] = None if not self.locked_subtrees[num]: p = self.parent[num] while p != -1: self.locked_subtrees[p].remove(num) if self.locked_subtrees[p] or self.locked_by[p] is not None: break num, p = p, self.parent[p] return True return False def upgrade(self, num: int, user: int) -> bool: if self.locked_by[num] is not None: return False if not self.locked_subtrees[num]: return False p = self.parent[num] while p != -1: if self.locked_by[p] is not None: return False p = self.parent[p] def unlock_all(num): self.locked_by[num] = None for child in self.locked_subtrees[num]: unlock_all(child) self.locked_subtrees[num].clear() unlock_all(num) self.lock(num, user) return True # Your LockingTree object will be instantiated and called as such: # obj = LockingTree(parent) # param_1 = obj.lock(num,user) # param_2 = obj.unlock(num,user) # param_3 = obj.upgrade(num,user)
5be33c75852f4c22b422a5d8c430ab7adeedb18a
rlee32/election-fraud-pennsylvania
/predict.py
1,767
3.53125
4
#!/usr/bin/env python3 import json from plot_turnout_by_age import ELECTION_YEAR, KEY_FILE, get_voters from matplotlib import pyplot as plt from typing import Dict, Set import sys MINIMUM_REGISTERED_VOTERS = 50 def plot_votes(votes: Dict[int, int], exclude: Set[int], style: str): vv = list(votes.items()) vv.sort() plt.plot([x[0] for x in vv if x[0] not in exclude], [x[1] for x in vv if x[0] not in exclude], style) if __name__ == '__main__': if len(sys.argv) != 2: print('arguments: county_name') sys.exit() county = sys.argv[1] key = json.load(open(KEY_FILE, 'r')) voters = get_voters(county) vote_count = {} voter_count = {} for v in voters: a = v['age'] if a not in voter_count: voter_count[a] = 0 voter_count[a] += 1 if v['vote']: if a not in vote_count: vote_count[a] = 0 vote_count[a] += 1 exclude = set() for a in voter_count: if voter_count[a] < MINIMUM_REGISTERED_VOTERS: exclude.add(a) plot_votes(vote_count, exclude, 'r-') overall_turnout = sum([vote_count[x] for x in vote_count]) / sum([voter_count[x] for x in voter_count]) prediction = {} for a in voter_count: k = key.get(str(a)) if k is None: prediction[a] = 0 else: prediction[a] = voter_count[a] * overall_turnout * key[str(a)] plot_votes(prediction, exclude, 'b:') plt.xlabel(f'Age (ages with less than {MINIMUM_REGISTERED_VOTERS} registered voters are hidden)') plt.ylabel('Votes (blue is prediction, red is actual)') plt.title(f'{ELECTION_YEAR} Pennsylvania County {county}: Prediction of Votes Cast vs. Age') plt.show()
17b4344c40482fa60b1f139b907f0053e06c621e
akozyreva/python-learning
/13-generators/13.2-iter.py
232
4.375
4
s = 'hello' for letter in s: print(letter) # but we can't iterate through next, only through for loop # but what we can do is s_iter = iter(s) # and now iteration works print(next(s_iter)) # show h print(next(s_iter)) # show e
80f1b9d1de9ed75f0d22fd1619a4e88665c879cc
chebypax/Python-course
/lesson3/task6.py
452
3.953125
4
def is_word_to_add(word): for symbol in word: if ord(symbol) < 97 or ord(symbol) > 122: return False return True def int_func(my_string): new_string = [] my_string = my_string.split() for word in my_string: if is_word_to_add(word): new_string.append(word.title()) return ' '.join(new_string) new_string = input('Введите предложение: ') print(int_func(new_string))
ea0e93f32f253f0408fd96bcf00f7fa7b05beeab
SREELEKSHMIPRATHAPAN/python
/python1/co1/8prgrm.py
81
3.640625
4
s=input("enter a word") con=s[0] s=s.replace(con,"$") s=con+s[1:] print(s)
74c2038a6299334425e9eb0c3e1a93db940b7cc9
viniTWL/Python-Projects
/break/ex69.py
939
3.703125
4
from time import sleep mi = men = women = 0 print('===== CADASTRO DE PESSOAS =====') while True: print('>>>> Faça o cadastro') i = int(input('Digite a idade:')) s = str(input('Digite o sexo:[M/F]')).strip().upper() while s not in 'MF': s = str(input('Digite o sexo:[M/F]')).strip().upper() if i >= 18: mi += 1 if s == 'M': men += 1 if s == 'F' and i >= 20: women += 1 r = str(input('Quer continuar cadastrando?[S/N]')).strip().upper() while r not in 'SN': r = str(input('Quer continuar cadastrando?[S/N]')).strip().upper() if r == 'S': print('-'*30) elif r == 'N': break print('\033[0;32mAnalisando os dados... Processando...\033[m') sleep(3) print(f'''De acordo com os dados: {mi} pessoas possuem mais de 18 anos. Foram cadastrados {men} homens. {women} mulheres tem mais de 20 anos.''') print('\033[1;31m===== FIM DO PROGRAMA =====')
0eca68667e922609b71db9a78582edbce5427c27
ProjectHax/pySilkroadSecurity
/python/stream.py
7,529
3.515625
4
#!/usr/bin/env python3 import struct import array class stream_reader(object): index = 0 data = None size = 0 def __init__(self, data, index=0): self.reset(data, index) def reset(self, data, index=0): if type(data) == array.array: self.data = data elif type(data) == list: self.data = array.array('B', data) else: raise Exception('incorrect data type was used to reset the class') self.size = self.data.__len__() self.seek_set(index) def bytes_left(self): return self.size - self.index def seek_forward(self, count): if self.index + count > self.size: raise Exception('index would be past end of stream') self.index += count def seek_backward(self, count): if self.index - count < 0: raise Exception('index would be < 0 if seeked further back') self.index -= count def seek_set(self, index): if index > self.size or index < 0: raise Exception('invalid index') self.index = index def read_int8(self): if self.index + 1 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('b', self.data, self.index)[0] self.index += 1 return unpacked def read_uint8(self): if self.index + 1 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('B', self.data, self.index)[0] self.index += 1 return unpacked def read_int16(self): if self.index + 2 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('h', self.data, self.index)[0] self.index += 2 return unpacked def read_uint16(self): if self.index + 2 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('H', self.data, self.index)[0] self.index += 2 return unpacked def read_int32(self): if self.index + 4 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('i', self.data, self.index)[0] self.index += 4 return unpacked def read_uint32(self): if self.index + 4 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('I', self.data, self.index)[0] self.index += 4 return unpacked def read_int64(self): if self.index + 8 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('q', self.data, self.index)[0] self.index += 8 return unpacked def read_uint64(self): if self.index + 8 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('Q', self.data, self.index)[0] self.index += 8 return unpacked def read_float(self): if self.index + 4 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('f', self.data, self.index)[0] self.index += 4 return unpacked def read_double(self): if self.index + 8 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('d', self.data, self.index)[0] self.index += 8 return unpacked def read_char(self): if self.index + 1 > self.size: raise Exception('past end of stream') unpacked = struct.unpack_from('c', self.data, self.index)[0] self.index += 1 return unpacked def read_ascii(self, length): if self.index + length > self.size: raise Exception('past end of stream') string = struct.unpack_from(str(length) + 's', self.data, self.index)[0] self.index += length return string.decode('ascii', 'replace') ''' def read_utf8(self, length): if self.index + length > self.size: raise Exception('past end of stream') string = struct.unpack_from(str(length) + 's', self.data, self.index)[0] self.index += length return string.decode('utf-8') ''' def read_utf16(self, length): length *= 2 if self.index + length > self.size: raise Exception('past end of stream') string = struct.unpack_from(str(length) + 's', self.data, self.index)[0] self.index += length return string.decode('utf-16le') def read_utf32(self, length): length *= 4 if self.index + length > self.size: raise Exception('past end of stream') string = struct.unpack_from(str(length) + 's', self.data, self.index)[0] self.index += length return string.decode('utf-32le') class stream_writer(object): data = array.array('B') index = 0 size = 0 def __init__(self, data=None): self.reset(data) def reset(self, data=None): if type(data) == array.array: self.data = data elif type(data) == list: self.data = array.array('B', data) elif data == None: self.data = array.array('B') else: raise Exception('incorrect data type was used to reset the class') self.size = self.data.__len__() self.seek_end() def tostring(self): return self.data.tostring() def tolist(self): return self.data.tolist() def tofile(self, f): return self.data.tofile(f) def toarray(self): return self.data def seek_forward(self, count): if self.index + count > self.size: raise Exception('index would be past end of stream') self.index += count def seek_backward(self, count): if self.index - count < 0: raise Exception('index would be < 0 if seeked further back') self.index -= count def seek_set(self, index): if index > self.size or index < 0: raise Exception('invalid index') self.index = index def seek_end(self): self.index = self.size def write_int8(self, val): self.__append(struct.pack('b', val)) def write_uint8(self, val): self.__append(struct.pack('B', val)) def write_int16(self, val): self.__append(struct.pack('h', val)) def write_uint16(self, val): self.__append(struct.pack('H', val)) def write_int32(self, val): self.__append(struct.pack('i', val)) def write_uint32(self, val): self.__append(struct.pack('I', val)) def write_int64(self, val): self.__append(struct.pack('q', val)) def write_uint64(self, val): self.__append(struct.pack('Q', val)) def write_float(self, val): self.__append(struct.pack('f', val)) def write_double(self, val): self.__append(struct.pack('d', val)) def write_char(self, val): self.__append(struct.pack('c', val)) def write_ascii(self, val): self.__append(bytes(val, 'ascii', 'replace')) ''' def write_utf8(self, val): self.__append(bytes(val, 'utf-8')) ''' def write_utf16(self, val): self.__append(val.encode('utf-16le')) def write_utf32(self, val): self.__append(val.encode('utf-32le')) def write(self, val): self.__append(val) def __append(self, packed): for x in packed: self.data.insert(self.index, x) self.index += 1 self.size += 1 if __name__ == '__main__': w = stream_writer() w.write_uint8(4) w.write_ascii('test') w.write_uint32(1337) w.write_int64(-1337313371337) w.write_double(1337.31337) w.write([0x75, 0x00, 0x74, 0x00, 0x66, 0x00, 0x31, 0x00, 0x36, 0x00, 0x20, 0x00, 0x77, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6b, 0x00, 0x73, 0x00]) hex_string = w.tostring() hex_list = w.tolist() hex_array = w.toarray() print('String: %s' % hex_string) print('List: %s' % hex_list) print('Array: %s\n' % hex_array) '''''''''''''''''''''''''''''''''''''''''''''''''''''' r = stream_reader(hex_array) length = r.read_uint8() string = r.read_ascii(length) integer = r.read_uint32() integer_64 = r.read_int64() double = r.read_double() utf16 = r.read_utf16(11) print('Extracted length: \'%d\'' % length) print('Extracted string: \'%s\'' % string) print('Extracted number: \'%s\'' % integer) print('Extracted signed 64-bit integer: \'%s\'' % integer_64) print('Extracted double: \'%s\'' % double) print('UTF-16: \'%s\'' % utf16) print('Bytes left: \'%s\'' % r.bytes_left())
f7a1cf9dd1c14e7e43271738204743388f2f6ef8
Simratt/N-Body_Simulation
/particle.py
1,116
4.15625
4
import pygame class Particle: ''' This is a representation of a particle in space === Attributes === - _x: the x position of the particle - _y: the y position of the particle - coords: the coordinates of the particle on the screen - size: the radius of the particle - color: the color of the particle - thickness: the thickness of the particle, this is for the pygame window === Representaion Invariants === #TODO _x: int _y: int coords: tuple(int, int) size: [int, float] color: tuple(int,int,int) thickness: int ''' def __init__(self, x: int ,y: int, size: int) -> None: ''' the constructor for the particle class''' self._x = x self._y = y self.coords = (self._x, self._y) self.size = size self.color = (255,255,255) self.thickness = 1 def display(self, screen: pygame.display) -> None: ''' this function draws the particle onto a paygame window''' pygame.draw.circle(screen, self.color, self.coords, self.size, self.thickness)
525fe7ffeada498adee6c83b8ac39631e97352f8
ttomchy/LeetCodeInAction
/others/q57_insert_interval/solution.py
1,867
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ FileName: solution.py Description: Author: Barry Chow Date: 2020/11/4 5:16 PM Version: 0.1 """ class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: start = newInterval[0] end = newInterval[1] res = [] if len(intervals) == 0: res.append(newInterval) return res find_left = False find_right = False for i, (left, right) in enumerate(intervals): # 还没找到start所在的区间 if not find_left: # 起始点在当前区间和上一个区间之间 if start < left: find_left = True # 起始点在这个区间 elif start <= right: find_left = True start = left # 起始点不在这个区间,在后面区间 elif start > right: res.append(intervals[i]) # 找到start所在的区间,再寻找end if not find_right: # end在当前区间和之前区间之间 if end < left: res.append([start, end]) res.append([left, right]) find_right = True # end在当前区间内 elif end <= right: end = right res.append([start, end]) find_right = True # end在之后的区间 elif end > right: # 若是最后一个元素,需要保存值 if len(intervals) - 1 == i: res.append([start, end]) else: res.append(intervals[i]) return res
94b4aa4bc9f5e528aa60a9b311a5b27ab27a3dff
neroexpress/GitHubRepo
/Amne/subranges.py
2,563
3.703125
4
''' Code developed by - Narender Kumar This code requires Python 3.0, and for other versions, the code will not compile. Please make sure that all the required contstraints are met in the input text file, the code will not check for the required constraints. That is 1 ≤ N ≤ 200,000 days and 1 ≤ K ≤ N days. This code creates an output text file(output.txt), in the same directory as this program. ''' # The code starts from here input_file_name = "input.txt" output_file_name = "ouput.txt" def read_text_file(fn): ''' This function reads the text file and stores the N value and K value in data structure. This function also stores the sale price from the input text file ''' with open(fn) as f: read_data = f.readlines() i=1 N_values = list() for x in read_data: if i==1: K_values = [int(y) for y in x.split()] i+=1 else: x = [int(x) for x in x.split()] N_values.extend(x) return K_values,N_values def number_of_increasing_Subranges(window): ''' This function returns the number of increasing subranges. ''' increasing_subrange = 0 for j in range(len(window)-1): for i in range(len(window)-1): new_window = window[j:len(window)-i] if len(new_window)<2:continue if all(new_window[p] < new_window[p+1] for p in range(len(new_window)-1)): increasing_subrange +=1 return increasing_subrange def number_of_decreasing_Subranges(window): ''' This function returns the number of decreasing subranges. ''' decreasing_subrange = 0 for j in range(len(window)-1): for i in range(len(window)-1): new_window = window[j:len(window)-i] if len(new_window)<2:continue if all(new_window[p] > new_window[p+1] for p in range(len(new_window)-1)): decreasing_subrange +=1 return decreasing_subrange def do_computation(k,n_list): ''' This function returns a list of increasing subranges within the window minus the number of decreasing subranges within the window. ''' j = 0 computed_list = list() for x in range(k[0]- k[1]+1): num_inc = number_of_increasing_Subranges(n_list[j:k[1]+j]) num_dec = number_of_decreasing_Subranges(n_list[j:k[1]+j]) j+=1 #print(num_inc-num_dec) computed_list.append(num_inc-num_dec) return computed_list def print_to_textfile(fn,list_of_values): ''' This function prints the answer to a output text file as well to the consol. ''' with open(fn,'wt') as f: for s in list_of_values: print(s) print(s, file=f) K_values,N_values = read_text_file(input_file_name) print_to_textfile(output_file_name,do_computation(K_values,N_values)) #End of code
9edce05dad818bcbcb1567e6d383730c317b26a5
LamprechtMatyas/Python_labs
/palindrome.py
428
3.921875
4
import sys def _main(): input_string = sys.argv[1] isPalindrome = True for i in range((len(input_string) + 1)//2): if input_string[i] != input_string[len(input_string) - 1 - i]: isPalindrome = False break if isPalindrome: print("This is palindrome") else: print("This is not palindrome") # Or s == s[::-1] :) if __name__ == "__main__": _main()
40b8d227dc9d8524f90ee55105fd24bf24f2d19a
shir21-meet/meetyl1
/facebook.py
918
3.703125
4
class User(): def __init__(self, name, email, password): self.name = name self.email = email self.password = password self.friends_list = [] self.posts = [] def add_friends(self, email): self.friends_list.append(email) print(self.name + " has added " + email + " as a friends ") def remove_friends(self, email): self.friends_list.remove(email) print(self.name + " has removed " + email + " as a friends ") def post(self,text): self.posts.append(text) print(self.name + " has postsed : " + text) def get_userInfo(self): print(" name: " + str(self.name)) print(" email: " + str(self.email)) print(" password: " + str(self.password)) print("friends: " + str(self.friends_list)) print(" posts: " + str(self.posts)) User1= User("Shir", "shir15@meet.mit.edu" , "shir1234") User2= User("Yousef", "Yousef15@meet.mit.edu", "Yousef1234" ) User1.add_friends("Yousef15@meet.mit.edu") User2.post("hi shir") User1.get_userInfo()
8619a4734ace9ed6082e68ac1b98443190be7378
AlexandraWin/Pyautogui_AW
/Lists_AW.py
580
3.84375
4
import time subjects = ['Comp Sci', 'History', 'Spanish', 'Science', 'Math', 'Dance'] for i in subjects: if i == "History": print ("My favortie subject is " + i + "!!!") else: print ("I like " + i + "!")\ friends = ['Hedgehogs', 'My Bed', 'Hunter', 'Noah Snapp', 'John', ] for i in friends: print (i.title() + " is awesome!") myname = "" letters = [ 'm', 'r', '.', ' ', 'p', 'i', 'c', 'k', 'l', 'e', 's',] for i in letters: myname = myname + i print (myname) time.sleep(0.5) print (myname.title())
1f885a981f6f3ac5f9495c5888ffff78699713fc
PedroGal1234/unite1
/quiz1.py
307
4.03125
4
#Pedro Gallino #9/11/17 #quiz1.py - my first proggramming quiz print('Juan Pedro Gallino') num1 = int(input('Enter a number: ')) num2 = int(input('Enter another number: ')) print('The sum of your numbers is: ', num1+num2) print('The product of your numbers is: ', num1*num2) print('Your lucky number is:',(num1*7)+(num2*7))
2980788f2903ddf1ab5662c761d2cff30cd65076
sunshine-mtt/Selenium
/currency_exchange.py
1,087
3.84375
4
#美元汇率 USD_EXCHANGE_RATE = 6.77 #输入货币金额 currency_str_value = input("请输入带有单位的货币金额(如果退出请按Q): ") #统计循环次数 i = 0 while currency_str_value != 'Q': i = i + 1 # 获取货币单位 unit = currency_str_value[-3:] if unit == 'CNY': # 获取货币金额 rmb_str_value = currency_str_value[:-3] rmb_value = eval(rmb_str_value) usd_value = rmb_value / USD_EXCHANGE_RATE print("美元汇兑金额是:", usd_value) elif unit == 'USD': # 获取货币金额-字符串 usd_str_value = currency_str_value[:-3] # 获取货币金额 usd_value = eval(usd_str_value) rmb_value = usd_value * USD_EXCHANGE_RATE print("人民币汇兑金额是:", rmb_value) else: print("您输入的货币单位不在查询范围") print("************************************") # 输入货币金额 currency_str_value = input("请输入带有单位的货币金额(如果退出请按Q): ") print("您已退出程序!")
ca427c708390f5a2f31c99007dc624ba8502daf8
omakasekim/python_algorithm
/00_자료구조 구현/queue_파이썬의 데크 이용.py
399
3.609375
4
from collections import deque queue = deque() # 맨 뒤에 데이터 추가 queue.append('지우') queue.append('광호') queue.append('지희') queue.append('주현') queue.append('용현') print(queue) # 맨 앞 데이터에 접근 print(queue[0]) # 맨 앞 데이터 삭제(삭제하는 데이터를 return) print(queue.popleft()) print(queue.popleft()) print(queue.popleft()) print(queue)
d53fd86411cfc51dfb630ac38e0681f17871e445
quickeee/Coding-Bootcamp
/Prepatory weeks/28_09_2016_Python/exercise_2.py
335
4.03125
4
bitnumber = input('Please enter the 8-bit binary number for check: ') if len(bitnumber) == 8: sum = 0 for i in range(0,8): sum += int(bitnumber[i]) if sum%2 == 0: print('Parity check ok!') else: print('Parity check not ok') else: print('The number you entered in not a valid 8-bit number!')
732dec0d02e4af8787436b9e62c3d9113db76517
calmcat/Algorithm
/bubble_sort.py
238
3.78125
4
def bubble_sort(A): for i in xrange(len(A)-1): for j in xrange(len(A)-1, i, -1): k = j-1 if A[j] < A[k]: A[j-1], A[j] = A[j], A[j-1] A = [8, 7, 6, 5, 4, 3, 2, 1] bubble_sort(A) print A
447cab83643fcb45511d17064344526e59e813bd
rigsbyk/python-challenge
/PyPoll/main.py
3,460
4.1875
4
#!/usr/bin/env python # coding: utf-8 #import os provides function for interacting with the operating system(OS) #import csv is a module for importing and reading csv files import os import csv #provides the path of the csv file "election_data.csv" election_data = os.path.join("Resources","election_data.csv") #initially setting variables vote_count = 0 candidate_percent = 0 #created lists to store data candidate_khan= [] candidate_correy = [] candidate_li = [] candidate_otooley = [] winner = [] #opens up the csvfile from the data_budget path provided above #csvreader iterates over each line of the csvfile with open(election_data) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") #next(csvreader) just reads over the header; removing it from calculations csv_header = next(csvreader) #going through each row after the header and first_row for row in csvreader: #using a count to grab total votes vote_count += 1 #using a conditional to sort the candidates for calculations #then storing that data to a list for each candidate if (row[2] == "Khan"): candidate_khan.append(row[2]) elif (row[2]) == "Correy": candidate_correy.append(row[2]) elif (row[2]) == "Li": candidate_li.append(row[2]) elif (row[2]) == "O'Tooley": candidate_otooley.append(row[2]) #Finding out number of votes for each candidate khan_votes = len(candidate_khan) correy_votes = len(candidate_correy) li_votes = len(candidate_li) otooley_votes = len(candidate_otooley) #Finding out percent of votes for each candidate khan_per = (khan_votes/vote_count) *100 correy_per = (correy_votes/vote_count) *100 li_per = (li_votes/vote_count) *100 otooley_per = (otooley_votes/vote_count) *100 #Setting up to compare each candidate list to find the winner #the max value will be the winner winner = [khan_votes,correy_votes,li_votes,otooley_votes] final_winner = max(winner) #Using a conditional to find the max value and who has that max value if final_winner == khan_votes: winner_name = 'Khan' elif final_winner == correy_votes: winner_name = "Correy" elif final_winner == li_votes: winner_name = "Li" elif final_winner == otooley_votes: winner_name = "O'Tooley" #created a string to be able to call on for both print and output results = ( f"Election Results\n" f"-----------------------------\n" f"Total Votes:{vote_count}\n" f"-----------------------------\n" f"Kahn:{ckhan} {khan_per:.3f}% ({khan_votes})\n" f"Correy: {correy_per:.3f}% ({correy_votes})\n" f"Li: {li_per:.3f}% ({li_votes})\n" f"O'Tooley: {otooley_per:.3f}% ({otooley_votes})\n" f"-----------------------------\n" f"Winner:{winner_name}\n" f"-----------------------------\n" ) #print results print(results) #provides path of output results for new text file analysis.txt outpath = os.path.join("Analysis", "analysis.txt") #opens file for writing and writes the results to analysis.txt with open(outpath, "w") as text_file: text_file.write(results)
7dfae30b2f25ade8b2cb75ecd66bfbe9c8261a9e
xiyiwang/leetcode-challenge-solutions
/2021-01/2021-01-25-kLengthApart.py
2,335
3.546875
4
# LeetCode Challenge: Check If All 1's Are at Least Length K Places Away (01/25/2021) # Given an array nums of 0s and 1s and an integer k, return True if all 1's are at # least k places away from each other, otherwise return False. # # Constraints: # * 1 <= nums.length <= 10^5 # * 0 <= k <= nums.length # * nums[i] is 0 or 1 # Submission Detail: # * Runtime: 564 ms (better than 66.89% of python3 submissions) # * Memory Usage: 17 MB (better than 64.65% of python3 submissions) def kLengthApart(nums: [int], k: int) -> bool: if k == 0 or not 1 in nums: return True # remove leading 0's if any first_one_idx = nums.index(1) if first_one_idx != 0: nums = nums[first_one_idx:] while nums: if len(nums) == 1 or not 1 in nums[1:]: return True next_one_idx = nums[1:].index(1) + 1 if next_one_idx <= k: return False sub_arr = nums[:next_one_idx] if sub_arr: nums = nums[next_one_idx:] return True # Official Solution 1 - One Pass + Counter: def kLengthApart1(nums: [int], k: int) -> bool: # initialize the counter of zeros to k # to pass the first 1 in nums count = k for num in nums: # if the current integer is 1 if num == 1: # check that number of zeros in-between 1s # is greater than or equal to k if count < k: return False # reinitialize counter count = 0 # if the current integer is 0 else: # increase the counter count += 1 return True # Official Solution 2 - Bit Manipulation: def kLengthApart2(nums: [int], k: int) -> bool: # convert binary array into int x = 0 for num in nums: x = (x << 1) | num # base case if x == 0 or k == 0: return True # remove trailing zeros while x & 1 == 0: x = x >> 1 while x != 1: # remove trailing 1-bit x = x >> 1 # count trailing zeros count = 0 while x & 1 == 0: x = x >> 1 count += 1 # number of zeros in-between 1-bits # should be greater than or equal to k if count < k: return False return True
28e37f4dd13f1842d48b6c59e8bded09688301bc
parvathi98/Basic
/program/6.py
192
3.640625
4
cm = 1000; meter = cm / 100.0; kilometer = cm / 100000.0; print("Length in meter = " , meter , "m"); print("Length in Kilometer = ", kilometer , "km");
3c097187ae7d7dae2bbc249c1e5988b97a18cf7f
jvalansi/word2code
/word2code/res/translations/TriFibonacci.py
1,705
4.0625
4
from problem_utils import * class TriFibonacci: def complete(self, A): input_array = A # A TriFibonacci sequence begins by defining the first three elements A[0], A[1] and A[2]. # The remaining elements are calculated using the following recurrence: A[i] = A[i-1] + A[i-2] + A[i-3] def mapping(possibility): #### return ((A[(i - 1)] + A[(i - 2)]) + A[(i - 3)]) return ((A[(possibility - 1)] + A[(possibility - 2)]) + A[(possibility - 3)]) # You are given a int[] A which contains exactly one element that is equal to -1, you must replace this element with a positive number in a way that the sequence becomes a TriFibonacci sequence. #### number = A_(indexOf(A, -1)) possibilities = mapping(indexOf(A, (-1))) # Return this number. #### return number return possibilities # If no such positive number exists, return -1. # def example0(): cls = TriFibonacci() input0 = [1,2,3,-1] returns = 6 result = cls.complete(input0) return result == returns def example1(): cls = TriFibonacci() input0 = [10, 20, 30, 60, -1 , 200] returns = 110 result = cls.complete(input0) return result == returns def example2(): cls = TriFibonacci() input0 = [1, 2, 3, 5, -1] returns = -1 result = cls.complete(input0) return result == returns def example3(): cls = TriFibonacci() input0 = [1, 1, -1, 2, 3] returns = -1 result = cls.complete(input0) return result == returns def example4(): cls = TriFibonacci() input0 = [-1, 7, 8, 1000000] returns = 999985 result = cls.complete(input0) return result == returns if __name__ == '__main__': print(example0())
5d100f66a04f3aad4a426cb2a299bec161550442
kmoreti/python-masterclass
/Comprehensions/listcomp.py
279
3.890625
4
print(__file__) numbers = [1, 2, 3, 4, 5, 6] number = int(input("Please enter a number, and I'll tell its square: ")) squares = [number ** 2 for number in numbers] # squares = [number ** 2 for number in range(1, 7)] index_pos = numbers.index(number) print(squares[index_pos])
d66d45a518af7f0376f1f0b87655e6310dca87a3
subbuinti/python_practice
/getseassion.py
362
4.03125
4
month = int(input()) winter = (((month==12) or (month ==11)) or (month ==1)) spring = ((month == 2) or (month ==3)) summer = (((month ==4) or (month ==5)) or (month ==6)) rainy = ((month ==7) or (month == 8)) if winter: print("Winter") elif spring: print("Spring") elif summer: print("Summer") elif rainy: print("Rainy") else: print("Autumn")
d666f8ce550f99690f15d1bad9bfedd2ddcd0027
beatriceziliani/esercizi-libro
/Python/28.py
271
3.8125
4
valori= [] print ("rispondi con 0 al punteggio se hai finito") while True: nome = input ("Inserisci il nome dello studente") punteggio = int (input ("quanti punti ha fatto?")) if punteggio == 0: break valori.append(punteggio) print (max (valori))
161f1df0e0fe00a17d34f74a9b41d1f9505e6dfa
darsovit/AdventOfCode2020
/Day23/Day23.py
1,292
3.5625
4
#!python class CrabCups: def __init__(self, start): self.state = start self.rounds = 0 def __nextLower(aChar): if aChar == '1': return '9' return chr(ord(aChar)-1) def playRound(self): saved_cups = self.state[1:4] interstate = self.state[:1] + self.state[4:] findvalue = CrabCups.__nextLower(self.state[0]) pos = interstate.find(findvalue) while pos is -1: findvalue = CrabCups.__nextLower(findvalue) pos = interstate.find(findvalue) #print('found: {} in {} at pos {}'.format(findvalue,interstate,pos)) assert pos != 0, 'Next lower from {} should not be {} at pos 0, state= {}'.format(self.state[0], findvalue, self.state) self.state = interstate[1:pos+1] + saved_cups + interstate[pos+1:] + interstate[0] self.rounds += 1 def __repr__(self): return '{{rounds: {}, state: {}}}'.format( self.rounds, self.state ) def test(): game = CrabCups( '389125467' ) print(game) for i in range(10): game.playRound() print(game) for i in range(90): game.playRound() print(game) test() game = CrabCups( '219748365' ) for i in range(100): game.playRound() print(game)
cebf74b1d7adcf746c5e97fdb8bfcd83827f79f2
JohnEspenhahn/algorithms
/dynamic programming/longest_palindrome.py
568
3.734375
4
def find_longest(s): """ :type s: str :rtype: int """ p = [[0]*len(s) for i in range(len(s))] max_lng = 0 max_start = 0 max_end = 0 for lng in range(0,len(s)): for i in range(0,len(s)-lng): j = i + lng if (lng == 0): p[i][j] = True elif (lng == 1): p[i][j] = (s[i] == s[j]) else: p[i][j] = (s[i] == s[j] and p[i+1][j-1]) if p[i][j] and lng > max_lng: max_lng = lng max_start = i max_end = j return s[max_start:max_end+1] print(find_longest("cbbd"))
7a92d43dfedfe78286a0618bf66eb53b9bc4ca37
albert-yakubov/py-practice
/hackerrank/pairs_of_socks.py
887
3.796875
4
#!/bin/python3 import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): # color doesnt matter here because to make a pair of socks you only need two socks # same answer goes for same color socks # iniate count count = 0 ar.sort() ar.append('#') i = 0 while i < n: # if the numbers are matching if ar[i]==ar[i+1]: #increment count count = count + 1 # of pairs so by 2 i += 2 else: i += 1 return count print(sockMerchant(9, [1,2,3,4,4,3,2,2,2])) # if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # n = int(input()) # ar = list(map(int, input().rstrip().split())) # result = sockMerchant(n, ar) # fptr.write(str(result) + '\n') # fptr.close()
b725ad0961fadcd78df9199f97232ffc4041b9de
shuheiktgw/data_structures
/Programming-Assignment-1/tree_height/tree_height.py
1,330
3.703125
4
# python3 import sys, threading sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size class Node: def __init__(self): self.children = [] def add_child(self, child): self.children.append(child) class Tree: def __init__(self, n, parent): self.nodes = [] for i in range(n): self.nodes.append(Node()) for i in range(n): if parent[i] == -1: self.root = self.nodes[i] else: self.nodes[parent[i]].add_child(self.nodes[i]) def height(self): return self._compute_height(self.root) def _compute_height(self, node): h = [0] for child in node.children: h.append(self._compute_height(child)) return 1 + max(h) class TreeHeight: def read(self): self.n = int(sys.stdin.readline()) self.parent = list(map(int, sys.stdin.readline().split())) def compute_height(self): tree = Tree(self.n, self.parent) return tree.height() def main(): tree = TreeHeight() tree.read() print(tree.compute_height()) threading.Thread(target=main).start()
9a681664cc59eca8b7ea2f40cd444b97c9550052
daniel-reich/turbo-robot
/e6fL5EiwGZcsW7C5D_17.py
949
4.03125
4
""" Create a function that converts a string of letters to their respective number in the alphabet. A| B| C| D| E| F| G| H| I| J| K| L| M| N| O| P| Q| R| S| T| U| V| W| ... ---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|--- 0| 1| 2| 3| 4| 5| 6| 7| 8| 9| 10| 11| 12| 13| 14| 15| 16| 17| 18| 19| 20| 21| 22| ... ### Examples alph_num("XYZ") ➞ "23 24 25" alph_num("ABCDEF") ➞ "0 1 2 3 4 5" alph_num("JAVASCRIPT") ➞ "9 0 21 0 18 2 17 8 15 19" ### Notes * Make sure the numbers are spaced. * All letters will be UPPERCASE. """ def alph_num(txt): output="" alphorder = { "A": 0,"B": 1,"C": 2,"D": 3,"E": 4,"F": 5,"G": 6,"H": 7,"I": 8,"J": 9,"K": 10,"l": 11,"M": 12,"N": 13,"O": 14,"P": 15, "Q": 16,"R": 17,"S": 18,"T": 19,"U": 20,"V": 21,"W": 22,"X": 23,"Y": 24,"Z": 25} for i in txt: output=output+str(alphorder[i])+' ' return output[:-1]
3c4b18dc9652d5beb8be8c3904b12ebe32f46606
zhangruochi/OnlineLearning
/Data Structures and Algorithms/Algorithmic Toolbox/week 1/max_pairwise_product.py
1,422
3.515625
4
#python3 def fast_method(a, n): max_indice_1 = -1 for i in range(n): if max_indice_1 == -1 or a[i] > a[max_indice_1]: max_indice_1 = i max_indice_2 = -1 for j in range(n): if j != max_indice_1 and (max_indice_2 == -1 or a[j] > a[max_indice_2]): max_indice_2 = j #print(max_indice_1, max_indice_2) return a[max_indice_1] * a[max_indice_2] n = int(input()) a = [int(x) for x in input().split()] assert(len(a) == n) result = fast_method(a,n) print(result) """ def slow_method(a, n): result = 0 for i in range(0, n): for j in range(i + 1, n): if a[i] * a[j] > result: result = a[i] * a[j] return result import random def stress_test(): random.seed(10) while(True): # the number of sequence n = random.randint(1000,10000) * 2 # the sequence a = [random.randint(0, 10) * 10 for _ in range(n)] #print(n) #print(a) result_fast = fast_method(a, n) result_slow = slow_method(a, n) if result_fast == result_slow: print("result_fast: {}, result_slow: {}".format( result_fast, result_slow)) else: print("result_fast: {}, result_slow: {}".format( result_fast, result_slow)) break print("") if __name__ == '__main__': stress_test() """
612bcb009f157e7f8972a33f0b7693fc9e2398d0
adityaKoteCoder/codex
/q_6.py
247
4.375
4
#accept a number from the uder and display if it is a palindome or not def reverse_num(num): num=int(input("enter the number")) rev=0 while num!=0: rev=rev*10+num%10 num=num/10 print(f"{num} is a palindrome")
1c1501e13cc6732ca55e3270de76306db9baa8df
ThanatoSohne/Misc-Projects
/Python Language/startNew.py
4,473
3.640625
4
# -*- coding: utf-8 -*- from bs4 import * from bs4 import BeautifulSoup as soup from urllib.request import urlopen as req from urllib.request import Request from termcolor import colored as cl import random as rn import wikipedia as wiki #Function to scrape and pull the word of the day from Dictionary.com def wordADay(): nary = "https://www.dictionary.com/e/word-of-the-day/" naryClient = req(nary) site_parse_nary = soup(naryClient.read(), "lxml") naryClient.close() #Pull from 'Word of the Day' wrapper wordDayCase = site_parse_nary.find("div", {"class": "wotd-item-wrapper"}) #Pull the word itself wordDay = wordDayCase.find("div", {"class": "wotd-item-headword__word"}).text.strip() #Pull the pronunciation wordSpeak = wordDayCase.find("div", {"class": "wotd-item-headword__pronunciation"}).text.strip() #Pull the definition wordMean = wordDayCase.find("div", {"class": "wotd-item-headword__pos-blocks"}) wordType = wordMean.find("span").text.strip() wordDef = wordMean.findAll("p")[1].text.strip() print(cl(wordDay, "blue")) print(cl(wordSpeak, "red")) print(cl("----------------------", "grey")) print(cl("Word type: " + wordType, "cyan")) print(cl(wordDef, "blue")) # tab1_layout = [ # [sg.T(wordDay)], # [sg.T(wordSpeak)], # [sg.T('---------')], # [sg.T('Word type: ' + wordType)], # [sg.T(wordDef)] # ] # # return tab1_layout #Function to pull a random quote from the GoodReads popular quotes page def quoteADay(): goodReads = "https://www.goodreads.com/quotes" goodClient = req(goodReads) site_parse_quote = soup(goodClient.read(), "lxml") goodClient.close() #Pull from the left container quotesOnly = site_parse_quote.find("div", {"class": "leftContainer"}) #Randomly choose a quote from the front page ranQuote = quotesOnly.find("div", {"class": "quotes"}).findAll("div", {"class": "quote"})[rn.randrange(30)] #Pull info from ranQuote sourceQuote = ranQuote.find("span").text.strip() quote = ranQuote.find("div", {"class": "quoteText"}).text.strip().split('\n')[0] #Give a little background info about the author of the quote authorInfo = wiki.summary(sourceQuote, sentences=1) print(cl(quote, "green")) print(cl('~'+'\033[1m'+sourceQuote+'~', "magenta")) print(cl(authorInfo, "magenta")) # tab2_layout = [ # [sg.T(quote)], # [sg.T('~'+sourceQuote+'~')], # [sg.T(authorInfo)] # ] # # return tab2_layout #Function to pull a random word from dict.tu def deustchesWort(): dicttu = "https://dict.tu-chemnitz.de/dings.cgi?o=3020;service=deen;random=en" dictClient = req(dicttu) site_parse_deutsch = soup(dictClient.read(), "lxml") dictClient.close() #Pull a subject in order to find a word subDeutsch = site_parse_deutsch.find("div", {"class": "result"}).find("table", {"id": "result"}) wortAlles = subDeutsch.find("tbody", {"id": "h1"}).find("tr", {"class": "s1"}).text.strip() wort = wortAlles.split('\n')[0] wortDef = wortAlles.split('\n')[1] print(cl("Deutsches Wort: ", "yellow")) print(cl(wort, "blue")) print(cl("auf Englisch: " + wortDef, "red")) #In case a search is incomplete or not found try: wortInfo = wiki.summary(wortDef,sentences=2, auto_suggest=False) except: print("Page not found for English entry") else: print(cl(wortInfo, "green")) def main(): print(cl("~~~~~~~~~~~~~~~Word of the Day~~~~~~~~~~~~~~~~", "grey")) wordADay() print(cl("~~~~~~~~~~~~~~~Quote for the Day~~~~~~~~~~~~~~", "grey")) quoteADay() print(cl("~~~~~~~~~~~~~German Word of the Day~~~~~~~~~~~~~", "grey")) deustchesWort() # sg.theme('Dark Blue 3') # # layout = [[ # sg.TabGroup([ # [sg.Tab('Word of the Day', wordADay()), # sg.Tab('Quote for the Day', quoteADay())] # ]) # ]] # # window = sg.Window('Start New', layout, # grab_anywhere=True, finalize=True) if __name__ == "__main__": main()
4fc8adf3c677113fc2b20efbd203e9296eb2714d
AnaArce/introprogramacion
/Practico_1/Ejercicio_11.py
446
3.6875
4
#Programa que entregue la edad del usuario a partir de su fecha de nacimiento from time import localtime t = localtime() año_ac = t.tm_year mes_ac = t.tm_mon dia_ac = t.tm_mday año = int(input("Año: ")) mes = int(input("Mes: ")) dia = int(input("Dia: ")) #año edad1 = año_ac - año #mes edad2 = mes_ac - mes #dia edad3 = dia_ac - dia if edad2 < 0: print("Usted tiene", (edad2-1), "años") else: print("Usted tiene", edad1, "años")
f4f327836daf5271a397819b1d73809b291147ae
timofeyabramski/Ising-model-files
/hello.py
496
4.125
4
#!/usr/bin/env python class bikes: 'common base class for bikes' bikecount = 0 def _init_(self, name, cost): self.name = name self.cost = cost bikes.bikecount += 1 def displayCount(self): print "Total number of bikes %d" % self.bikecount def displayCount(self): print "Name : ", self.name, ", cost: ", self.cost "This would create first object of bikes class" bike1 = bikes("Trek Madone", 2000) "This would create a second object of bikes class" bike2 = bikes("Cube Agree", 2400)
1979be1c034fc762398263ba75035f17c4386e73
tjhamad/CheckiO
/monkey typing.py
497
3.828125
4
# -*- coding: utf-8 -*- from datetime import date def days_diff(date1, date2): d0 = date(*date1) d1 = date(*date2) delta = d0 - d1 print abs(delta.days) return abs(delta.days) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3 assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238 assert days_diff((2014, 8, 27), (2014, 1, 1)) == 238
04f19b0fc1f0ff0008fcb5aa830237b104c83a45
yonatanGal/Four-In-a-Row
/ex12/board.py
3,018
4.03125
4
from .disc import Disc BOARD_HEIGHT = 6 BOARD_WIDTH = 7 EMPTY = '_' BLUE = 'blue' RED = 'red' PLAYER_ONE = '1' PLAYER_TWO = '2' class Board: """ creates a board object """ def __init__(self): self.__board = [['_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_'], ['_', '_', '_', '_', '_', '_', '_']] self.__discs = [] def get_board(self): """ returns thhe current state of the board """ return self.__board def get_player_at(self, row, col): """ returns the player at the (row, col) coordinate """ if self.__board[row][col] == BLUE: return PLAYER_ONE elif self.__board[row][col] == RED: return PLAYER_TWO else: return None def get_discs_list(self): """ returns the discs list """ return self.__discs def update_discs_list(self, disc): """ adds a disc to the discs list """ self.__discs.append(disc) def update_board(self, x_location, y_location, color): self.__board[x_location][y_location] = color def __str__(self): """ This function is called when a board object is to be printed. :return: A string of the current status of the board """ board_str = '' for row in range(BOARD_HEIGHT): row_str = '' for col in range(BOARD_WIDTH): row_str += self.__board[row][col] + " " board_str += row_str + "\n" return board_str def add_disc(self, disc, column): """ adds a disc to the board """ if self.is_legal(column): x, y = self.is_legal(column) disc.set_location((x,y)) self.update_board(x, y, disc.get_color()) self.update_discs_list(disc) return True else: return None def possible_moves(self): """ returns a list of all possible moves """ possible_moves_list=[] for col in range(BOARD_WIDTH): if self.is_legal(col): possible_moves_list.append(self.is_legal(col)) return possible_moves_list def is_legal(self, column): """ checks if it's legal to insert a disc to in a given column. """ row = None if column not in range(BOARD_WIDTH): return False for i in range(BOARD_HEIGHT-1,-1,-1): if self.__board[i][column] == EMPTY: row = i break if row is None: return False else: return (row,column) def cell_content(self, coordinate): """ return the disc a given location """ x_location,y_location = coordinate return self.__board[x_location][y_location]
9e956269ff70341a7f1d73a8481b482c329d53d6
emilywitt/HW05
/HW05_ex00_TextAdventure.py
3,314
4.3125
4
#!/usr/bin/env python # HW05_ex00_TextAdventure.py ############################################################################## # Imports from sys import exit from sys import argv # Body def infinite_stairway_room(count,name): print name + " walks through the door to see a dimly lit hallway." print "At the end of the hallway is a" + (count * 'long ') + 'staircase going towards some light. What does ' + name + " do?" next = raw_input("> ") # infinite stairs option if next == "take stairs": print name + ' takes the stairs' if (count > 0): print "but " + name + " is not happy about it" infinite_stairway_room(count + 1, name) # option 2 == ????? if next == "turn around": print name + " goes back to the gold room." gold_room(name) def gold_room(name): print "This room is full of gold. How much does " + name + " take?" while True: how_much = raw_input("> ") try: how_much == int(how_much) if int(how_much) > 50: print name + " is greedy. after taking the gold, " infinite_stairway_room(int(how_much),name) elif int(how_much) <= 50: print "You have a heart of gold! Since you're not greedy, you win!" pass except: print "Come on, " + name + ", type a number." exit(0) def bear_room(name): print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How is " + name + " going to move the bear?" bear_moved = False while True: next = raw_input("> ") if next == "take honey" or next == "take" or next == "honey": dead("The bear looks at " + name + " then slaps " + name + "'s face off.") elif next == "taunt" and not bear_moved: print "The bear has moved from the door. " + name + " can go through it now." bear_moved = True elif next == "taunt" and bear_moved: dead("The bear gets pissed off and chews " + name + "'s leg off.") elif (next == "open" or next == "door") and bear_moved: gold_room(name) else: print "I got no idea what that means." def cthulhu_room(name): print "Here " + name + " sees the great evil Cthulhu." print "He, it, whatever stares at " + name + " and " + name + " goes insane." print "Does " + name + " flee for his/her life or eat his/her own head?" next = raw_input("> ") if "flee" in next: main() elif "head" in next: dead("Well that was tasty!") else: cthulhu_room() def dead(why): print why, "Dead!" exit(0) ############################################################################## def main(): # START the TextAdventure game name = argv[1] print name + " is in a dark room." print "There is a door to " + name + "'s right and left." print "Which one does " + name + " take?" next = raw_input("> ") if next == "left": bear_room(name) elif next == "right": cthulhu_room(name) else: dead(name + " stumbles around the room and then starves.") if __name__ == '__main__': main()