blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2ae591ad210d4fcd3748a406f0a5855d7ffd7f59
MarioGN/web-scraping-estudos
/live_20_selenium/google.py
877
3.671875
4
""" Exemplo de PO no google.com """ from selenium import webdriver class Google: def __init__(self, driver): self.driver = driver self.url = 'http://google.com.br' self.search_bar = 'q' self.btn_search = 'btnK' self.btn_lucky = 'btnI' def navigate(self): self.driver.get(self.url) def search(self, word='None'): self.driver.find_element_by_name( self.search_bar).send_keys(word) self.driver.find_element_by_name( self.btn_search).click() def lucky(self, word='None'): self.driver.find_element_by_name( self.search_bar).send_keys(word) self.driver.find_element_by_name( self.btn_lucky).click() ch = webdriver.Chrome() g = Google(ch) g.navigate() g.lucky('live de python') # fechar navegador # ch.quit()
42f1e79d6b99b5466d1521daf013afe3d2464655
thebatcn/python-study
/pandas/pandas_DataFrame.py
3,208
3.875
4
import pandas as pd data = { "state": ["Ohio", "Ohio", "Ohio", "Nevada", "Nevada", "Nevada"], "year": [2000, 2001, 2002, 2001, 2002, 2003], "pop": [1.5, 1.7, 3.6, 2.4, 2.9, 3.2], } frame = pd.DataFrame(data) print(pd.DataFrame(data, columns=["year", "state", "pop"])) # 如果指定了列序列,则DataFrame的列就会按照指定顺序进行排列 frame2 = pd.DataFrame( data, columns=["year", "state", "pop", "debt"], index=(["one", "two", "three", "four", "five", "six"]), ) # 重新设置索引 print(frame2) # 如果传入的列在数据中找不到,就会在结果中产生缺失值 # print(frame2.columns) #列名称 # print(frame2.index ) #索引 # print(frame2['pop']) #通过类似字典标记的方式或属性的方式,可以将DataFrame的列获取为一个Series # # print(frame2.loc['six']) #行也可以通过位置或名称的方式进行获取,比如用loc属性 # 列可以通过赋值的方式进行修改 frame2["debt"] = 15.5 # print(frame2) # 将列表或数组赋值给某个列时,其长度必须跟DataFrame的长度相匹配。如果赋值的是一个Series,就会精确匹配DataFrame的索引,所有的空位都将被填上缺失值 val = pd.Series([-1.2, -1.5, -1.7], index=["two", "four", "five"]) frame2["debt"] = val # print(frame2) # 为不存在的列赋值会创建出一个新列。关键字del用于删除列 frame2["eastern"] = frame2["state"] == "Ohio" # print(frame2) del frame2["eastern"] print(frame2) #如果嵌套字典传给DataFrame,pandas就会被解释为:外层字典的键作为列,内层键则作为行索引 pop = {'Nevada':{2001:2.4,2002:2.9},'Ohio:':{2000:1.5,2001:1.7,2002:3.6}} frame3 = pd.DataFrame(pop) print('\n',frame3) # print(frame3.T) #你也可以使用类似NumPy数组的方法,对DataFrame进行转置(交换行和列) #内层字典的键会被合并、排序以形成最终的索引。如果明确指定了索引,则不会这样 #合并,排序提现在哪里? # print(pd.DataFrame(pop,index=[2001,2002,2003])) # print(pop) # pdata = {'Ohio':frame3['Ohio'][:-1], #取列数据0至-1,到倒数第二个 # 'Nevada':frame3['Nevada'][:2]} #取1和2两个数 # print(pdata) # frame3.index.name='year';frame3.columns.name='state' # print(frame3) # 如果设置了DataFrame的index和columns的name属性,则这些信息也会被显示出来 # # obj = pd.Series(range(3),index=['a','b','c']) # index = obj.index # print(type(index)) # # index[1]='d' #index对象元素不能修改?对象可以整体赋值? # index = ['x','y','z'] #变成了 list,其他类型了。 # print(type(index)) # obj = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c']) print(obj) obj2 = obj.reindex(['a','b','c','d','e']) #用该Series的reindex将会根据新索引进行重排。如果某个索引值当前不存在,就引入缺失值 print(obj2) obj3 = pd.Series(['blue', 'purple', 'yellow'], index=[0, 2, 4]) print(obj3) obj3 = obj3.reindex(range(6),method="ffill") #重新索引时可能需要做一些插值处理。method选项即可达到此目的,例如,使用ffill可以实现前向值填充 print(obj3)
967c018b9a496484cba2547c89666118074091e4
m-lobocki/Python-ExercisesSamples
/ex49.py
169
3.765625
4
# Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). result = list(map(lambda x: x * x, range(1,21)))
e61728f6155eb36d4294d0a54e1cd0342fd746c4
uday3445/python-al-and-ds
/nivice gcd.py
378
3.921875
4
def gcd(m,n): """ gcd of all two numbers :param m: :param n: :return: """ cf=[] for i in range (1,min(m,n)+1): if (m%i)==0 and (n%i)==0: cf.append(i) return( cf[-1]) num1 = int(input("The first number is ")) num2 = int(input("The second number is ")) print('the gcd of ', num1, 'and ', num2, 'is ', gcd(num1, num2))
b4c085111617c3ff74ded41f1c47cc2caaa6d379
Ellipse404/100-Exercises-Python-Programming-
/100+ Exercises Solved/Question - 6.py
766
3.90625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 16 17:28:16 2019 @author: BHASKAR NEOGI """ # Level - 2 import math as m c = 50 h = 30 d = input("Enter The Comma ',' Seperated Numbers : ").split(",") print("Here We Go With Your Number List",d) print(''' ''') r = [] # for listing the round values. e = [] # for listing the exact values. for i in d : i = float(i) w = m.sqrt((2*c*i)/h) print("Exact Square Root of ",i,"is : ",w," ; Round At : ",round(w)) e.append(str(w)) r.append(str(round(w))) # U may not Typecast it to string. print(''' ''',"List of Exact Values : ",e,''' ''') print(" List of Round Values : ",r)
2e5132a3647f8081b28750e8b201805ae7a81df3
pgurazada/ml-projects
/wells-africa/2018-05-28_assemble.py
3,328
3.578125
4
# coding: utf-8 # In this workbook we assemble the required features of the data set as per the observations from the exploratory data analysis. # In[37]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('ticks') get_ipython().magic('matplotlib inline') # In[4]: wells_features = pd.read_csv('data/well_features.csv') wells_labels = pd.read_csv('data/well_labels.csv') # In[5]: wells_features.info() # In[6]: wells_labels.info() # In[8]: wells_labels.status_group.value_counts() # ### Encoding the labels # # Encoding the labels into numeric values is simple since there are only three categories. Using a dictionary in such cases makes the intent also explicit # In[10]: status_group_to_numeric = {'functional needs repair' : 0, 'functional' : 1, 'non functional' : 2} # In[11]: wells_labels['status'] = wells_labels['status_group'].map(status_group_to_numeric) # In[12]: wells_labels.status.value_counts() # ### Encoding the features # In[16]: wells_features.shape # In[64]: gps_ht_bins = pd.qcut(wells_features.gps_height, 4, labels=range(4)) # In[65]: gps_ht_bins.value_counts() # In[69]: wells_features.construction_year.value_counts(ascending=True) # In[71]: def bin_construction_yr(c): if c >= 1960 and c < 1970: return 1 elif c >= 1971 and c < 1980: return 2 elif c >= 1981 and c < 1990: return 3 elif c >= 1991 and c < 2000: return 4 elif c >= 2001 and c < 2010: return 5 elif c >= 2011 and c < 2020: return 6 else: return 0 # In[75]: construct_yr_bins = wells_features.construction_year.apply(bin_construction_yr) # In[76]: construct_yr_bins.value_counts() # In[78]: wells_features.amount_tsh.describe() # In[79]: def is_tsh_zero(tsh): if tsh == 0: return 1 else: return 0 # In[84]: def take_log(tsh): if tsh == 0: return 0 else: return np.log(tsh) # In[86]: tsh_zero = wells_features.amount_tsh.apply(is_tsh_zero) # In[88]: def group_funded(funder): if funder == 'Government Of Tanzania': return 'Govt' elif funder == 'Danida': return 'F1' elif funder == 'Hesawa': return 'F2' elif funder == 'Rwssp': return 'F3' elif funder == 'World Bank': return 'F4' elif funder == 'Kkkt': return 'F5' elif funder == 'World Vision': return 'F6' elif funder == 'Unicef': return 'F7' elif funder == 'Tasaf': return 'F8' elif funder == 'District Council': return 'F9' else: return 'Oth' # In[89]: funded_by = wells_features.funder.apply(group_funded) # In[90]: funded_by.value_counts() # In[94]: wells_features.info() # In[93]: wells_features = wells_features.assign(gps_ht_bin = pd.qcut(wells_features.gps_height, 4, labels=range(4)), construct_yr_bin = wells_features.construction_year.apply(bin_construction_yr), tsh = wells_features.amount_tsh.apply(take_log), tsh_zero = wells_features.amount_tsh.apply(is_tsh_zero), funded_by = wells_features.funder.apply(group_funded))
da9c89fee8cfcf874ee1e8bedfcf3da45a83fd3f
arjunshah1993/Algorithms
/factrecursion.py
121
3.6875
4
n = 6 def factrec(n): if n == 1: return 1 elif n == 2: return 2 else: return n*factrec(n-1) print(factrec(n))
35a780b0870b9050346561ea796f671bdbcd721b
ekaraali/gaih-students-repo-example
/Homeworks/Day3_HW.py
1,174
4.40625
4
print(""" User login system.... """) #define username and password so that input provided by the users can be checked username = "edizkaraali" password = "123456" #define an entering right value to create safer system entering_right = 3 while True: username_from_user = input("Please enter your username: ") password_from_user = input("Please enter your password: ") if (username_from_user == username) and (password_from_user != password): print("Password is incorrect, please enter a correct password!!") entering_right -= 1 elif (username_from_user != username) and (password_from_user == password): print("Username is incorrect, please enter a correct username!!") entering_right -= 1 elif (username_from_user != username) and (password_from_user != password): print("Both username and password are incorrect, please enter a correct username and password!!") entering_right -= 1 else: print("Welcome to the system....") break #each time, check entering right if entering_right == 0: print("Your entering rights has been run off, please try again after 5 minutes...") break
67edf3cf50688ac4136fa0b6115bd536e26a0465
pcaenngtaeera/Information-Retrieval
/Inverted Index/compression.py
1,739
4.5
4
#!/usr/bin/env python from struct import pack, unpack def encode(integer): """ Encodes the Uses integer operations instead of bit shifts for efficiency. The integer "128" is equivalent to "1000 0000" and is used a mask. The algorithm focuses on adding byte-values to the <bytes> until the value can fit into a single byte. The last byte is given a "continuation bit" to let the decoder know it is the final byte. :param integer: an integer :return: a variable-byte encoded integer """ bytes = [] while True: print(integer % 128) bytes.insert(0, integer % 128) # adds the byte-value to the front of the list if integer < 128: # we have already the final byte break integer = integer // 128 # next byte bytes[-1] += 128 # add a "continuation bit" to the front of a byte return pack('%dB' % len(bytes), *bytes) def decode(filestream): """ Decodes an integer from a <filestream> by reading bytes until a "continuation bit" is encountered. Build an integer by iterating adding byte-values using the opposite operation of <encode>. The byte-values are unpacked one at a time until a "continuation" bit is reached. :param filestream: a filestream :return: an integer decoded from the filestream """ integer = 0 byte = unpack('B', filestream.read(1))[0] while True: if byte < 128: # byte is missing the "continuation bit" integer = 128 * integer + byte byte = unpack('B', filestream.read(1))[0] # read next byte else: # any byte-value over 128 will have the "continuation bit" integer = 128 * integer + (byte - 128) return integer
3fbe02f6284b59e5d97180a6d058bab16a511372
AninditaBasu/iPythonBluemixWatsonTone
/watson_get_tweets.py
3,489
3.703125
4
import json from twitter import TwitterStream, OAuth # # Authenticate yourself with Twitter # CONSUMER_KEY = raw_input('Enter the Twitter consumer key: ') CONSUMER_SECRET = raw_input('Enter the Twitter consumer key secret: ') ACCESS_TOKEN = raw_input('Enter the Twitter access token: ') ACCESS_SECRET = raw_input('Enter the Twitter access token secret: ') oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET) # # Pull some tweets # twitter_stream = TwitterStream(auth=oauth) iterator = twitter_stream.statuses.filter(follow="14677919") # # Dump the Twitter-returned data into a file for use later. Also, print the tweets to the console # i = 50 # # the number of tweets to read # a small number so that the code runs faster # tweets = open("./static/tweets.json", "w") # # write to the static folder so that the file persists # for tweet in iterator: tweet_raw = json.dumps(tweet) print >> tweets, tweet_raw # # write the entire tweet to a file, for use later # tweet_text = json.loads(tweet_raw.strip()) if 'text' in tweet_text: print tweet['text'].encode('utf-8') # # so that only the text of the tweet # is displayed on the console # no need to see everything # i -= 1 if i == 0: break tweets.close() # # Extract the contents of the text node of tweets, clean up, and write to a file for use later # # clean up the tweets to remove punctuations, hashtags, and other unwanted stuff # end_strip = [".", ",", "?", "/", "!", "*", ":", ")", "'", '"'] start_strip = [":", "*", "(", "'", '"'] words = [] # a list to contain all the words in all the tweets tweets_file = open('./static/tweets.json', 'r') for line in tweets_file: tweet = json.loads(line) #print tweet if 'text' in tweet: tweet_text = tweet['text'] #print tweet for word in tweet_text.split(): word = word.lower() if word == "rt": # do not add to list if word is "rt" break for item in end_strip: if word.endswith(item): word = word[:-1] for item in start_strip: if word.startswith(item): word = word[1:] words.append(word) tweets_file.close() prefix_list = ("http", "@", "t.co", "bit.ly") # do not reckon words that start with any of the strings in the prefix list for word in words[:]: if word.startswith(prefix_list): words.remove(word) text = "" for word in words: #print word text = text + " " + word #print text text = text.encode('utf-8') # write the text to a file, for later use textfile = open("./static/tweets_text.txt", "w") textfile.write(text) textfile.close() print "Done cleaning up tweets." # # Generate a word cloud image # Optional part of the code, hence commented out # #%matplotlib inline # for iPython notebook use # #f = open("./static/tweets_text.txt", "r") #text = f.read() # #from wordcloud import WordCloud #wordcloud = WordCloud().generate(text) # #import matplotlib.pyplot as plt #plt.imshow(wordcloud) #plt.axis("off") # #wordcloud = WordCloud(max_font_size=40, relative_scaling=.5).generate(text) # #plt.imshow(wordcloud) #plt.axis("off") #plt.show() # end of watson_get_tweets.py
b2546b464960eb71bc86723faabe1a04db6a1db1
desig53/Leetcode_Practice
/leetcode_pracitce/Replace_Elements_with_Greatest_Element_on_Right_Side.py
2,459
4.0625
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 7 16:03:38 2021 @author: asus """ ##Replace Elements with Greatest Element on Right Side ''' Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. After doing so, return the array. Example 1: Input: arr = [17,18,5,4,6,1] Output: [18,6,6,6,1,-1] Explanation: - index 0 --> the greatest element to the right of index 0 is index 1 (18). - index 1 --> the greatest element to the right of index 1 is index 4 (6). - index 2 --> the greatest element to the right of index 2 is index 4 (6). - index 3 --> the greatest element to the right of index 3 is index 4 (6). - index 4 --> the greatest element to the right of index 4 is index 5 (1). - index 5 --> there are no elements to the right of index 5, so we put -1. Example 2: Input: arr = [400] Output: [-1] Explanation: There are no elements to the right of index 0. Constraints: 1 <= arr.length <= 104 1 <= arr[i] <= 105 ''' def replaceElements(self, arr): ''' 邏輯 : 從最後一個元素開始跑,先預設最大元素(maximum)為最後一個元素 假設跑到的元素比最大元素小,則把這個值換成maximum 假設跑到的元素筆最大元素大,則把這個值換成原本maximum,並將maximum改為跑到的這個數 ''' """ :type arr: List[int] :rtype: List[int] """ great_pos = len(arr)-1 ##最大值的位置(預設最大元素(maximum)為最後一個元素) great_num = arr[great_pos] ##最大值 for i in range(great_pos,-1,-1): ##從最後一個元素開始跑 if i==great_pos:##如果是最一個元素,把這個元素指定為-1 arr[i]=-1 else: if arr[i]<great_num: #假設跑到的元素比最大元素小,則把這個值換成maximum arr[i]=great_num else: #假設跑到的元素筆最大元素大,則把這個值換成原本maximum,並將maximum改為跑到的這個數 temp = arr[i] arr[i]=great_num great_num=temp return arr
cc4ef7f5af73080449a6a28d8445fc619e42c56e
abhijitmamarde/py_notebook
/programs/dict_methods.py
2,090
4.25
4
# two ways for defn dict d = dict() print( type(d) ) d = {} print( type(d) ) # dict is key value pair d = {'name': 'abhijit', 'age': 24, 'is_student': False, 'salary': 24.5} # key could be anyone of an int, float, bool, string or tuple but NOT list # value could be any object/type in Python # ----- basic operations ------ print( len(d) ) # accessing items in a dict, using key print( d['name'] ) # changing data for a particular key d['name'] = "sachin" print( d['name'] ) # adding a key value pair print( d ) d['department'] = "IT" print( d ) # deleting a key value pair print( d['is_student'] ) del d['is_student'] # print( d['is_student'] ) # raises KeyError: 'is_student', as this key is no more available in dict # checking availibility of a key # check if a exists in dict or not if 'salary' in d: print("Salary exists: ", d['salary']) if 'is_student' in d: print("is_student exists: ", d['is_student']) else: print("is_student does not exists: ") # shortcut for doing same, get() method returns None if key is not found or return's the key's value # the second argument defines the default value which will return in case key is not found (default value is None) x = d.get('x', 0) # x = d.get('salary') print('x is:', x) # --------- other methods of dict ----------- # help(dict()) # clear(), copy() # same as that of list methods # keys(), values() and items() print("keys are:") print(list(d.keys())) for key in d.keys(): print(key, d[key]) print("values are:") print(list(d.values())) print("items are:") print(list(d.items())) for k, v in d.items(): print(k, v) # pop(), popitem() print(d) print( d.pop('salary') ) print(d) # print( d.pop('salary') ) # raises KeyError print( d.pop('salary', 0) ) print(d) print(d.popitem()) print(d.popitem()) print(d.popitem()) # print(d.popitem()) # KeyError: 'popitem(): dictionary is empty' # update() d1 = {'a': 1, 'b': 2} d2 = {'a1': 11, 'b1': 12} d3 = {} # similar to operation d3 = d1 + d2 # but '+' operator does not work for dict object d3.update(d1) d3.update(d2) print(d3)
a2c7a2e172e9f09f8a9152e80f1d5d4b381dc182
ritualnet/Euler
/Euler1.py
2,227
3.921875
4
def euler1(a, b, value): # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. sumval = 0 for x in range(1, value): if (x % a == 0) or (x % b == 0): sumval += x return sumval def euler2(limit): # Each new term in the Fibonacci sequence is generated by adding the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, # find the sum of the even-valued terms. num1 = sumr = num2 = 0 while num2 <= limit: if num1 == 0: num2 = 1 num3 = num2 + num1 num1 = num2 num2 = num3 if num2 % 2 == 0: sumr += num2 return sumr def prime(number): # return a list of prime numbers up to the number sent in via parameter primelist = list() for x in range(2, number+1): cntr = 0 for y in range(2, x+1): if x == y: if cntr == 0: primelist.append(x) break elif x % y == 0: cntr += 1 continue return primelist def prime2(number): cntr = 0 for y in range(number, 2, -1): if number % y == 0 and number != y: cntr += 1 if cntr == 0: return True else: return False def euler3(test): # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? # work backwards. All we need is the first prime number we hit, that is a factor of the number. #print("test", test, "test//2", test//2) for x in range(test, 2, -1): #print(x) if test % x == 0: #print("Check Prime2 for", x) if prime2(x): return x else: continue # # print("Euler 1 Result = ", euler1(3, 5, 1000)) # print("Euler 2 Result = ", euler2(4000000)) print("Euler 3 Result = ", euler3(600851475143))
620b481dd29f76a04b85299194e085eedde93726
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/41_10.py
2,531
4.03125
4
Python – Check if List is K increasing Given a List, check if next element is always x + K than current(x). > **Input** : test_list = [3, 7, 11, 15, 19, 23], K = 4 > **Output** : True > **Explanation** : Subsequent element difference is 4. > > **Input** : test_list = [3, 7, 11, 12, 19, 23], K = 4 > **Output** : False > **Explanation** : 12 – 11 = 1, which is not 4, hence False **Method #1 : Using loop** In this, we iterate for each element of list, and check if element is not K increasing, if found, the result is flagged false and returned. ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Check if List is K increasing # Using loop # initializing list test_list = [4, 7, 10, 13, 16, 19] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 3 res = True for idx in range(len(test_list) - 1): # flagging if not found if test_list[idx + 1] != test_list[idx] + K: res = False # printing results print("Is list K increasing ? : " + str(res)) --- __ __ **Output** The original list is : [4, 7, 10, 13, 16, 19] Is list K increasing ? : True **Method #2 : Using all() + generator expression** In this, we check for all the elements being K increasing using all(), and generator expression is used for iteration. ## Python3 __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Check if List is K increasing # Using all() + generator expression # initializing list test_list = [4, 7, 10, 13, 16, 19] # printing original list print("The original list is : " + str(test_list)) # initializing K K = 3 # using all() to check for all elements res = all(test_list[idx + 1] == test_list[idx] + K for idx in range(len(test_list) - 1)) # printing results print("Is list K increasing ? : " + str(res)) --- __ __ **Output** The original list is : [4, 7, 10, 13, 16, 19] Is list K increasing ? : True Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
81b06a40d05788c799a7735eff01a692f4f19532
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/097d732334c14eceb0b7047bda198ad1.py
808
4.15625
4
# Dirk Herrmann's solution version 2 for exercism exercise "Word Count" # This file implements class Phrase: # # * A Phrase object is constructed from a string. # # * The method word_count returns a dictionary (a Counter, actually). Keys # are strings holding the words from the phrase, values are integer values # indicating how many times the word occured in the phrase. Words are # substrings matched by the "\w+" regexp, turned to lower case. # Example: "!foo bAr$1 Bar" results in {'1': 1, 'foo': 1, 'bar': 2} import re from collections import Counter class Phrase(object): def __init__(self, input_string): self._phrase_string = input_string def word_count(self): normalized = self._phrase_string.lower() words = re.findall("\w+", normalized) return Counter(words)
e353bda883873ec0c429cc0851e24d3e3dc06cc1
unsilence/Python-function
/Python基础/按照列表某一列的元素大小进行排序.py
269
3.609375
4
''' 利用set自动去重 ''' if __name__ == '__main__': a = set() for _ in range(100): a.add(1) a.add(3) b = set() b.add(3) b.add(5) # 对两个集合取交集 print(b&a) # 对两个集合取并集 print(b|a)
5cbbb33e9ae32f0ca466ed12fa8780e432e0d697
100pawan/my_code_python
/while_loop.py
148
3.75
4
# i = 1 # while i<=10: # print("pawan") # i = i+1 i = input("enter your name ") n = 1 while n<=10: print(f"{i} {n}") n = n + 1
0a438cbe88865719ba8d266722df1a547f3b2ca9
vipulsingh24/DSA
/Problems/max_balloon.py
549
3.78125
4
def max_number_of_balloons(text): count = [0] * 26 for i in range(len(text)): count[ord(text[i]) - ord('a')] += 1 print("Count: ", count) balloon_count = count[1] # b balloon_count = min(balloon_count, count[0]) # a balloon_count = min(balloon_count, count[11] / 2) # l balloon_count = min(balloon_count, count[14] / 2) # o balloon_count = min(balloon_count, count[13]) # n return balloon_count if __name__ == "__main__": str_ = "loonxbaloballpooonn" print(max_number_of_balloons(str_))
8c68c725df8dfa25e2921703cc34adc4bc0cecd3
charlieb/python-presentations
/tips_tricks.py
4,339
3.828125
4
## C-like Looping list1 = [1,2,3,4,5,6] # Bad: result = False for i in range(len(list1)): if list1[i] == 1: result = True break # Better: result = False for val in list1: if val == 1: result = True break # Best: result = 1 in list1 # "in" checks for membership in a list # it can also be used for other iterables # Dict: dict1 = {"a":1, "b":2, "c":3} "a" in dict1 # >>> True # Tuple: tpl = (1,2,3,4,5) 3 in tpl # >>> True # What if you need the index? list1 = ['a', 'b', 'c'] for i, val in enumerate(list1): print i, val # >>> # 0 a # 1 b # 2 c ## Truth , Falsity and None # in C FALSE == 0 == NULL and everything else is TRUE # # In python False <> None <> True False == None # >>> False True == None # >>> False # The rules are the same as C but the values are different if False: print False # >>> (prints nothing) if None: print None # >>> (prints nothing) if True: print True # >>> True (duh) # good practices # Just as in C avoid comparison to True: val = True if val == True: print "naughty" if val: print "nice" # In python also avoid comparison to None: val = None if val == None: print "naughty" if val is None: print "nice" # Why "is"? # None is a singletyon and there is only ever one value for None # "==" tests for equality # "is" tests for identity (a pointer comparison if you like) [1] == [1] # >>> True [1] is [1] # >>> False # Practically there's not that much difference but # the key difference is that classes can redefine "==" # but they cannot redefine "is" # Advanced Example: class A: def __eq__(self, other): return True foo = A() foo == None # >>> True ## Strings and Concatenation # In python strings are concatenated with + "one " + "two" # >>> "one two" # Repeated Concatenation # Bad: cpd_lst = ["one", "two", "three", "four"] cpds = "" for cpd in cpd_lst: cpds += ", " + cpd # Better: ", ".join(cpd_lst) # >>> "one, two, three, four" " and ".join(cpd_lst) # >>> "one and two and three and four" ## Docstrings # docstrings are just a special comment that the user of the # function, class , module etc. can access at runtime # They're very useful for exploration of unfamiliar modules # Start a docstring wuth 3 quotes def docstring_test(): """Docstring testing function. """ return None print docstring_test.__doc__ # >>> # Docstring testing function. # the docstring for a class is the docstring for the __init__ method class DString: """DString class. Very useful""" print DString.__doc__ # >>> # DString class. # Very useful ## Assignment # multiple assignment is awesome a,b = 1,2 # example: swap two variables # Bad: tmp = a a = b b = tmp # Better a,b = b,a # Unpacking multiple assignment lst = [1,2,3] # Bad: a, b, c = lst[0], lst[1], lst[2] # Better: a,b,c = lst # (I told you it was awesome) # Destructuring multiple assignment: lst = [1,2,[3,4], 5] a,b,c,d = lst print "%s,%s,%s,%s"%(a,b,c,d) # >>> 1,2,[3,4],5 a,b,(c,d),e = lst print "%s,%s,%s,%s,%s"%(a,b,c,d,e) # >>> 1,2,3,4,5 # (Pretty cool eh?) # Destructuring multiple assignment from an iterator: a,b,c,d = range(4) print "%s,%s,%s,%s"%(a,b,c,d) # >>> 1,2,4,5 d,e,f = {"a":1, "b":2, "c":3} print "%s,%s,%s"%(d,e,f) # >>> a,b,c # (what is this sorcery?!) ## Filtering and Mapping Iterables (lists) # Bad: lst = [1,2,3,4] lst2 = [] for a in lst: lst2.append(a*2) print lst2 # >>> [2,4,6,8] # Also bad: lst2 = [] for a in lst: if a%2 == 0: lst2.append(a*2) print lst2 # >>> [4,8] # Better: # The syntax for this looks weird but it's quite nice once you get used to it lst = [1,2,3,4] [a*2 for a in lst] # >>> [2,4,6,8] #a*2 <-- mapping part, can use any python expression # for a in lst <-- iteration part, defines a for use in expression [a*2 for a in lst if a%2 == 0] # >>> [4,8] # if a%2 == 0 <-- filter part, a's that evaluate to True are kept # Just like "in" you can also use this syntax for other iterables # Dict: dict1 = {"a":1, "b":2, "c":3} {k+'z': v+1 for k,v in dict1.iteritems()} # >>> {'az': 2, 'cz': 4, 'bz': 3} # Tuple: tuple syntax is a little different as the tuple is # converted to a list by the comprehension and then back again by us tpl = (1,2,3,4,5) tuple([t + 1 for t in tpl]) # >>> (2,3,4,5,6)
9b030ea113d2d1ee6dae82b2d660cd08d5532cca
ColinTing/Algorithms
/147.insertionSortList.py
1,552
4.125
4
class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next list = ListNode(-1, ListNode(5, ListNode(3, ListNode( 4, ListNode(0))))) class Solution: def insertionSortList(self, head): if head is None or head.next is None: return head dummy = ListNode(0) dummy.next = head #pre = dummy #pre可省略 cur = head while cur is not None and cur.next is not None: if cur.val < cur.next.val: cur = cur.next else: temp = cur.next cur.next = temp.next pre = dummy #head = dummy.next #head可省略 while temp.val>pre.next.val: #head 替换成 pre 时可以只用一个pre 来实现排序,因为他是对pre.next进行操作 pre = pre.next #head 而用head操作时需要两个参数 并且在while循环中还需要 *pre = head* head = head.next temp.next = pre.next pre.next = temp return dummy.next def printListNode(self, listNode): answer = [] head = listNode while head is not None: #这里没有 head.next 的判断,那么上面的 cur 需要么? 需要,因为会比对cur和cur.next的值 answer.append(head.val) head = head.next return answer s = Solution() s.insertionSortList(list) print(s.printListNode(list))
eb9db6ae3608e8833bde7a33b65161f96e1be5f5
axxporras/PIA-de-Contabilidad
/presupuesto maestro.py
34,279
3.953125
4
respuesta = '' while respuesta != 12: print("\nPresupuesto Maestro *Ferretería Santa Lucía* \n") print("[1] Presupuesto de Ventas") print("[2] Determinar Saldo de Clientes y Flujo de Entradas") print("[3] Presupuesto de Producción") print("[4] Presupuesto de Requerimiento de Materiales") print("[5] Presupuesto de Compra de Materiales") print("[6] Determinación del saldo de Proveedores y Flujo de Salidas") print("[7] Presupuesto de Mano de Obra Directa") print("[8] Presupuesto de Gastos Indirectos de Fabricación") print("[9] Presupuesto de Gastos de Operación") print("[10] Determinación del Costo Unitario de Productos Terminados") print("[11] Valuación de Inventarios Finales") print("[12] Salir") respuesta = int(input("\n")) if respuesta== 1: print('[Presupuesto de Ventas]') print('\n~Primer semestre') print('\nProducto CL') unitCL1 = int(input('Unidades vendidas: ')) precioCL1 = int(input('Precio de venta: ')) print('\nProducto CE') unitCE1 = int(input('Unidades vendidas: ')) precioCE1 = int(input('Precio de venta: ')) print('\nProducto CR') unitCR1 = int(input('Unidades vendidas: ')) precioCR1 = int(input('Precio de venta: ')) print('\n~Segundo semestre') print('\nProducto CL') unitCL2 = int(input('Unidades vendidas: ')) precioCL2 = int(input('Precio de venta: ')) print('\nProducto CE') unitCE2 = int(input('Unidades vendidas: ')) precioCE2 = int(input('Precio de venta: ')) print('\nProducto CR') unitCR2 = int(input('Unidades vendidas: ')) precioCR2 = int(input('Precio de venta: ')) importecl1= unitCL1*precioCL1 importecl2= unitCL2*precioCL2 importecltotal= importecl1+importecl2 importece1= unitCE1*precioCE1 importece2= unitCE2*precioCE2 importecetotal= importece1+importece2 importecr1= unitCR1*precioCR1 importecr2= unitCR2*precioCR2 importecrtotal= importecr1+importecr2 totalporsemestre1= importecl1+importece1+importecr1 totalporsemestre2= importecl2+importece2+importecr2 totalanual= importecltotal+importecetotal+importecrtotal print('\nImporte de Venta (Producto CL)') print(f'Primer semestre: {importecl1}') print(f'Segundo semestre: {importecl2}') print(f'Importe anual: {importecltotal}') print('\nImporte de Venta (Producto CE)') print(f'Primer semestre: {importece1}') print(f'Segundo semestre: {importece2}') print(f'Importe anual: {importecetotal}') print('\nImporte de Venta (Producto CR)') print(f'Primer semestre: {importecr1}') print(f'Segundo semestre: {importecr2}') print(f'Importe anual: {importecrtotal}') print('\nTotal de Ventas por Semestre') print(f'Primer semestre: {totalporsemestre1}') print(f'Segundo semestre: {totalporsemestre2}') print(f'Importe anual: {totalanual}') print('\nDevuelta al menu') elif respuesta== 2: print('[Determinar Saldo de Clientes y Flujo de Entradas]') clientes= int(input('Saldo de clientes [2020]: ')) ventas= int(input('Ventas [2021]: ')) totalclientes= clientes+ventas print(f'Total de Clientes 2021: {totalclientes}') cobranza= ventas*0.8 entradas= cobranza+clientes print('\n~Entradas por efectivo') print(f'Por Cobranza del 2020: {clientes}') print(f'Por Cobranza del 2021: {cobranza}') print(f'Total de entradas 2021: {entradas}') saldo= totalclientes+entradas print(f'\nSaldo de clientes del 2021: {saldo}') print('\nDevuelta al menu') elif respuesta== 3: print("[Presupuesto de Producción]") print("[1] CL") print("[2] CE") print("[3] CR") producto= int(input('\n')) if producto== 1: print('[Producto CL]') print('~Primer Semestre \n') unidades1= int(input('Unidades a vender: ')) invfinal1= int(input('Inventario final: ')) totalunit1= unidades1+invfinal1 print(f'Total de unidades: {totalunit1}') print(f'Inventorio inicial {invfinal1}') producir1= totalunit1-invfinal1 print(f'Unidades a Producir: {producir1}') print('\n~Segundo Semestre \n') unidades2= int(input('Unidades a vender: ')) invfinal2= int(input('Inventario final: ')) totalunit2= unidades2+invfinal2 print(f'Total de unidades: {totalunit2}') print(f'Inventario inicial: {invfinal1}') producir2= totalunit2-invfinal1 print(f'Unidades a Producir: {producir2}') print('\n~Total Anual \n') unidades3= unidades1+unidades2 totalunit3= unidades3+invfinal2 producir3= producir1+producir2 print(f'Unidades a vender: {unidades3}') print(f'Inventario final: {invfinal2}') print(f'Total de unidades: {totalunit3}') print(f'Inventario inicial: {invfinal1}') print(f'Unidades a Producir: {producir3}') print('\nDevuelta al menu') elif producto== 2: print('[Producto CE]') print('~Primer Semestre \n') unidades1= int(input('Unidades a vender: ')) invfinal1= int(input('Inventario final: ')) totalunit1= unidades1+invfinal1 print(f'Total de unidades: {totalunit1}') print(f'Inventorio inicial {invfinal1}') producir1= totalunit1-invfinal1 print(f'Unidades a Producir: {producir1}') print('\n~Segundo Semestre \n') unidades2= int(input('Unidades a vender: ')) invfinal2= int(input('Inventario final: ')) totalunit2= unidades2+invfinal2 print(f'Total de unidades: {totalunit2}') print(f'Inventario inicial: {invfinal1}') producir2= totalunit2-invfinal1 print(f'Unidades a Producir: {producir2}') print('\n~Total Anual \n') unidades3= unidades1+unidades2 totalunit3= unidades3+invfinal2 producir3= producir1+producir2 print(f'Unidades a vender: {unidades3}') print(f'Inventario final: {invfinal2}') print(f'Total de unidades: {totalunit3}') print(f'Inventario inicial: {invfinal1}') print(f'Unidades a Producir: {producir3}') print('\nDevuelta al menu') elif producto== 3: print('[Producto CR]') print('~Primer Semestre \n') unidades1= int(input('Unidades a vender: ')) invfinal1= int(input('Inventario final: ')) totalunit1= unidades1+invfinal1 print(f'Total de unidades: {totalunit1}') print(f'Inventorio inicial {invfinal1}') producir1= totalunit1-invfinal1 print(f'Unidades a Producir: {producir1}') print('\n~Segundo Semestre \n') unidades2= int(input('Unidades a vender: ')) invfinal2= int(input('Inventario final: ')) totalunit2= unidades2+invfinal2 print(f'Total de unidades: {totalunit2}') print(f'Inventario inicial: {invfinal1}') producir2= totalunit2-invfinal1 print(f'Unidades a Producir: {producir2}') print('\n~Total Anual \n') unidades3= unidades1+unidades2 totalunit3= unidades3+invfinal2 producir3= producir1+producir2 print(f'Unidades a vender: {unidades3}') print(f'Inventario final: {invfinal2}') print(f'Total de unidades: {totalunit3}') print(f'Inventario inicial: {invfinal1}') print(f'Unidades a Producir: {producir3}') print('\nDevuelta al menu') else: print('\nDevuelta al menu') elif respuesta== 4: print('[Presupuesto de Requerimiento de Materiales]') print('\n~Producto CL') unidadescl1= int(input('Unidades a producir (Primer Semestre): ')) unidadescl2= int(input('Unidades a producir (Segundo Semestre): ')) unidadescl3= unidadescl1+unidadescl2 print(f'Unidades a producir (Total): {unidadescl3}') print('\nMaterial A') materialcla= float(input('Requerimiento de material: ')) totalacl1= unidadescl1*materialcla totalacl2= unidadescl2*materialcla totalacl3= totalacl1+totalacl2 print(f'Total de Material A requerido: {totalacl1}, {totalacl2}, {totalacl3}') print('\nMaterial B') materialclb= float(input('Requerimiento de material: ')) totalbcl1= unidadescl1*materialclb totalbcl2= unidadescl2*materialclb totalbcl3= totalbcl1+totalbcl2 print(f'Total de Material B requerido: {totalbcl1}, {totalbcl2}, {totalbcl3}') print('\nMaterial C') materialclc= float(input('Requerimiento de material: ')) totalccl1= unidadescl1*materialclc totalccl2= unidadescl2*materialclc totalccl3= totalccl1+totalccl2 print(f'Total de Material C requerido: {totalccl1}, {totalccl2}, {totalccl3}') print('\n\n~Producto CE') unidadesce1= int(input('Unidades a producir (Primer Semestre): ')) unidadesce2= int(input('Unidades a producir (Segundo Semestre): ')) unidadesce3= unidadesce1+unidadesce2 print(f'Unidades a producir (Total): {unidadesce3}') print('\nMaterial A') materialcea= float(input('Requerimiento de material: ')) totalace1= unidadesce1*materialcea totalace2= unidadesce2*materialcea totalace3= totalace1+totalace2 print(f'Total de Material A requerido: {totalace1}, {totalace2}, {totalace3}') print('\nMaterial B') materialceb= float(input('Requerimiento de material: ')) totalbce1= unidadesce1*materialceb totalbce2= unidadesce2*materialceb totalbce3= totalbce1+totalbce2 print(f'Total de Material B requerido: {totalbce1}, {totalbce2}, {totalbce3}') print('\nMaterial C') materialcec= float(input('Requerimiento de material: ')) totalcce1= unidadesce1*materialcec totalcce2= unidadesce2*materialcec totalcce3= totalcce1+totalcce2 print(f'Total de Material C requerido: {totalcce1}, {totalcce2}, {totalcce3}') print('\n\n~Producto CR') unidadescr1= int(input('Unidades a producir (Primer Semestre): ')) unidadescr2= int(input('Unidades a producir (Segundo Semestre): ')) unidadescr3= unidadescr1+unidadescr2 print(f'Unidades a producir (Total): {unidadescr3}') print('\nMaterial A') materialcra= float(input('Requerimiento de material: ')) totalacr1= unidadescr1*materialcra totalacr2= unidadescr2*materialcra totalacr3= totalacr1+totalacr2 print(f'Total de Material A requerido: {totalacr1}, {totalacr2}, {totalacr3}') print('\nMaterial B') materialcrb= float(input('Requerimiento de material: ')) totalbcr1= unidadescr1*materialcrb totalbcr2= unidadescr2*materialcrb totalbcr3= totalbcr1+totalbcr2 print(f'Total de Material B requerido: {totalbcr1}, {totalbcr2}, {totalbcr3}') print('\nMaterial C') materialcrc= float(input('Requerimiento de material: ')) totalccr1= unidadescr1*materialcrc totalccr2= unidadescr2*materialcrc totalccr3= totalccr1+totalccr2 print(f'Total de Material C requerido: {totalccr1}, {totalccr2}, {totalccr3}') print('\n\nTotal de Requerimientos') totaldea1= totalacl1+totalace1+totalacr1 totaldea2= totalacl2+totalace2+totalacr2 totaldea3= totalacl3+totalace3+totalacr3 totaldeb1= totalbcl1+totalbce1+totalbcr1 totaldeb2= totalbcl2+totalbce2+totalbcr2 totaldeb3= totalbcl3+totalbce3+totalbcr3 totaldec1= totalccl1+totalcce1+totalccr1 totaldec2= totalccl2+totalcce2+totalccr2 totaldec3= totalccl3+totalcce3+totalccr3 print(f'Material A Metros: {totaldea1}, {totaldea2}, {totaldea3}') print(f'Material B Metros: {totaldeb1}, {totaldeb2}, {totaldeb3}') print(f'Material C Metros: {totaldec1}, {totaldec2}, {totaldec3}') print('\nDevuelta al menu') elif respuesta== 5: print('[Presupuesto de Compra de Materiales]') print('\n~Material A') materiala1= int(input('Requerimiento de Materiales (Primer semestre): ')) invfinala1= int(input('Inventario Final: ')) totalmaterialesa1= materiala1+invfinala1 print(f'Total de materiales: {totalmaterialesa1}') print(f'Inventario inicial: {invfinala1}') materialcomprara1= totalmaterialesa1-invfinala1 print(f'Material a comprar: {materialcomprara1}') precioa1= int(input('Precio de compra: ')) totala1= materialcomprara1*precioa1 print(f'Total de Materia A en $ (Primer semestre): {totala1}') materiala2= int(input('\nRequerimiento de Materiales (Segundo semestre): ')) invfinala2= int(input('Inventario Final: ')) totalmaterialesa2= materiala2+invfinala2 print(f'Total de materiales: {totalmaterialesa2}') print(f'Inventario inicial: {invfinala1}') materialcomprara2= totalmaterialesa2-invfinala1 print(f'Material a comprar: {materialcomprara2}') precioa2= int(input('Precio de compra: ')) totala2= materialcomprara2*precioa2 print(f'Total de Materia A en $ (Segundo semestre): {totala2}') materiala3= materiala1+materiala2 totalmaterialesa3= materiala3+invfinala2 materialcomprara3= materialcomprara1+materialcomprara2 totala3= totala1+totala2 print(f'\nRequerimiento de Materiales (Total): {materiala3}') print(f'Inventario Final: {invfinala2}') print(f'Total de materiales: {totalmaterialesa3}') print(f'Inventario inicial: {invfinala1}') print(f'Material a comprar: {materialcomprara3}') print(f'Total de Material A en $ (Total): {totala3}') print('\n\n~Material B') materialb1= int(input('Requerimiento de Materiales (Primer semestre): ')) invfinalb1= int(input('Inventario Final: ')) totalmaterialesb1= materialb1+invfinalb1 print(f'Total de materiales: {totalmaterialesb1}') print(f'Inventario inicial: {invfinalb1}') materialcomprarb1= totalmaterialesb1-invfinalb1 print(f'Material a comprar: {materialcomprarb1}') preciob1= int(input('Precio de compra: ')) totalb1= materialcomprarb1*preciob1 print(f'Total de Materia B en $ (Primer semestre): {totalb1}') materialb2= int(input('\nRequerimiento de Materiales (Segundo semestre): ')) invfinalb2= int(input('Inventario Final: ')) totalmaterialesb2= materialb2+invfinalb2 print(f'Total de materiales: {totalmaterialesb2}') print(f'Inventario inicial: {invfinalb1}') materialcomprarb2= totalmaterialesb2-invfinalb1 print(f'Material a comprar: {materialcomprarb2}') preciob2= int(input('Precio de compra: ')) totalb2= materialcomprarb2*preciob2 print(f'Total de Materia B en $ (Segundo semestre): {totalb2}') materialb3= materialb1+materialb2 totalmaterialesb3= materialb3+invfinalb2 materialcomprarb3= materialcomprarb1+materialcomprarb2 totalb3= totalb1+totalb2 print(f'\nRequerimiento de Materiales (Total): {materialb3}') print(f'Inventario Final: {invfinalb2}') print(f'Total de materiales: {totalmaterialesb3}') print(f'Inventario inicial: {invfinalb1}') print(f'Material a comprar: {materialcomprarb3}') print(f'Total de Material B en $ (Total): {totalb3}') print('\n\n~Material C') materialc1= int(input('Requerimiento de Materiales (Primer semestre): ')) invfinalc1= int(input('Inventario Final: ')) totalmaterialesc1= materialc1+invfinalc1 print(f'Total de materiales: {totalmaterialesc1}') print(f'Inventario inicial: {invfinalc1}') materialcomprarc1= totalmaterialesc1-invfinalc1 print(f'Material a comprar: {materialcomprarc1}') precioc1= int(input('Precio de compra: ')) totalc1= materialcomprarc1*precioc1 print(f'Total de Materia C en $ (Primer semestre): {totalc1}') materialc2= int(input('\nRequerimiento de Materiales (Segundo semestre): ')) invfinalc2= int(input('Inventario Final: ')) totalmaterialesc2= materialc2+invfinalc2 print(f'Total de materiales: {totalmaterialesc2}') print(f'Inventario inicial: {invfinalc1}') materialcomprarc2= totalmaterialesc2-invfinalc1 print(f'Material a comprar: {materialcomprarc2}') precioc2= int(input('Precio de compra: ')) totalc2= materialcomprarc2*precioc2 print(f'Total de Materia C en $ (Segundo semestre): {totalc2}') materialc3= materialc1+materialc2 totalmaterialesc3= materialc3+invfinalc2 materialcomprarc3= materialcomprarc1+materialcomprarc2 totalc3= totalc1+totalc2 print(f'\nRequerimiento de Materiales (Total): {materialc3}') print(f'Inventario Final: {invfinalc2}') print(f'Total de materiales: {totalmaterialesc3}') print(f'Inventario inicial: {invfinalc1}') print(f'Material a comprar: {materialcomprarc3}') print(f'Total de Material C en $ (Total): {totalc3}') semestre1= totala1+totalb1+totalc1 semestre2= totala2+totalb2+totalc2 total= totala3+totalb3+totalc3 print(f'\n\nCompras totales: {semestre1}, {semestre2}, {total}') print('\nDevuelta al menu') elif respuesta== 6: print('[Determinación del saldo de Proveedores y Flujo de Salidas]') proveedores= int(input('Saldo de Proveedores [2020]: ')) ventas= int(input('Compras [2021]: ')) totalproveedores= proveedores+ventas print(f'Total de Proveedores 2021: {totalproveedores}') cobranza= ventas*0.5 salidas= cobranza+proveedores print('\n~Salidas de Efectivo') print(f'Por Proveedores del 2020: {proveedores}') print(f'Por Proveedores del 2021: {cobranza}') print(f'Total de Salidas 2021: {salidas}') saldo= totalproveedores - salidas print(f'\nSaldo de Proveedores del 2021: {saldo}') print('\nDevuelta al menu') elif respuesta== 7: print('[Presupuesto de Mano de Obra Directa]') print('\n~Producto CL') unidadesa1= int(input('Unidades a Producir (Primer semestre): ')) horasa1= float(input('Horas requeridas por unidad: ')) totalhorasa1= unidadesa1*horasa1 print(f'Total de horas requeridas: {totalhorasa1}') cuotaa1= float(input('Cuota por hora: ')) importea1= totalhorasa1*cuotaa1 print(f'Importe de M.O.D. (Primer semestre): {importea1}') unidadesa2= int(input('\nUnidades a Producir (Segundo semestre): ')) print(f'Horas requeridas por unidad: {horasa1}') totalhorasa2= unidadesa2*horasa1 print(f'Total de horas requeridas: {totalhorasa2}') cuotaa2= float(input('Cuota por hora: ')) importea2= totalhorasa2*cuotaa2 print(f'Importe de M.O.D. (Primer semestre): {importea2}') unidadesa3= unidadesa1+unidadesa2 totalhorasa3= totalhorasa1+totalhorasa2 importea3= importea1+importea2 print(f'\nUnidades a Producir (Total): {unidadesa3}') print(f'Horas requeridas por unidad: {horasa1}') print(f'Total de horas requeridas: {totalhorasa3}') print(f'Importe de M.O.D. (Total): {importea3}') print('\n\n~Producto CE') unidadesb1= int(input('Unidades a Producir (Primer semestre): ')) horasb1= float(input('Horas requeridas por unidad: ')) totalhorasb1= unidadesb1*horasb1 print(f'Total de horas requeridas: {totalhorasb1}') cuotab1= float(input('Cuota por hora: ')) importeb1= totalhorasb1*cuotab1 print(f'Importe de M.O.D. (Primer semestre): {importeb1}') unidadesb2= int(input('\nUnidades a Producir (Segundo semestre): ')) print(f'Horas requeridas por unidad: {horasb1}') totalhorasb2= unidadesb2*horasb1 print(f'Total de horas requeridas: {totalhorasb2}') cuotab2= float(input('Cuota por hora: ')) importeb2= totalhorasb2*cuotab2 print(f'Importe de M.O.D. (Primer semestre): {importeb2}') unidadesb3= unidadesb1+unidadesb2 totalhorasb3= totalhorasb1+totalhorasb2 importeb3= importeb1+importeb2 print(f'\nUnidades a Producir (Total): {unidadesb3}') print(f'Horas requeridas por unidad: {horasb1}') print(f'Total de horas requeridas: {totalhorasb3}') print(f'Importe de M.O.D. (Total): {importeb3}') print('\n\n~Producto CR') unidadesc1= int(input('Unidades a Producir (Primer semestre): ')) horasc1= float(input('Horas requeridas por unidad: ')) totalhorasc1= unidadesc1*horasc1 print(f'Total de horas requeridas: {totalhorasc1}') cuotac1= float(input('Cuota por hora: ')) importec1= totalhorasc1*cuotac1 print(f'Importe de M.O.D. (Primer semestre): {importec1}') unidadesc2= int(input('\nUnidades a Producir (Segundo semestre): ')) print(f'Horas requeridas por unidad: {horasc1}') totalhorasc2= unidadesc2*horasc1 print(f'Total de horas requeridas: {totalhorasc2}') cuotac2= float(input('Cuota por hora: ')) importec2= totalhorasc2*cuotac2 print(f'Importe de M.O.D. (Primer semestre): {importec2}') unidadesc3= unidadesc1+unidadesc2 totalhorasc3= totalhorasc1+totalhorasc2 importec3= importec1+importec2 print(f'\nUnidades a Producir (Total): {unidadesc3}') print(f'Horas requeridas por unidad: {horasc1}') print(f'Total de horas requeridas: {totalhorasc3}') print(f'Importe de M.O.D. (Total): {importec3}') horasrequeridas1= totalhorasa1+totalhorasb1+totalhorasc1 horasrequeridas2= totalhorasa2+totalhorasb2+totalhorasc2 horasrequeridas3= totalhorasa3+totalhorasb3+totalhorasc3 importetotal1= importea1+importeb1+importec1 importetotal2= importea2+importeb2+importec2 importetotal3= importea3+importeb3+importec3 print(f'\n\nTotal de horas requeridas por semestre: {horasrequeridas1}, {horasrequeridas2}, {horasrequeridas3}') print('Total M.O.D. por semestre: {importetotal1}, {importetotal2}, {importetotal3}') print('\nDevuelta al menu') elif respuesta== 8: print('[Presupuesto de Gastos Indirectos de Fabricación]') print('\n~Primer Semestre') depreciacion1= int(input('Depreciación: ')) seguros= int(input('Seguros: ')) mantenimiento1= int(input('Mantenimiento: ')) energia1= int(input('Energeticos: ')) varios= int(input('Varios: ')) total1= depreciacion1+seguros+mantenimiento1+energia1+varios print(f'Total G.I.F. por semestre: {total1}') print('\n\n~Segundo Semestre') depreciacion2= int(input('\nDepreciación: ')) print(f'Seguros: {seguros}') mantenimiento2= int(input('Mantenimiento: ')) energia2= int(input('Energeticos: ')) print('Varios: {varios}') total2= depreciacion2+seguros+mantenimiento2+energia2+varios print(f'Total G.I.F. por semestre: {total2}') print('\n\n~Total Anual') depreciacion3= depreciacion1+depreciacion2 seguros3= seguros+seguros mantenimiento3= mantenimiento1+mantenimiento2 energia3= energia1+energia2 varios3= varios+varios total3= total1+total2 print(f'Depreciación: {depreciacion3}') print(f'Seguros: {seguros3}') print(f'Mantenimiento: {mantenimiento3}') print(f'Energeticos: {energia3}') print(f'Varios: {varios3}') print(f'Total G.I.F. por semestre: {total3}') print(f'\n\nTotal de G.I.F.: {total3}') horasmod= int(input('Total horas M.O.D. Anual: ')) horagif= total3/horasmod print(f'Costo por Hora de G.I.F.: {horagif}') elif respuesta== 9: print('[Presupuesto de Gastos de Operación]') print('\n~Primer Semestre') depreciacion1= int(input('Depreciación: ')) salarios= int(input('Sueldos y Salarios: ')) comisiones1= int(input('Comisiones: ')) varios1= int(input('Varios: ')) prestamo= int(input('Intereses por Préstamo: ')) total1= depreciacion1+salarios+comisiones1+varios1+prestamo print(f'Total de Gastos de Operación: {total1}') print('\n\n~Segundo Semestre') depreciacion2= int(input('Depreciación: ')) print(f'Sueldos y Salarios: {salarios}') comisiones2= int(input('Comisiones: ')) varios2= int(input('Varios: ')) print('Intereses por Préstamo: {prestamo}') total2= depreciacion2+salarios+comisiones2+varios2+prestamo print(f'Total de Gastos de Operación: {total2}') print('\n\n~Total Anual') depreciacion3= depreciacion1+depreciacion2 salarios3= salarios+salarios comisiones3= comisiones1+comisiones2 varios3= varios1+varios2 prestamo3= prestamo+prestamo total3= total1+total2 print(f'Depreciación: {depreciacion3}') print(f'Salarios: {salarios3}') print(f'Comisiones: {comisiones3}') print(f'Varios: {varios3}') print(f'Intereses por Préstamo: {prestamo3}') print(f'Total de Gastos por Operación: {total3}') print('\nDevuelta al menu') elif respuesta== 10: print('[Determinación del Costo Unitario de Productos Terminados]') print("[1] CL") print("[2] CE") print("[3] CR") producto= int(input('\n')) if producto==1: print('[Producto CL]') print('\n~Costo') materiala1= float(input('Material A: ')) materialb1= float(input('Material B: ')) materialc1= float(input('Material C: ')) mano1= float(input('Mano de Obra: ')) gastos1= float(input('Gastos Indirectos de Fabricación: ')) print('\n\n~Cantidad') materiala2= float(input('Material A: ')) materialb2= float(input('Material B: ')) materialc2= float(input('Material C: ')) mano2= float(input('Mano de Obra: ')) gastos2= float(input('Gastos Indirectos de Fabricación: ')) print('\n\n~Costo Unitario') materiala3= materiala1*materiala2 materialb3= materialb1*materialb2 materialc3= materialc1*materialc2 mano3= mano1*mano2 gastos3= gastos1*gastos2 print(f'Material A: {materiala3}') print(f'Material B: {materialb3}') print(f'Material C: {materialc3}') print(f'Mano de Obra: {mano3}') print(f'Gatos Indirectos de Fabricación: {gastos3}') costo= materiala3+materialb3+materialc3+mano3+gastos3 print(f'\nCosto Unitario: {costo}') print('\nDevuelta al menu') elif producto==2: print('[Producto CE]') print('\n~Costo') materiala1= float(input('Material A: ')) materialb1= float(input('Material B: ')) materialc1= float(input('Material C: ')) mano1= float(input('Mano de Obra: ')) gastos1= float(input('Gastos Indirectos de Fabricación: ')) print('\n\n~Cantidad') materiala2= float(input('Material A: ')) materialb2= float(input('Material B: ')) materialc2= float(input('Material C: ')) mano2= float(input('Mano de Obra: ')) gastos2= float(input('Gastos Indirectos de Fabricación: ')) print('\n\n~Costo Unitario') materiala3= materiala1*materiala2 materialb3= materialb1*materialb2 materialc3= materialc1*materialc2 mano3= mano1*mano2 gastos3= gastos1*gastos2 print(f'Material A: {materiala3}') print(f'Material B: {materialb3}') print(f'Material C: {materialc3}') print(f'Mano de Obra: {mano3}') print(f'Gatos Indirectos de Fabricación: {gastos3}') costo= materiala3+materialb3+materialc3+mano3+gastos3 print(f'\nCosto Unitario: {costo}') print('\nDevuelta al menu') elif producto==3: print('[Producto CR]') print('\n~Costo') materiala1= float(input('Material A: ')) materialb1= float(input('Material B: ')) materialc1= float(input('Material C: ')) mano1= float(input('Mano de Obra: ')) gastos1= float(input('Gastos Indirectos de Fabricación: ')) print('\n\n~Cantidad') materiala2= float(input('Material A: ')) materialb2= float(input('Material B: ')) materialc2= float(input('Material C: ')) mano2= float(input('Mano de Obra: ')) gastos2= float(input('Gastos Indirectos de Fabricación: ')) print('\n\n~Costo Unitario') materiala3= materiala1*materiala2 materialb3= materialb1*materialb2 materialc3= materialc1*materialc2 mano3= mano1*mano2 gastos3= gastos1*gastos2 print(f'Material A: {materiala3}') print(f'Material B: {materialb3}') print(f'Material C: {materialc3}') print(f'Mano de Obra: {mano3}') print(f'Gatos Indirectos de Fabricación: {gastos3}') costo= materiala3+materialb3+materialc3+mano3+gastos3 print(f'\nCosto Unitario: {costo}') print('\nDevuelta al menu') else: print('\nDevuelta al menu') elif respuesta== 11: print('[Valuación de Inventarios Finales]') print('\n*Inventario Final de Materiales*') print('~Unidades') materiala1= float(input('Material A: ')) materialb1= float(input('Material B: ')) materialc1= float(input('Material C: ')) print('\n~Costo Unitario') materiala2= float(input('Material A: ')) materialb2= float(input('Material B: ')) materialc2= float(input('Material C: ')) print('\n~Costo Total') materiala3= materiala1*materiala2 materialb3= materialb1*materialb2 materialc3= materialc1*materialc2 print(f'Material A: {materiala3}') print(f'Material B: {materialb3}') print(f'Material C: {materialc3}') costo1= materiala3+materialb3+materialc3 print(f'Inventario Final de Materiales: {costo1}') print('\n\n*Inventario Final de Producto Terminado*') print('~Unidades') productoa1= float(input('Producto CL: ')) productob1= float(input('Producto CE: ')) productoc1= float(input('Producto CR: ')) print('\n~Costo Unitario') productoa2= float(input('Producto CL: ')) productob2= float(input('Producto CE: ')) productoc2= float(input('Producto CR: ')) print('\n~Costo Total') productoa3= productoa1*productoa2 productob3= productob1*productob2 productoc3= productoc1*productoc2 print(f'Producto CL: {productoa3}') print(f'Producto CE: {productob3}') print(f'Producto CR: {productoc3}') costo2= productoa3+productob3+productoc3 print(f'Inventario Final de Producto Terminado: {costo2}') print('\nDevuelta al menu') elif respuesta== 12: print('\nGracias, vuelva pronto :)')
113d7bbfa4ae7b0f36316a783fb600d89791f817
lrussell21/ICPC_Template_Code
/Algorithms/problem23/main23.py
4,476
3.953125
4
import os import copy import sys from collections import defaultdict class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.output = '' self.count = 0 self.circuitCount = 0 # function to add an edge to graph def addEdge(self, u, v, weight): self.graph[int(u)].append([int(v), int(weight)]) #self.graph[v].append(u) def removeNode(self, graph, node): if node in graph: del graph[node] for x in graph: if node in graph.get(x): graph[x].remove(node) return graph def printGraph(self): print(self.graph) # for x in self.graph: # print(x) def BellmanFord(self, start): # Create distance list dist = [float("Inf")] * (self.V + 1) dist[start] = 0 # Starting node will be of length 0 # Repeat main algorithm for each verticy for _ in range(self.V - 1): # Goes through all the verticies and checks if the parent verticy and its weight to the next verticy is less than infinity. # In the end we get the least distance because the parent for loop itterates through all the verticies. So each one is checked more than once. for u in self.graph: if dist[u] != float("Inf"): for x in self.graph.get(u): v = x[0] weight = x[1] if (int(dist[u]) + weight) < dist[v]: dist[v] = int(dist[u]) + weight print(dist) # If there is a shorter path it means there is a negative weight cycle for u in self.graph: if dist[u] != float("Inf"): for x in self.graph.get(u): v = x[0] weight = x[1] if (int(dist[u]) + weight) < dist[v]: print("Graph contains negative weight cycle") return 1 #return 1 # Gets through negative cycle check return -1 def main(): filename = "/input.txt" dir_path = os.path.dirname(__file__) f = open(str(dir_path) + filename) numInput = f.readlines() numOfProblems = 0 listOfProblems = [] tempList = [] verticies = 0 verticiesToInput = 0 firstLineSkip = True startNewProblemInput = True skipBlank = False for x in numInput: # Get number of problems and get ready for input of problems if skipBlank: skipBlank = False continue if firstLineSkip: numOfProblems = int(x) firstLineSkip = False skipBlank = True continue if startNewProblemInput: temp = x.split() verticies = int(temp[0]) verticiesToInput = int(temp[1]) tempList.append(verticies) startNewProblemInput = False continue if verticiesToInput > 0: temp = x.split() tempList.append([int(temp[0]), int(temp[1]), int(temp[2])]) verticiesToInput -= 1 continue else: #startNewProblemInput = True # Push problem into array and start over listOfProblems.append(tempList[:]) tempList.clear() # Input for new problem temp = x.split() #print(temp) verticies = int(temp[0]) verticiesToInput = int(temp[1]) tempList.append(verticies) continue listOfProblems.append(tempList) #print(listOfProblems) tempOut = '' firstLineInput = True for problem in listOfProblems: firstLineInput = True print("New problem") for x in problem: if firstLineInput: g = Graph(int(x)) firstLineInput = False else: g.addEdge(int(x[0]), int(x[1]), int(x[2])) tempOut += str(g.BellmanFord(-1)) + " " #g.printGraph() #g.BellmanFord(1) print(tempOut) # File Output filename = "/output.txt" dir_path = os.path.dirname(__file__) filewrite = open(str(dir_path) + filename, 'w') filewrite.write(str(tempOut)) if __name__== "__main__": main()
5df6d93c9478d318416209582f02d6b9e33964e0
mengyx-work/CS_algorithm_scripts
/leetcode/LC_1143. Longest Common Subsequence.py
612
3.5625
4
class Solution(object): def longestCommonSubsequence(self, text1, text2): m, n = len(text1), len(text2) res = 0 d = [[0 for _ in range(n+1)] for _ in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if text1[i-1] == text2[j-1]: d[i][j] = d[i - 1][j - 1] + 1 else: d[i][j] = max(d[i - 1][j], d[i][j - 1]) res = max(res, d[i][j]) # print(d) return res sol = Solution() text1 = "abcde" text2 = "ace" print(sol.longestCommonSubsequence(text1, text2))
869324317072e944a8cf2cb2bd8ef53bc88afc47
evizitei/py-sandbox
/pig_latin.py
257
3.703125
4
word = raw_input("Give me a word...") if len(word) > 0 and word.isalpha(): word = word.lower() first_letter = word[0] midway = (word + first_letter + "ay") translation = midway[1:len(midway)] print translation else: print "It's no good, sir..."
6623abe71a0d441f21f1e6a1d9c553c7eea3fc69
JLMarshall63/myGeneralPythonCode
/CalculatorAreaCircleTriangle.py
919
4.4375
4
''' The program should do the following: Prompt the user to select a shape Depending on the shape the user selects, calculate the area of that shape Print the area of that shape to the user ''' from math import pi from time import sleep from datetime import datetime now = datetime.now() print '%s/%s/%s/%s/%s/%s' % (now.month, now.day, now.year, now.hour, now.minute, now.second) sleep(1) hint = "Units = Inches\n" entry = raw_input("Print C to calculate a Circle or T to calculate a Triangle: " + hint) if entry == "C": r = float(raw_input("Enter radius: ")) area = pi * r**2 print "The pie is baking . . ." sleep(1) print area elif entry == "T": h = float(raw_input("Enter height: ")) b = float(raw_input("Enter base: ")) area = ((0.5 * b) * h) print "Uni Bi Tri . . ." sleep(1) print area
8453e4ab440c1535b1bdb9f7c8d26983696bed51
TBG1006/Python-Challenge
/PyBank/analysis/PyBankMain.py.py
3,132
3.828125
4
import os import csv csvpath = os.path.join('PyBank', 'Resources', 'PyBank_Resources_budget_data.csv') with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) # Read the header row first (skip this step if there is now header) csv_header = next(csvreader) print(f"CSV Header: {csv_header}") # Set lists to accept data from csv months = [] profitData = [] monthProfitChange = [] # iterate through columns in csv and add to lists for row in csvreader: #add months to totalMonths months.append(row[0]) #add P/l data to profitData profitData.append(int(row[1])) #print(Months) #print(profitData) #Find number of months totalMonths = len(months) #print(totalMonths) # add profit change data to list for i in range(len(profitData)-1): monthProfitChange.append(profitData[i+1]-profitData[i]) # function to find average def Average(monthProfitChange): return sum(monthProfitChange) / len(monthProfitChange) #call function to find average averageProfit = round(Average(monthProfitChange),2) #print(averageProfit) # find max profit in list maxProfitChange = max(monthProfitChange) #print(maxProfitChange) # find min profit in list minProfitChange = min(monthProfitChange) #print(minProfitChange) # find index value of max profit to pass into months[] add one because we have to use the monthe we are subtracting FROM maxMonth = monthProfitChange.index(max(monthProfitChange)) +1 #print(maxMonth) # find index value of min profit to pass into months[] add one because we have to use the monthe we are subtracting FROM minMonth = monthProfitChange.index(min(monthProfitChange)) +1 # This section prints values to terminal ##### print("Financial Anlaysis:") print("----------------------------------------------") print(f"Total Months: {totalMonths}") print(f"Net Total P/L: ${sum(profitData)}") print(f"Average Change: ${averageProfit}") print(f"Greatest Increase in Profits: {months[maxMonth]} (${maxProfitChange})") print(f"Greatest Decrease in Profits: {months[minMonth]} (${minProfitChange})") #OUTPUT output_path = os.path.join('PyBank', 'Analysis', 'PyBankOutput.csv') with open (output_path, 'w', newline='') as csvfile: #csvwriter = csv.writer(csvfile, delimiter=',') csvfile.write("Financial Analysis:") csvfile.write("\n") csvfile.write("-------------------------------------------") csvfile.write("\n") csvfile.write(f"Total Months: {totalMonths}") csvfile.write("\n") csvfile.write(f"Net Total P/L: ${sum(profitData)}") csvfile.write("\n") csvfile.write(f"Average Change: ${averageProfit}") csvfile.write("\n") csvfile.write(f"Greatest Increase in Profits: {months[maxMonth]} (${maxProfitChange})") csvfile.write("\n") csvfile.write(f"Greatest Decrease in Profits: {months[minMonth]} (${minProfitChange})")
e73ca0d006d3413c307da8a8ea657bf188007167
dongupak/Prime-Python
/src/Ch10/minus_filter_func.py
453
3.671875
4
# 코드 10-7 : 람다 함수를 이용한 음수 값 추출기능 1 ## "으뜸 파이썬", p. 581 def minus_func(n): # n이 음수이면 True, 그렇지 않으면 False를 반환 if n < 0 : return True else: return False n_list = [-30, 45, -5, -90, 20, 53, 77, -36] minus_list = [] # 음수를 저장할 리스트 for n in filter(minus_func, n_list): minus_list.append(n) print('음수 리스트 :', minus_list)
f64760c1474c178d626a4e2fca0996ffed70239e
musicGDS/CS50-tasks
/credit.py
749
3.578125
4
import re from cs50 import get_string def legitNumber(number): x = 1 y = 0 lenght = len(number) for i in range(lenght - 1, -1, -2): x = x + 2 * int(number[i]) for i in range(lenght, -1, -2): y = y + int(number[i]) if (x + y) % 10 == 0: return True else: return False # check which brand the car is cardNumber = get_string("Number: ") if cardNumber.isdigit() != True: print("foo") elif re.search("^3[4,7].*", cardNumber) and len(cardNumber) == 15: print("AMEX") elif re.search("^4.*", cardNumber) and len(cardNumber) == 16 or len(cardNumber) == 13 : print("VISA") elif re.search("^5[1-5].*") and len(cardNumber) == 16 : print("MASTERCARD") else: print("foo")
914a4473eb06e7d9e00d09a544d8506eb22670c9
mikeyj777/ProjectEuler_2
/ProjectEuler_2/0009_special_pythagorean_triplet.py
968
3.96875
4
import numpy as np import math # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a2 + b2 = c2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def c(b): return (1000000 - 2000 * b + 2 * b**2) / (2000 - 2 * b) def a(b, ccalc): return math.sqrt(ccalc**2 - b**2) solns = [] for b in range(1, 999): ctest = c(b) atest = a(b, ctest) if atest % 1 == 0 and ctest % 1 == 0 and atest > 0 and ctest > 0 and atest < 999 and ctest < 999: solns.append((atest, b, ctest)) solns = np.array(solns) print(solns) for soln in solns: testpyth = soln[0] ** 2 + soln[1] ** 2 - soln[2]**2 testsum = soln[0] + soln[1] + soln[2] print("python triple test (should be zero): ", testpyth) print("sum test (should be 1000): ", testsum) soln = solns[0] prod = 1 for val in soln: prod *= val print(prod)
4db671f2a6e83603dce394bb5304ae5cfe356ae6
radineshkumar/Python_scripts
/Bootcamp/CaptsoneProjects/number_exercises/NumbersTuple.py
345
4.15625
4
""" Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. """ def main(): usr_input = input("Enter the numbers in comma format:\n") test = usr_input.split(",") print(test) print(tuple(test)) if __name__ == "__main__": main()
4ce5773cb7ffefb2e4796beb5022104449b1a0cf
lvraikkonen/GoodCode
/leetcode/653_two_sum_IV_input_is_a_BST.py
2,010
3.875
4
from __future__ import print_function from collections import deque # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Tree(object): def __init__(self, root=None): self.root = root def __repr__(self): left = None if self.root.left is None else self.root.left.val right = None if self.root.right is None else self.root.right.val return '(D:{}, L:{}, R:{})'.format(self.root.val, left, right) def build_binary_tree(self, sequence): """ build tree from sequence return root """ if type(sequence) != list: print("Illegal data type, please input list.") node_data = iter(sequence) self.root = TreeNode(next(node_data)) queue = deque([self.root]) while True: head_node = queue.popleft() try: head_node.left = TreeNode(next(node_data)) queue.append(head_node.left) head_node.right = TreeNode(next(node_data)) queue.append(head_node.right) except StopIteration: break return self.root class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ if not root: return False queue, candidate_val_set = deque([root]), set() while queue: node = queue.popleft() if k - node.val in candidate_val_set: return True candidate_val_set.add(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return False if __name__ == '__main__': s = Solution() num = [5,3,6,2,4,None,7] k = 9 t = Tree() root = t.build_binary_tree(num) s.findTarget(root, k)
8d30316add8b3861ad790cb43a7133cd81397dc5
mergehez/Eight-Queens-Problem
/EightQueen/eightqueen.py
6,658
3.703125
4
import sys import tkinter as tk import tkinter.messagebox as msgbox ## GameBoard class from http://stackoverflow.com/a/4959995/2999554 class GameBoard(tk.Frame): def __init__(self, parent, rows=8, columns=8, size=32, color1="white", color2="blue"): '''size is the size of a square, in pixels''' self.rows = rows self.columns = columns self.size = size self.color1 = color1 self.color2 = color2 self.pieces = {} canvas_width = columns * size canvas_height = rows * size tk.Frame.__init__(self, parent) self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, width=canvas_width, height=canvas_height, background="bisque") self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2) # this binding will cause a refresh if the user interactively # changes the window size self.canvas.bind("<Configure>", self.refresh) def addpiece(self, name, image, row=0, column=0): '''Add a piece to the playing board''' self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c") self.placepiece(name, row, column) def placepiece(self, name, row, column): '''Place a piece at the given row/column''' self.pieces[name] = (row, column) x0 = (column * self.size) + int(self.size/2) y0 = (row * self.size) + int(self.size/2) self.canvas.coords(name, x0, y0) def refresh(self, event): '''Redraw the board, possibly in response to window being resized''' xsize = int((event.width-1) / self.columns) ysize = int((event.height-1) / self.rows) self.size = min(xsize, ysize) self.canvas.delete("square") color = self.color2 for row in range(self.rows): color = self.color1 if color == self.color2 else self.color2 for col in range(self.columns): x1 = (col * self.size) y1 = (row * self.size) x2 = x1 + self.size y2 = y1 + self.size self.canvas.create_rectangle(x1, y1, x2, y2, outline="black", fill=color, tags="square") color = self.color1 if color == self.color2 else self.color2 for name in self.pieces: self.placepiece(name, self.pieces[name][0], self.pieces[name][1]) self.canvas.tag_raise("piece") self.canvas.tag_lower("square") # image for queen imagedata = ''' iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAAtAAAALQB65csewAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFWSURBVEiJ1ZUxTgJREIa/QU02aEOk4AgmFDS2hlgbTkCzFTEcwcaEPQUVva0JB9iESk9AC0dQTFAZC2fNY308V9Yt/JNJ9s375/9n3r7NiqpSJWq/IYtIU0SalRiIyC2wBJb2XAyq+mMADWAFqMUKaBSpLTrBARA568hyhXAGjIEboB6YInEmSAK8ummNTZvUKRwGCicObxLgDR1eWrPzzXDqG1FELoHYScWW88HVaAB0bYo1MPB0FAFzp6ss5kDk4Q9MKwW67sYUeAP6gbPPR5Lj9k1j+pVzNkdW9A7ElmtbN7sM1kDbuLHVKjDyGfScwg1wDcwC4lnMjLtxcj2fQauAWNFofTMwk8UfiC9CX/ID5bGl8f8NxP3hiMgxn7epDO5V9TlbHOY2X4Ar4GhP8VfgbiuTu0Udyt+iTugWXezZ+U6Nyg3yL/kcOClp8KSqj16DKvABRL2gKnTXZ/kAAAAASUVORK5CYII= ''' ## Queens class from http://svn.python.org/projects/python/trunk/Demo/scripts/queens.py N = 8 # Number of Columns, for chess board M = 1 # Number of Solutions class Queens: def __init__(self, n=N, m=M): self.n = n self.m = m self.reset() def setM(self,m=M): self.m = m def getM(self): return self.m def reset(self): n = self.n m = self.m self.y = [None] * n # Where is the queen in column x self.row = [0] * n # Is row[y] safe? self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? self.nfound = 0 # Instrumentation # All Solutions (3d array of zeros) [sol][row][col] self.sols = [[[0 for k in range(n)] for j in range(n)] for i in range(m+1)] def add(self, c, r, x): self.sols[c][r][x] = 1 def solve(self, x=0): # Recursive solver for y in range(self.n): if self.safe(x, y): self.place(x, y) if x+1 == self.n: if self.nfound == self.m: return self.display() else: self.solve(x+1) self.remove(x, y) def safe(self, x, y): return not self.row[y] and not self.up[x-y] and not self.down[x+y] def place(self, x, y): self.y[x] = y self.row[y] = 1 self.up[x-y] = 1 self.down[x+y] = 1 def remove(self, x, y): self.y[x] = None self.row[y] = 0 self.up[x-y] = 0 self.down[x+y] = 0 silent = 0 def display(self): rw=0 print("------------------start----------------") for y in range(self.n-1, -1, -1): col = '' cl=y for x in range(self.n): if self.y[x] == y: col += ' Q ' rw = int(x) else: col += ' . ' #print (col) self.add(self.nfound,rw,cl) print ("[sol][row][col]", self.nfound,rw,cl) print("------------------end----------------") rw=0 cl=0 self.nfound = self.nfound + 1 q = Queens(8,M) root = tk.Tk() board = GameBoard(root) solnum=0; def refresh(): # displaying chess border with a solution M = q.getM() global labeltext global solnum for i in range(q.n): # i is row for j in range(q.n): # j is column if q.sols[solnum][i][j] == 1: print ("[sol][row][col]", solnum,i,q.sols[solnum][i][j]) board.addpiece("player"+str(i) , player1 , i, j) # adding a queen to the board print("---------------"+str(solnum+1)+"-------------------") labeltext = str(solnum+1) + ". Solution" # changing label text solnum = (solnum + 1)%(M); label.configure(text=labeltext) root.mainloop() def getM(): # asking number of solutions global M global q a = ""; try: a = int(input("How many solution do you want? ")) if a<0: print("Must be a positive integer!!") getM() else: if a>92: # For a 64-cell board, max number of solutions is 92 print("Must be less than 92!!") getM() else: q = Queens(8,a) q.solve() # inserting all solution to the solution array(q.sols) refresh() except ValueError: print("Not an integer value!!") getM() if __name__ == "__main__": label = tk.Label(root, text="", width=25) label.pack(pady=5) board.pack(side="top", fill="both", expand="true", padx=4, pady=4) player1 = tk.PhotoImage(data=imagedata) btn = tk.Button(root,text='Refresh',width=25,command=refresh) btn.pack(pady=10) n = N getM()
16a3c35263acfc965ce23e6b1bd54ddc37e053e6
themikesam/1072-Python
/prime.py
957
3.859375
4
import time; # 引入time模块 def isPrime(n): # prime numbers are greater than 1 if n > 1: # check for factors for i in range(2,n): if (n % i) == 0: print(n,"不是質數") print(i,"x",n//i,"=",n) break else: print(n,"是質數") break # if input nber is less than # or equal to 1, it is not prime else: print(n,"不是質數") def isPrime_ans(n): i = 2 if n > 1: while i < n: if n % i == 0: return False i+=1 return True else: return False def sumPrime(n): i = 0 sum = 0 while i < n: i+=1 if(isPrime_ans(i)): sum+=1 return sum def Main(): start = time.time() n = int(input()) print(sumPrime(n)) end = time.time() print('共用了',(end-start)*1000,'ms') Main()
cf1e8b70cd5a8fd41292882350fb4f2ba413df17
qichaozhao/potatolemon
/src/layer.py
3,551
3.6875
4
""" A layer is a collection of Neurons """ import numpy as np from .neuron import Neuron from .activations import sigmoid from .optimisers import sgd class Layer(object): def __init__(self, size, num_inputs, type=Neuron, activation=sigmoid, optimiser=sgd, learning_rate=0.01): """ :param size: The number of neurons in the layer :param num_inputs: A matrix of shape (i, m). - i is the number of neurons in the previous layer - m is the number of training examples :type: The type of neuron to use """ self.size = size self.num_inputs = num_inputs self.neuron_type = type self.activation = activation self.optimiser = optimiser self.learning_rate = learning_rate # Create all the neurons in this layer self.neurons = [] for i in range(size): self.neurons.append(self.neuron_type(self.num_inputs, activation=self.activation, optimiser=self.optimiser, learning_rate=self.learning_rate)) def get_weights(self): """ We have a list of neuron objects with their associated weights. For each item in the list, the shape will be a vector of length self.num_inputs Therefore, we should concatenate these weights together, so that the layer weights will be (self.size, self.num_inputs) :return: A matrix of shape (self.size, self.num_inputs) """ weights = np.zeros((self.size, self.num_inputs)) for idx, neuron in enumerate(self.neurons): weights[idx, :] = np.squeeze(neuron.get_weights()) return weights def set_weights(self, weights): """ Decomposes the weights matrix into a list of vectors to store into the Neuron weights. :param weights: A matrix of shape (self.num_inputs, self.size) :return: """ for idx, neuron in enumerate(self.neurons): neuron.set_weights(weights[idx, :]) def forward(self, input): """ Performs a forward pass step, calculating the result of all neurons. :param input: A matrix of shape (self.num_inputs, t) (from the previous layer or the overall input) :return: A vector of length (self.size, t) (i.e. the result of the equation sigmoid(W.X + b)). t is the number of training examples """ # In a more performant network, we should do a direct matrix multiplication for all Neurons # But in our slower version we rely on the per neuron forward function to retrieve our forward propagation result res = [] for idx, neuron in enumerate(self.neurons): res.append(neuron.forward(input)) return np.vstack(res) def backward(self, da): """ Performs a backward pass step, calculating the backwards propagation result of all neurons within a layer. :param da: The backpropagation result of the previous layer. Shape is (self.size, t) :return: The backpropagation result of the current layer (dp) """ res = [] for idx, neuron in enumerate(self.neurons): da_neuron = da[idx, :] res.append(neuron.backward(da_neuron)) # Now our result array is a list of backpropagated vectors of shape (m, t), we should just do an element-wise # sum to construct the layer backprop output # noinspection PyArgumentList dp = np.add.reduce(res) return dp
4eebeabb683b05f146e7067f766ae1992df65fa3
alexandvoigt/python-csv-parser
/parser.py
3,191
3.75
4
import csv import re ''' Sort Flags: - N = Name - A = Age - L = Number of known languages Sort Order: - A = Ascending - D = Descending ''' VALID_SORT_FLAGS = {'N', 'A', 'L'} VALID_SORT_ORDER = {'A', 'D'} VALID_COLUMN_HEADERS = ["name", "age", "number_of_known_languages"] NAME_COLUMN = 0 AGE_COLUMN = 1 LANGUAGE_COLUMN = 2 def trim_whitespace(rows): for row in rows: for i in range(0, len(row)): row[i] = row[i].strip() def validate_input_parameters(sort_flag, sort_order): assert sort_flag in VALID_SORT_FLAGS, "{} is not a valid sorting flag! Valid entries are {}".format(sort_flag, VALID_SORT_FLAGS) assert sort_order in VALID_SORT_ORDER, "{} is not a valid sorting order! Valid entries are {}".format(sort_order, VALID_SORT_ORDER) def validate_row(row): assert re.search('[a-zA-Z] [a-zA-Z]', row[NAME_COLUMN]), "The name must include first and last names" assert re.search('\d', row[AGE_COLUMN]), "The age must only contain numbers" assert re.search('\d', row[LANGUAGE_COLUMN]), "The number of spoken lanuages must only contain numbers" def sanitize_row(row): full_name = row[NAME_COLUMN] first_name, last_name = full_name.split() row[NAME_COLUMN] = first_name.capitalize() + " " + last_name.capitalize() def validate_and_sanitize_csv_rows(input_rows): trim_whitespace(input_rows) header_row = input_rows[0] assert VALID_COLUMN_HEADERS == header_row, "{} are not valid column headers! The expected headers are {}".format(header_row, VALID_COLUMN_HEADERS) data_rows = input_rows[1:len(input_rows)] for row in data_rows: validate_row(row) sanitize_row(row) return input_rows def sort_rows(rows, sort_flag, sort_order): header_row = rows[0] data_rows = rows[1:len(rows)] if (sort_flag == 'N'): data_rows = sorted(data_rows, key = lambda row : row[NAME_COLUMN], reverse = bool(sort_order == 'D')) elif (sort_flag == 'A'): data_rows = sorted(data_rows, key = lambda row : row[AGE_COLUMN], reverse = bool(sort_order == 'D')) elif (sort_flag == 'L'): data_rows = sorted(data_rows, key = lambda row : row[LANGUAGE_COLUMN], reverse = bool(sort_order == 'D')) else: raise AssertionError("{} is not a valid sorting flag! Valid entries are {}".format(sort_flag, VALID_SORT_FLAGS)) return [header_row] + data_rows def pretty_print_rows(rows): header_row = rows[0] data_rows = rows[1:len(rows)] padding = 20 formatted_header_row = "|".join(str(value).ljust(padding) for value in header_row) print(formatted_header_row) print("-" * len(formatted_header_row)) for row in data_rows: print("|".join(str(value).ljust(padding) for value in row)) file_path, sort_flag, sort_order = input("Enter the file path, column to sort by, and the sorting order: ").split() sort_flag = sort_flag.upper() sort_order = sort_order.upper() validate_input_parameters(sort_flag, sort_order) with open(file_path, newline='') as input_file: input_rows = list(csv.reader(input_file)) rows = validate_and_sanitize_csv_rows(input_rows) rows = sort_rows(rows, sort_flag, sort_order) pretty_print_rows(rows)
6de09919f6700751f08ac00cdb5640e73c933c6a
AnthonySimmons/EulerProject
/ProjectEuler/ProjectEuler/Problems/Problem48.py
638
3.703125
4
 #The series, 11 + 22 + 33 + ... + 1010 = 10405071317. #Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000. def SumOfSquaresInSequence(sequence): sum = 0 for num in sequence: power = pow(num, num) sum += power return sum sequence = range(1, 1000) sum = SumOfSquaresInSequence(sequence) def LastDigits(value, numDigits): digits = [] for i in range(numDigits): d = value % 10 value = int(value / 10); digits.add(d) return digits #lastTenDigits = LastDigits(sum, 10) def Solve(): sumStr = str(sum) print("Sum: " + sumStr) print("Last Ten Digits: " + sumStr[-10:]) return sumStr
5de88ba24bf8c59e0e9c3f0e5536f0035a656578
szymek156/project_euler
/28.py
1,731
3.5
4
def main(): sizeOfSquare = 1001 sumOfDiagonals = 0 firstDiag = 1 # for i in range(2, sizeOfSquare + 3, 2): # firstDiag += (((i+1)/2) - 1) * 8 # secondDiag = firstDiag - (i - 2) # thirdDiag = secondDiag - (i - 2) # fourthDiag = thirdDiag - (i - 2) # print "#1 ", firstDiag # sumOfDiagonals += firstDiag # if (secondDiag > 1): # print "#2 ", secondDiag # sumOfDiagonals += secondDiag # if (thirdDiag > 1): # print "#3 ", thirdDiag # sumOfDiagonals += thirdDiag # if (fourthDiag > 1): # print "#4 ", fourthDiag # sumOfDiagonals += fourthDiag # print "#############################" # print "Sum of diags ", sumOfDiagonals for k in range (3, 9 + 1, 2): firstDiag = k*k secondDiag = firstDiag - (k-1) thirdDiag = secondDiag - (k-1) fourthDiag = thirdDiag - (k-1) print "#1 ", firstDiag sumOfDiagonals = 0 sumOfDiagonals += firstDiag if (secondDiag > 1): print "#2 ", secondDiag sumOfDiagonals += secondDiag if (thirdDiag > 1): print "#3 ", thirdDiag sumOfDiagonals += thirdDiag if (fourthDiag > 1): print "#4 ", fourthDiag sumOfDiagonals += fourthDiag print "Sum of diags ", sumOfDiagonals print "poly ", 4*k*k - 6*k + 6 print "#############################" if __name__ == "__main__": main()
4d109a120dde7fcbfd33e3c9ac4545a8405b9112
dzinrai/my_euler_proj
/e23 other.py
1,486
3.765625
4
#find the sum of all the positive integers that cannot be written as the sum of two abundant numbers #Every number above 20161 can be written as two abundant numbers #every multiple of a perfect number is abundant #every multiple of abundant number is abundant abun = [12] no_abun = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] for i in range(13, 28123): if i in abun or i in no_abun: continue factors = set() factors.add(1) for u in range(2, i): if u in factors: continue elif i%u == 0: factors.update([u, i/u]) if sum(factors) > i: count = 2 abun.append(i) num = count*i while num < 28123: abun.append(num) count += 1 num = num*count elif sum(factors) == i: no_abun.append(i) count = 2 num = count*i while num < 28123: abun.append(num) count += 1 num = num*count else: no_abun.append(i) print(sorted(abun)) print() print('The length of abun is:', len(abun)) print() print(no_abun) print() print('The length of no_abun is:', len(no_abun)) abun_set = set() for i, u in enumerate(abun): for k in abun[i:]: if (u+k) <= 28123: abun_set.add(u+k) nonabun_list = [] for i in range(0, 28123): if i not in abun_set: nonabun_list.append(i) print(sum(nonabun_list))
284562893291732b0230143bbb85f35ed068ba72
MrX456/Algoritmos_Diversos_Python
/D035_FormarTriangulo.py
446
3.96875
4
#Ler comprimeto de 3 retas e dizer se elas podem ou não formar um triângulo r1 = float(input('Digite o comprimento da primeira reta: ')) r2 = float(input('Digite o comprimento da segunda reta: ')) r3 = float(input('Digite o comprimento da terceira reta: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2 : print('As retas acima podem formar um triângulo') else : print('As retas acima não podem formar um triângulo')
83b54e2d42257b3f027ff3ebb06b94e5981709a3
summerHuaiJin/PythonReadEMS
/TimeToName.py
1,930
3.75
4
# -*- coding:utf-8 -*- """ 这是一个将年月日时分转化为一串字符的程序 例如,2017年12月16日1点05分,将表示成201712160105 输入为年月日,输出为name,类型为list,包含当日每隔五分钟的字符串,一共288个""" def time_name(year, month, day): import time # 导入time模块 year = str(year).zfill(4) # zfill方法表示对字符串补位,高位补零 month = str(month).zfill(2) day = str(day).zfill(2) hour = [] # 定义小时为空list minute = [] # 定义分钟为空list name = [] # 定义名称字符串为空list first_time = year + '-' + month + '-' + day + ' 00:00:00' # 字符串可以直接用加法运算 # 转换成时间数组 timearray = time.strptime(first_time, "%Y-%m-%d %H:%M:%S") # 时间数组元素依次为年、月、日……秒 # 转换成时间戳 timestamp = time.mktime(timearray) # 时间戳是以秒为单位的一串数字 hour.append(timearray[3]) # append方法表示从列表最后新增元素 minute.append(timearray[4]) hour_str = str(hour[-1]).zfill(2) # zfill方法表示对字符串补位,高位补零 minute_str = str(minute[-1]).zfill(2) name.append(year + month + day + hour_str + minute_str) for i in range(1, 288): timestamp = timestamp + 60 * 5 timearray = time.localtime(timestamp) # localtime方法表示将时间戳转化为时间数组形式 hour.append(timearray[3]) minute.append(timearray[4]) hour_str = str(hour[-1]).zfill(2) minute_str = str(minute[-1]).zfill(2) name.append(year + month + day + hour_str + minute_str) # dt = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) # print(dt) # print(hour[-1]) # print(minute[-1]) # print('---------') return name # print(Name) # print(len(Name))
355179a53bd4e66bebcf696c1f4bec89056f7eae
lilyandcy/pyLearn-1
/Learn_math/math_Learn.py
265
3.640625
4
import math def function_Complex(a,b,c): try: result1 = (-b + math.sqrt(b*b-4*a*c))/(2*a) result2 = (-b - math.sqrt(b*b-4*a*c))/(2*a) return (result1,result2) except: return 'No valid input' print function_Complex(3,12,2)
0fa3538b82519f5b8a117b61ec443816cb949517
jonqi/a-nether-calculator
/nether_calculator.py
387
3.921875
4
def get_coordinate(x): while True: x_coord = input(f"{x} Coordinate: ") try: x_coord = float(x_coord) / 8 break except ValueError: print("Please input a number.") return x_coord x_coord = get_coordinate("X") y_coord = get_coordinate("Y") * 8 z_coord = get_coordinate("Z") print(f"({x_coord}, {y_coord}, {z_coord})")
e97d19ec62004d65d333d83246fa4c71d4c9a775
ElManu3le/Pythoon2
/EjerciciosPythoon2/ejercicio24.py
412
3.9375
4
"Ejercicio 24 - Escribid un programa que, dado un número entero positivo, calcule y muestre su factorial. El factorial de un número se obtiene multiplicando todos los números enteros positivos que hay entre el 1 y ese número. El factorial de 0 es 1." numerofac = int(input('Dime un numero con el que poder hacer el factorial: ')) for i in range(1, numerofac+1): print('En valor',i , 'es:',numerofac*i)
bed82ae55c419f67558696a3f3355a48ff4d9d98
jeonghaejun/01.python
/ch14_class/ex01_class.py
1,594
4
4
# 누구의 계좌인지 # 출금(withdraw) # 클래스 설계능력이 중요!! class Human: def __init__(self, name, age): # <--쓸변수는 다넣어준다. 나중에 정의해줄 변수도 self.name = name # 나중에 정의할 변수에는 None을 넣는다 self.age = age self.gender = None def intro(self): print(f'{self.age}살 {self.name}({self.gender})입니다.') def change(self, gender): # <--class 인자 추가가능 하지만 비권장이다. self.gender = gender def __str__(self): # <-----특수 메소드 return f'<Human {self.age},{self.name},{self.gender}>' def __repr__(self): return f'<Human {self.name}>' class Account: def __init__(self, owner, balance): # 생성자 함수 self.owner = owner # self.owner.name, self.owner.age, self.owner.gender self.balance = balance def deposit(self, money): self.balance += money def inquire(self): print('잔액은 %d원 입니다.' % self.balance) def withdraw(self, money): if self.balance < money: raise Exception('잔액부족') self.balance -= money return money hong = Human('홍길동', 29) account = Account(hong, 8000) # Account의 인스턴스 생성 account.deposit(1000) # <--- ctrl + 클릭시 해당 메소드로 이동 된다. account.inquire() try: account.withdraw(3000) account.inquire() account.withdraw(10000) account.inquire() except Exception as e: print('예외', e) # print(account)
fff3b0199cf5b029418a5405da4ea69676609c88
uopcs/euler
/001-099/029/todd.py
406
3.65625
4
def questionTwentyNine(): combinations = [] for a in range(2, 101, 1): for b in range(2, 101, 1): term = a ** b #print(term) double = False for current in combinations: if term == current: double = True if double == False: combinations.append(term) print(len(combinations))
d5096425a4fb0fa8467e23df962ba56188d28d67
David-E-Alvarez/Intro-Python-I
/src/05_lists.py
1,100
4.1875
4
# For the exercise, look up the methods and functions that are available for use # with Python lists. x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE x.append(4) #print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # YOUR CODE HERE #print(x) #x.append(y) i don't like the output of this on repl.it but don't know if i can do print(x + y) #print(x + y) # Change x so that it is [1, 2, 3, 4, 9, 10] # YOUR CODE HERE #print(x + y[1:]) #or x.append(y[1:]) to use print(x) #print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] #for this one the first thing i do is add the 99 like so: #y.insert(2,99) #i then can append y to x and "splice" the 8 out like so: #x.append(y[1:]) #if i do the line above i can use print(x) but if i can also do this: #print(x + y[1:])#and not do the appending of y to x # YOUR CODE HERE #print(x) # Print the length of list x # YOUR CODE HERE #print(len(x)) # Print all the values in x multiplied by 1000 # YOUR CODE HERE # for elem in x: # print(elem * 1000)
8fd37dddf0a777ce5e762d8731ecf7e05be3de5c
Licho59/Licho-repository
/inne_projekty/problem_solving_with_algorithms/unordered_complete_linkedList.py
6,543
3.859375
4
from node_class import Node class LinkedList(object): def __init__(self): self.head = None self.tail = None self.length = 0 def add(self, data): temp = Node(data) temp.setNext(self.head) self.head = temp self.tail = self.head self.length += 1 ''' def size(self): # alternative method for counting size of list current = self.head count = 0 while not (current is None): count += 1 current = current.getNext() return count ''' def remove(self, data): current = self.head prev = None found = False try: while not found: if current.getData() == data: found = True else: prev = current current = current.getNext() if prev is None: self.head = current.getNext() else: prev.setNext(current.getNext()) self.length -= 1 except AttributeError: print("The number " + str(data) + " can not be removed because there is no such number in the list.") def slice(self, start, stop): """ return a copy of the list starting at start position and going upto but not including stop position """ if (start < 0) or (start > stop) or (stop > self.length + 1): print("Invalid range.") return None stop = stop - 1 curr = self.head count = 0 while curr is not None: if count == start: break curr = curr.next count += 1 node = Node(curr.data) front = node back = front while count < stop: curr = curr.next node = Node(curr.data) back.next = node back = back.next count += 1 curr = front result = [] while curr is not None: result.append(curr.data) curr = curr.next print("Sliced list: ") print(result) #return front def pop(self, i=-1): """ Remove the item at the given position in the linked list, and return it. If no index is specified, a.pop() removes and returns the last item in the linked list.""" if self.isEmpty(): return None if i >= self.size(): return None if (i + self.length) < 0: return None if i < 0: ind = i + self.length else: ind = i curr = self.head prev = None count = 0 found = False while curr is not None: if count == ind: found = True break prev = curr curr = curr.next count += 1 if found: node = curr.data if prev is None: self.head = self.head.next else: prev.next = curr.next curr.next = None self.length -= 1 return node return None def insert(self, data, index): """ Insert data at given index in the linked list""" if not isinstance(index, int): print("Index should be of type Integer, str() passed") return False if index < 0 or index > self.size(): print("Bad Index Range!") return False curr = self.head prev = None count = 0 node = Node(data) if index == self.size(): print("Inserting at tail") self.tail.next = node self.tail = self.tail.next self.length += 1 return True while curr is not None: if count == index: break prev = curr curr = curr.next count += 1 if prev is None: print("Inserting at head") node.next = self.head self.head = node else: print("Inserting in between: ", count) node.next = curr prev.next = node self.length += 1 return True def index(self, x): """ return the index in the linked list of the first item whose value is x. Returns "None" if no such item in linked list """ curr = self.head index = 0 while curr is not None: if curr.data == x: return index curr = curr.next index += 1 return None def append(self, data): """ add the data at the end of the linked list """ node = Node(data) # If first node in the list then both head n tail should point to it if self.isEmpty(): self.head = node self.tail = self.head else: self.tail.next = node self.tail = self.tail.next self.length += 1 def search(self, key): """Search for key and if found return the index. return -1 otherwise""" current = self.head index = 0 found = False while current is not None: if key == current.data: found = True return index current = current.next index += 1 if found: return index return -1 def size(self): return self.length def isEmpty(self): return self.length == 0 def __str__(self): sll = [] curr = self.head while curr is not None: sll.append(curr.data) curr = curr.next #print (sll) return sll if __name__ == '__main__': mylist = LinkedList() mylist.add(31) mylist.append(400) mylist.add(77) mylist.add(17) mylist.add(93) mylist.add(26) mylist.add(54) mylist.insert(55, 0) mylist.pop() mylist.remove(200) mylist.add(17) print(mylist.size()) print(mylist.__str__()) print(mylist.search(400)) print(mylist.slice(0, 4)) print(mylist.index(31)) print(mylist.search(93)) print(mylist.search(100)) mylist.add(100) print(mylist.search(100)) print(mylist.size()) mylist.remove(54) print(mylist.size()) mylist.remove(93) print(mylist.__str__()) mylist.remove(31) print(mylist.size()) print(mylist.search(93))
1f2934e1123fd364ac751c35f6c6dff73f3f4119
osnaldy/Python-StartingOut
/chapter5/Buget_Analysis.py
357
3.921875
4
buget = int(raw_input("Enter the amount budgeted for the month: ")) total = 0 for i in range(6): expense = int(raw_input("Enter the total for each expense: ")) total += expense if total > buget: t1 = total - buget print "Your are over with", t1, 'Dollars' else: t1 = buget - total print "Your budget is under with ", t1, 'Dollars'
e7167d081e8bec13ba764bcc813692dc43028b7c
sarahgonsalves223/DSA_Python
/Hard/149_hard_max-points-on-a-line.py
2,076
3.75
4
# # @lc app=leetcode id=149 lang=python3 # # [149] Max Points on a Line # # https://leetcode.com/problems/max-points-on-a-line/description/ # # algorithms # Hard (16.00%) # Total Accepted: 134.7K # Total Submissions: 827.9K # Testcase Example: '[[1,1],[2,2],[3,3]]' # # Given n points on a 2D plane, find the maximum number of points that lie on # the same straight line. # # Example 1: # # # Input: [[1,1],[2,2],[3,3]] # Output: 3 # Explanation: # ^ # | # |        o # |     o # |  o   # +-------------> # 0  1  2  3 4 # # # Example 2: # # # Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] # Output: 4 # Explanation: # ^ # | # | o # |     o   o # |      o # |  o   o # +-------------------> # 0  1  2  3  4  5  6 # # # NOTE: input types have been changed on April 15, 2019. Please reset to # default code definition to get new method signature. # # from collections import defaultdict class Solution: def maxPoints(self, points: List[List[int]]) -> int: """ Time Complexity = O(n^2) Space Complexity = O(n-1) """ if len(points) == 0: return 0 if len(points) < 3: return len(points) max_count = 1 for i in range(len(points)-1): count = 1 lines = defaultdict(lambda:0) horizontal = 0 duplicates = 0 for j in range(i+1, len(points)): x1 = points[i][0] y1 = points[i][1] x2 = points[j][0] y2 = points[j][1] if x1 == x2 and y1 == y2: duplicates += 1 elif y1 == y2: horizontal += 1 count = max(count, horizontal+1) else: slope = (x1-x2)/(y1-y2) lines[slope] = lines[slope] + 1 count = max(count, lines[slope]+1) max_count = max(max_count, count+duplicates) return max_count
a87ea9ea2ef0f80bab207cbc0771bbe7c155a27d
zhoushuhua/CorPyProgPractice
/Chapter03/Test01.py
1,503
3.625
4
# user python download ftp file import ftplib import os import socket # const var HOST = "ftp.iap.ac.cn" DIR="/geog/hlens" FILE = "00001-02161.00001-01081" # defined function to download def main(): try: # connect ftp # print "> input ftp Host:" # data = raw_input() # if data != "" : HOST = data ftp = ftplib.FTP(HOST) except (socket.error, socket.gaierror) as e: print "ERROR : cannot reach %s" % HOST # terminal function return try: # login to ftp ftp.login() except ftplib.error_perm: print "ERROR : cannot login by anonymous" # terminal function return try: # print "> input ftp DIR:" # data = raw_input() # if data != "" : DIR = data ftp.cwd(DIR) except ftplib.error_perm: print "ERROR : cannot change to %s" % DIR # terminal function return try: # close file # with open(FILE, "wb") as f: # ftp.retrbinary("RETR %s" % FILE, f.write) # print "> input ftp download file Name:" # data = raw_input() # if data != "" : FILE = data f = open(FILE, "wb") ftp.retrbinary("RETR %s" % FILE, f.write) except ftplib.error_perm: print "ERROR : cannot read file %s " % FILE return finally: # close file if f in locals(): f.close() # return ftp.quit() if __name__ == "__main__": main()
6d1c98f7739cab2c09009efd3b94ea3513648c1d
gabriellaec/desoft-analise-exercicios
/backup/user_204/ch45_2020_10_06_18_47_29_059316.py
208
4.0625
4
lista = [] novo_valor = float(input("Digite um valor: ")) while novo_valor != 0 and novo_valor > 0: lista.append(novo_valor) novo_valor = float(input("Digite um valor: ")) lista.reverse() print(lista)
cf234c912af5d81c44f9aed6eda2165b3a715e79
zhaolijian/suanfa
/leetcode/135.py
959
3.546875
4
# 老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 # 你需要按照以下要求,帮助老师给这些孩子分发糖果: # 每个孩子至少分配到 1 个糖果。 # 相邻的孩子中,评分高的孩子必须获得更多的糖果。 # 那么这样下来,老师至少需要准备多少颗糖果呢? # 两次遍历 class Solution: def candy(self, ratings) -> int: length = len(ratings) if length < 2: return 1 res = [1] * length for i in range(1, length): if ratings[i] > ratings[i - 1]: res[i] = res[i - 1] + 1 for j in range(length - 2, -1, -1): if ratings[j] > ratings[j + 1]: res[j] = max(res[j], res[j + 1] + 1) return sum(res) if __name__ == '__main__': s = Solution() ratings = [1,3,2,2,1] print(s.candy(ratings))
21e3fba95bd4f521b72e74d480e26e0d064d0543
wqzhang0/python_stu
/icode/enum/enum_test.py
1,163
3.53125
4
from enum import Enum, unique # @unique装饰器可以帮助我们检查保证没有重复值。 @unique class Weekday(Enum): Sun = 0 # Sun的value被设定为0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = '5' Fri_int = 5 Sat = 6 if __name__ == '__main__': print(Weekday.Sat.value) print(type(Weekday.Sat)) print(type(Weekday.Sat.value)) print(Weekday.Fri.value) print(type(Weekday.Fri.value)) print(Weekday['Sun'].value) print(Weekday(2)) Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) # Month = Enum('x', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) # 上面这段代码等价于: # # class x(Enum): Jan = 1 # # # Feb = 2 # Mar = 3 # Apr = 4 # May = 5 # Jun = 6 # Jul = 7 # Aug = 8 # Sep = 9 # Oct = 10 # Nov = 11 # Dec = 12 # Month = x print(Month.Feb) print(Month.Feb.value) Weekday2 = Enum('x',('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) print(Weekday2.Jan)
22abfe9021fbf48281c700d70d616e5c49333b65
Meschdog18/simply-progress
/simply_progress/progress.py
2,156
3.796875
4
from os import system, name class Progress_Bar: """Init Progress Bar Parameters: range (int): total length of data, progress bar will track name (any value supported by print()): data placed infront of progress bar ({name} |{progressbar}|) (default is None) display (bool):to display done message or not (default is True) """ def __init__(self, range=0, name="", display=True): self._range = range self._progress_points = 10#atm only works with 10 progress points, will allow user to change this value in future self._current = 0 self._name = name self._done_message = " is done!" #default done message self._progress_bars = 0 self._display_done = display if not isinstance(range, int): raise TypeError("Only ints are allowed") if range == 0: raise ValueError("Range cannot be set to 0") """Iterate """ def next_step(self): self._current += 1 self._print() if self._current == self._range: self._done() def _clear(self): if name == 'nt': _ = system('cls') else: _ = system('clear') def _print(self): self.progress_percent = (self._current/self._range) * 100 pb = int(self.progress_percent/self._progress_points) self._progress_bars = pb progress_empty_bars = self._progress_points-self._progress_bars self._clear() print("{} |{}{}| {}%".format(self._name ,"="*self._progress_bars,"-"*progress_empty_bars, int(self.progress_percent))) @property def done_message(self): return self._done_message """Set Done Message, Printed When Progress Bar is Done Parameters: message (string): message to display """ @done_message.setter def done_message(self, message): if not isinstance(message, str): raise TypeError("Only strings are allowed") self._done_message = message def _done(self): if self._display_done: print("{}{}".format(self._name, self._done_message))
cb19ce83b5d1bdd29ac4052f7b03f9dd70943ebd
nanareyes/CicloUno-Python
/Nivelacion_3/colecciones.py
1,387
4.25
4
# Cadenas -> Flujos de caracteres o palabras (orden inmutables) cadena = "hola Mundo" print(cadena[0]) print(cadena[-1]) print(cadena[2]) print(cadena[0:4]) # las cadenas son inmutables, pero se pueden reordenar a partir de caracteres cadena = cadena[0].upper() + cadena[1:] # upper para mayúscula print(cadena) # Listas -> obedecen a un orden también se pueden modificar (mutables) lista = [12, "hola", "casa", 45] print(lista[0]) print(lista[-1]) print(lista[0:2]) lista[0] = 24 # Las listas son mutables y permiten insercciones print(lista) lista.append("nuevo elemento") # agrega un nuevo elemento al final print(lista) lista.insert(0, [6, 7, 8]) # insterta lista en el primer espacio (0) print(lista) lista.pop(0) # decrementar la lista, si no se especifica: elimina el último print(lista) """si no queremos coleccionar elementos que se modifiquen escogemos tuplas, pero de lo contrario escogemos listas""" # Tuplas -> equivalentes a listas que no se pueden modificar a = 12 b = 12 tupla = (a, b, lista) print(tupla) # Las tuplas van con paréntesis redondos # No siguen un orden -> conjutnos, diccionarios # Conjuntos conjunto = {"Armenia", "Bogotá", "Cali"} for elemento in conjunto: print(elemento) print("--------------") conjunto.add("Ibagué") # para agregar un elemento conjunto.remove("Armenia") # para remover for elemento in conjunto: print(elemento)
8722932b2e7c60001dbfd5dc1e332186f8f3f7bc
dgoffredo/leetcode
/palindrome-pairs/naive2.py
733
3.734375
4
from itertools import chain # leetcode.com boilerplate from typing import List class Solution: def palindromePairs(self, words: List[str]) -> List[List[int]]: return palindrome_pairs(words) def palindrome_pairs(words): result = [] for i in range(len(words)): for j in range(len(words)): if i != j and concatentation_is_palindrome(words[i], words[j]): result.append([i, j]) return result def concatentation_is_palindrome(left, right): i = chain(left, right) j = chain(reversed(right), reversed(left)) for _ in range((len(left) + len(right)) // 2): if next(i) != next(j): return False return True
e7c1ac6dfb8a4bce7e9cd7667917b785f855d027
C-CCM-TC1028-102-2113/tarea-4-RCERVANT3S
/assignments/17NCuadradoMayor/src/exercise.py
229
3.90625
4
def main(): #Escribe tu código debajo de esta línea pass num = int(input("Escribe un numero : ")) for conta in range(1,num,1): if conta ** 2 >= num: break print(conta) if __name__=='__main__': main()
6a410f66e4391f8742ad6f83ab591b7005239d6a
meghana2812/meghana
/third1.py
101
3.859375
4
v1={'a','e','i','o','u'} m1=input().lower() if m1 in v1: print("Vowel") else: print("Consonant")
5295c251aa633169e7f3f4dd807a4e604e3166ea
codrameurs/moyenneur
/main.py
1,332
3.578125
4
from tkinter import * from moyenneur_module import * ''' ''' class Fenetre(): denom=False def __init__(self): self.fenetre = Tk() self.fenetre.title("Moyeneur") self.fenetre.geometry("700x550") self.notes=getdict() self.menu_princ() def valider_note(self,entry): note = entry.get() print(note) return note def valider_sur(self,entry): sur = entry.get() print(sur) return sur def menu_princ(self): note=0 sur=0 title=Label(self.fenetre,text="Bienvenue sur le moyeneur") title.place(x=300,y=0) print(self.notes) entry=Entry(self.fenetre) entry.place(x=300,y=50) enter=Button(self.fenetre,text="entrer",command=self.valider_note(entry)) enter.place(x=300,y=100) phraseN=Label(self.fenetre,text="entrez votre note:") phraseN.place(x=300,y=30) phraseS=Label(self.fenetre,text="Sur combien est votre notre:") phraseS.place(x=300,y=30) enterS=Button(self.fenetre,text="entrer",command=self.valider_sur(entry)) enterS.place(x=300,y=100) texte = Label(self.fenetre,text="%d/%d"%(note,sur)) texte.place(x=20,y=100) self.fenetre.mainloop() fenetre=Fenetre() fenetre.__init__()
2731307da1f2ccfb2c91e64e29346eb30ae6a984
taoing/python_code
/3.0 python_structure/search/binary_search.py
1,836
3.9375
4
# -*- coding: utf-8 -*- # 二分查找 def binary_search(alist, item): first = 0 last = len(alist) - 1 found = False while first <= last and not found: midpoint = (first+last) // 2 if alist[midpoint] == item: found = True; else: if item < alist[midpoint]: last = midpoint-1 else: first = midpoint+1 return found testlist = [0, 1, 2, 8, 13, 19, 32, 42] print(binary_search(testlist, 3)) print(binary_search(testlist, 13)) # 递归 def binary_search_r(alist, item): if len(alist) == 0: return False else: midpoint = len(alist) // 2 if alist[midpoint] == item: return True else: if item < alist[midpoint]: return binary_search_r(alist[:midpoint], item) else: return binary_search_r(alist[midpoint+1:], item) testlist = [0, 1, 2, 8, 13, 19, 32, 42] print(binary_search_r(testlist, 3)) print(binary_search_r(testlist, 13)) # 递归改进 def binary_search_r_helper(alist, start, end, item): if start > end: return False else: midpoint = (start+end) // 2 if item == alist[midpoint]: return True else: if item < alist[midpoint]: return binary_search_r_helper(alist, start, midpoint-1, item) else: return binary_search_r_helper(alist, midpoint+1, end, item) def binary_search_r2(alist, item): if len(alist) == 0: return False else: return binary_search_r_helper(alist, 0, len(alist)-1, item) testlist = [0, 1, 2, 8, 13, 19, 32, 42] print(binary_search_r2(testlist, 3)) print(binary_search_r2(testlist, 13)) print(binary_search_r2(testlist, 0)) print(binary_search_r2(testlist, 42))
2dd7a7e94340ab6e7fd209141e714c7495fa8d3f
waithope/leetcode-jianzhioffer
/leetcode/227-basic-calculatorii.py
1,354
4.28125
4
# -*- coding:utf-8 -*- ''' Basic Calculator ======================== Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Output: 7 Example 2: Input: " 3/2 " Output: 1 Example 3: Input: " 3+5 / 2 " Output: 5 Note: You may assume that the given expression is always valid. Do not use the eval built-in library function. ''' def calculate(s: str): num, preOp, stack = 0, '+', [] for i in range(len(s)): if s[i].isdigit(): num = num * 10 + int(s[i]) if s[i] in '+-*/' or i == len(s) - 1: if preOp == '+': stack.append(num) elif preOp == '-': stack.append(-num) elif preOp == '*': stack.append(stack.pop() * num) else: stack.append(int(stack.pop() / num)) num = 0 preOp = s[i] return sum(stack) import unittest class TestCalculate(unittest.TestCase): def test_calculate(self): self.assertEqual(calculate('3+2*2'), 7) self.assertEqual(calculate(' 3/2 '), 1) self.assertEqual(calculate(' 3+5 / 2 '), 5) if __name__ == '__main__': unittest.main()
4618a34103ccc6d6e29577301c13e1f8a515dca3
vinhnh1905/pythonProject
/Cicrle Measurements.py
205
4.28125
4
import math r = float(input("Enter the radius of the circle: ")) Area = math.pi*r**2 Circumference = 2*math.pi*r print("area: %s circumfernce: %s" % (Area,Circumference)) #test github #haha print("Hello")
1799ad9e80b16702b476933420606df9f394a435
edmond-chu/OldStuff
/Python/3-starter-files/student_solution.py
507
3.625
4
# Change this file's name to "solution.py" before submitting. # Implement a basic calculator to evaluate a simple expression string. # The expression string contains only non-negative integers, +, -, *, / operators and empty spaces. # The integer division should truncate toward zero. # Make sure to follow order of operations! # Note: # You may not assume that the given expression is always valid. (Return 0 if not valid) # Do not use the eval built-in library function. def calculate(s: str) -> int:
a0f4ca972fae8b87d46a1f76249416b61545e138
gabrielbodrug/python
/oop/функциональное.py
375
4.03125
4
a = input('a: ') def culc(a, b, action): if action == '+': return int(a) + int(b) elif action == '-': return int(a) - int(b) elif action == '*': return int(a) * int(b) elif action == '/': return int(a) / int(b) b = input('b: ') action = input('action: ') answer = culc(a, b, action) print(answer)
39bb034453091c4474de4a592f2a1d03fa725415
StudyForCoding/BEAKJOON
/21_DivdeConquer/Step08/wowo0709.py
1,144
3.640625
4
''' 피보나치의 수열을 분할 정복으로 빨리 풀려면 행렬의 거듭제곱을 이용하면 된다. [[Fn+1,Fn],[Fn,Fn-1]] = [[F2,F1],[F1,F0]]^n = [[1,1],[1,0]]^n ''' import sys input = sys.stdin.readline div = int(1e9+7) def find_power(matrix, power): # 행렬곱을 분할 정복으로 나누기 if power == 1: return matrix if power % 2 == 0: tmp_mat = find_power(matrix,power//2) return MatMul(tmp_mat,tmp_mat) else: tmp_mat = find_power(matrix,power-1) return MatMul(tmp_mat,matrix) def MatMul(matrix1,matrix2): # 행렬곱 계산 # [[0]*N]*N 로 하면 리스트가 공유되서 다른 결과가 나옴 res_mat = [[0 for _ in range(N)] for _ in range(N)] for x in range(N): for y in range(N): for z in range(N): res_mat[x][z] += matrix1[x][y] * matrix2[y][z] for x in range(N): for y in range(N): res_mat[x][y] %= div return res_mat n = int(input()) fibonacci_mat = [[1,1],[1,0]] N = len(fibonacci_mat) answer = find_power(fibonacci_mat,n) print(answer[0][1]%div)
faa88213f394ac8aaa6fe174795f9d70fe809292
darksugar/pythonProjects
/day05/Calculater/re mod.py
3,097
3.6875
4
#Authon Ivor def addition(a): return str(round(float(a[0].strip())+float(a[1].strip()),5)) def subtraction(a): return str(round(float(a[0].strip())-float(a[1].strip()),5)) def multiplication(a): return str(round(float(a[0].strip())*float(a[1].strip()),5)) def division(a): return str(round(float(a[0].strip())/float(a[1].strip()),5)) import re import datetime num = ''' 请输入运算式: 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) >>> ''' a = input(num) begin_time = datetime.datetime.now() a = a.replace(" ","") while True: b = re.search(r'\([^()]+\)',a) print(b) if b: c = re.search('\d+\.?\d*/(\+|\-)?\d+\.?\d*',b.group()) if c: d = division(c.group().split("/")) a = a.replace(c.group(),d) continue c = re.search('\d+\.?\d*\*(\+|\-)?\d+\.?\d*',b.group()) if c: d = multiplication(c.group().split("*")) a = a.replace(c.group(),d) continue c = re.search('\d+\.?\d*\-\d+\.?\d*',b.group()) if c: d = subtraction(c.group().split("-")) a = a.replace(c.group(),d) continue c = re.search('\d+\.?\d*\+\d+\.?\d*',b.group()) if c: d = addition(c.group().split("+")) a = a.replace(c.group(),d) continue c = re.search('\d+\.?\d*(\+|\-){2}\d+\.?\d*',b.group()) if c: if "+-" in c.group(): a = a.replace(c.group(),c.group().replace("+-","-")) if "--" in c.group(): a = a.replace(c.group(),c.group().replace("--","+")) if "-+" in c.group(): a = a.replace(c.group(),c.group().replace("-+","-")) if "++" in c.group(): a = a.replace(c.group(),c.group().replace("++","+")) continue if b and not c: a = a.replace(b.group(),b.group().strip("()")) continue else: if "+-" in a: a = a.replace("+-","-") if "--" in a: a = a.replace("--","+") if "-+" in a: a = a.replace("-+","-") if "++" in a: a = a.replace("++","+") b = re.search('\d+\.?\d*/(\+|\-)?\d+\.?\d*', a) if b: c = division(b.group().split("/")) a = a.replace(b.group(),c) continue b = re.search('\d+\.?\d*\*(\+|\-)?\d+\.?\d*',a) if b: c = multiplication(b.group().split("*")) a = a.replace(b.group(),c) continue b = re.search('\d+\.?\d*\-\d+\.?\d*', a) if b: c = subtraction(b.group().split("-")) a = a.replace(b.group(),c) continue b = re.search('\d+\.?\d*\+\d+\.?\d*', a) if b: c = addition(b.group().split("+")) a = a.replace(b.group(),c) continue print(a) end_time = datetime.datetime.now() print("use %s" % (end_time-begin_time)) print(begin_time,end_time) exit()
6d1377d2a0b663e0cf029d52c5a0eb97dc2890a4
Flyeater/osinttools
/aopy/tweet_downloader_full.py
1,811
3.59375
4
''' Script from Justin Seitz's https://learn.automatingosint.com/ Course and Modified for Python 3 by Micah Hoffman ''' from twitter_keys import * import json import requests import time # # Download Tweets from a user profile # def download_tweets(screen_name, number_of_tweets, max_id=None): api_url = '%s/statuses/user_timeline.json' % base_twitter_url params = { 'screen_name': screen_name, 'count': number_of_tweets, } if max_id is not None: params['max_id'] = max_id # send request to Twitter response = requests.get(api_url, params=params, auth=oauth) if response.status_code == 200: tweets = json.loads(response.content) return tweets return None # # Takes a username and begins downloading all Tweets # def download_all_tweets(username): full_tweet_list = [] max_id = None oldest_tweet = {} # loop to retrieve all the Tweets while True: # grab a block of 200 Tweets tweet_list = download_tweets(username, 200, max_id) # if we didn't get any tweets, we are done if tweet_list is None or len(tweet_list) == 0: break # grab the oldest Tweet oldest_tweet = tweet_list[-1] full_tweet_list.extend(tweet_list) # set max_id to latest max_id we retrieved, minus 1 max_id = oldest_tweet['id'] - 1 print('[*] Retrieved: %d Tweets (max_id: %d)' % (len(full_tweet_list), max_id)) # sleep to handle rate limiting time.sleep(3) # return the full Tweet list return full_tweet_list full_tweet_list = download_all_tweets('jms_dot_py') # loop over each Tweet and print the date and text for tweet in full_tweet_list: print('%s\t%s' % (tweet['created_at'], tweet['text']))
d37550e4e167b5e2839c740f25138bb6047903a9
timsergor/StillPython
/176.py
1,578
3.671875
4
# 130. Surrounded Regions. Medium. 24%. # Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. # A region is captured by flipping all 'O's into 'X's in that surrounded region. class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: None Do not return anything, modify board in-place instead. """ if len(board) == 0: return [] def capture(point, S1, S2): if board[point[0]][point[1]] == S1: board[point[0]][point[1]] = S2 for i in range(-1,2): for j in range(-1,2): if abs(i + j) == 1 and point[0] + i >= 0 and point[0] + i < len(board) and point[1] + j >= 0 and point[1] + j < len(board[0]): capture((point[0] + i, point[1] + j), S1, S2) for i in range(len(board)): capture([i,0],"O","I") capture([i,len(board[0]) - 1],"O","I") for i in range(1,len(board[0]) - 1): capture([0,i],"O","I") capture([len(board) - 1,i],"O","I") for i in range(1,len(board) - 1): for j in range(1,len(board[0]) - 1): capture([i,j],"O","X") for i in range(len(board)): capture([i,0],"I","O") capture([i,len(board[0]) - 1],"I","O") for i in range(1,len(board[0]) - 1): capture([0,i],"I","O") capture([len(board) - 1,i],"I","O") return board
f5578488f88e81f1df0685930aabcac7694a4882
aatul/Python-Workspace
/017_List.py
725
4.4375
4
# define a list list1 = ["Java","C","CPP","Android","HTML","Dart","Go"] print(list1) # print whole list print(list1[1]) # prints 1st element # print the number of items in list i.e. length print(len(list1)) list1[2]="HTML" # replace element from given index no. print(list1) # printing list with for loop for x in list1: print(x) # check if item exists if "Android" in list1: print("Yes, 'Android' is in the list") # Add item or append an item in list list1.append("Python") print(list1) # Insert an item as the given position list1.insert(1, "R") print(list1) # reverse a list list1.reverse() print(list1) # find index of item specified x = list1.index("Python") print(x)
f3c1fc75fa71ce8229ba98f7ee22a02cafdaae70
rupertbauernfeind/aiml
/PA1/AIML_PA1_3.py
733
3.921875
4
def main(): try: arr = stringToAsciiArr(input()) bubbleSort(arr) except EOFError: return def stringToAsciiArr(string): return [ord(c) for c in string] def asciiArrToString(asciiArr): return ''.join(chr(i) for i in asciiArr) def bubbleSort(arr): if len(arr) == 1: print(asciiArrToString(arr)) while True: swapped = False for i in range(1, len(arr)): if arr[i - 1] > arr[i]: buff = arr[i] arr[i] = arr[i - 1] arr[i - 1] = buff swapped = True if not swapped: break else: print(asciiArrToString(arr)) if __name__ == "__main__": main()
d25e6c0fe7feb43b0fc38761f502583ef2e8fb0d
anyone21/Project-Euler
/gallery/Interesting-number-games/Problem-74.py
1,813
3.625
4
# -*- coding: utf-8 -*- """ Created on Sun May 8 17:41:48 2016 @author: Xiaotao Wang """ """ Problem 74: The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? """ import math def facsum(num): strnum = str(num) Sum = 0 for d in strnum: Sum += math.factorial(int(d)) return Sum def count_chains(chainLen = 60, maxnum = 10**6): cache = {} count = 0 for start in range(2, maxnum): if start in cache: if cache[start] == 60: count += 1 continue tmpdict = {} reverse = {} cur = start tick = 1 while not cur in tmpdict: tmpdict[cur] = tick reverse[tick] = cur cur = facsum(cur) tick += 1 for i in range(1, tmpdict[cur]+1): cache[reverse[i]] = tick - i if cache[start] == 60: count += 1 return count if __name__ == '__main__': count = count_chains() # ~1min 8s
67275a159f8e991bc19a967394a221b6831b7602
oursoul/python-demo
/第7章/test_1.py
325
3.8125
4
def minimal(x, y): #自定义计算较小值函数 if x > y: #如果x>y成立,返回y的值 return y else: #否则返回x的值 return x #用来测试 if __name__ == '__main__': #识别当前的运行方式 r = minimal(2,3) print('测试2和3的较小值为:',r)
d8ead4e2a30b8f7632a6f32819d8c02c8dbd541d
Sinha123456/Simple_code_python
/reverse_word.py
376
4.09375
4
'''def reverse(s): if len(s) == 0: return s else: return reverse(s[1:]) + s[0] s = "Geeksofgeeks" print(reverse(s))''' '''def reverse(str): str = str[::-1] return str sent = "My name is neetu, try to print reverse string" print(reverse(sent))''' def reverse(str): str = "".join(reversed(str)) return str print(reverse("coding is fun"))
34dc30239b80d5154661aef3a96bf9ae7e7e54d9
whywhyy/summer-code-jam-2020
/prickly-pufferfish/python_questions/zig_zag.py
851
4.03125
4
""" A sequence of integers is called a zigzag sequence if each of its / elements is either strictly less than both neighbors / or strictly greater than both neighbors. / For example, the sequence / 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2 and 3 8 6 4 5 aren't. / Write a function witch takes an array of integers and returns the length of / its longest contiguous sub-array that is a zigzag sequence. / Example / For a = [9, 8, 8, 5, 3, 5, 3, 2, 8, 6], the output should be / zigzag(a) = 4. / The longest zigzag sub-arrays are[5, 3, 5, 3] / and [3, 2, 8, 6] and they both have length 4. / - - - - - - - - - - - - - - - - - - - - - - - - / >>> zigzag([9, 8, 8, 5, 3, 5, 3, 2, 8, 6]) / 4 / >>> zigzag([2, 3, 1, 0, 2]) / 3 / >>> zigzag([1, 2, 3, 2, 1]) / 3 / >>> zigzag([2, 3, 1, 4, 2]) / 5 / >>> zigzag([1, 2, 0, 3, 2, 1, 3, 2, 4, 0]) / 6 / """
3dcb7f652c1f8a57fa6c4dcd389f6e74b682c22c
xDavidPM/Analisis-numerico-python
/lagrange.py
3,051
4.03125
4
#Super programa de Lagrange, simple y como si fuera poco multiple def main(): prueba = True while (prueba): print("LAGRANGE") print("seleccion (1) si desea usar Lagrange simple") print("seleccion (2) si desea usar Lagrange multiple:") opcion = int(input("")) if (opcion == 1 or opcion == 2): prueba = False if (opcion ==1): x=[] f=[] valor= 0 x,f,valor = Preparar_lagrange_simple() print print ("Su valor buscado es:") print (Lagrange(x,f,valor)) if (opcion == 2): x = [] y = [] f = [[]] valor1 = 0 valor2 = 0 x,y,f,valor1,valor2 = Preparar_lagrange_multiple() print print ("Su valor buscado de su interpolacion multiple es:") print (Lagrange_multiple(x,y,f,valor1,valor2)) def Lagrange(x,f,v): #Evaluar Lagrange pol = 0 for i in range(0,len(x)): L = 1 for j in range(0,len(f)): if (i != j): L = L*( (v-x[j]) /float(x[i] - x[j])) pol = pol + L*f[i] return pol def Lagrange_multiple(x,y,f,valor1,valor2): resul = [] pol = 0 for i in range(0, len(y)): r = 0 parte=[] for j in range(0,len(x)): parte.append(f[j][i]) r = Lagrange(x,parte,valor1) resul.append(r) pol = Lagrange(y,resul,valor2) return pol def Preparar_lagrange_multiple(): print ("Interpolacion de Lagrange multiple") print x = [] y = [] f = [[]] valor1 = 0 valor2 = 0 x = input("Ingrese los valores correspondientes de X separados por una coma:\n") y = input("Ingrese los valores correspondientes de Y separados por una coma:\n") f = input("Ingrese la matriz de variables dependientes, separandolos por parentesis y comas ejemplo: (3,4,5,8,7),(4,5,6,7),(5,6,7,8) continue :\n") valor1 = input("Ingrese el valor de interpolacion en X:\n") valor2 = input("Ingrese el valor de interpolacion en Y:\n") return x, y, f, valor1, valor2 def Preparar_lagrange_simple(): print ("Interpolacion de Lagrange simple") print x=[] f=[] valor = 0 x = input("Ingrese sus valores de X separados por comas:") print f = input("Ingrese sus valores de su funcion f(x) separados por comas:") print valor = input("Ingrese su valor a interpolar: \n") return x, f, valor if __name__ == "__main__": main() """ def denominador(x,f): deno = [] n = len(x) for i in range(0,n): den_parcial = 1 for j in range(0,n): if (j != i): den_parcial = den_parcial*(x[i] - x[j]) deno.append(den_parcial) return deno def numerador(x,f): num = [1] temp = 0 multi= 1 for i in range(0, len(x)): for j in range(1,len(x)): temp = temp - x[j] muti = multi*x[j] num.append(temp) num.append(multi) return num""" #print numerador(x,f)
5a847f022849fd0ee30304dd7a846b18494020ab
prabhuyellina/Assignments_Python
/assignments/vowel.py
166
4
4
def vowel_check(ch): list1=['a','e','i','o','u'] if ch in list1: return'True' return 'False' print vowel_check(raw_input('Enter the Character'))
ca9ae87f5c7130af1706f61c76f95951f3f660a7
firefly2442/ProjectEuler-python
/Problem112.py
737
3.75
4
def isBouncy(num): if len(str(num)) == 1: return False #check increasing increasing = True for i in range(0,len(str(num))-1): if int(str(num)[i]) < int(str(num)[i+1]): increasing = False break #check decreasing decreasing = True for i in range(0,len(str(num))-1): if int(str(num)[i]) > int(str(num)[i+1]): decreasing = False break if not increasing and not decreasing: return True else: return False bouncy_count = 0 tried_count = 0 while True: if isBouncy(tried_count): bouncy_count += 1 if float(bouncy_count)/float(tried_count) >= 0.99: break tried_count += 1 print "Bouncy count: ", bouncy_count print "Tried count: ", tried_count print "Ratio: ", float(bouncy_count)/float(tried_count)
4fb6e712c563b29f587a72a807e30f90de647be0
sandy1312/Fibonacci-series
/fibonacci.py
168
3.828125
4
n=int(input("Enter ur number:")) a=-1 b=1 if n<=0: print("No output") else: for i in range(n): c=a+b a,b=b,c print(c,end=" ")
903d8222654e4e843cc572685f5d239ccea3b5b3
ferrerinicolas/python_samples
/5.2 For loopss/5.2.4 Printing 10 Numbers Part2.py
110
3.9375
4
""" This program prints the numbers 1 though 10. We decided the range """ for i in range(1, 11): print(i)
6895badf0b35be4115638dd95915c16a1ee43f8d
code-drops/data-structures-algorithms
/python/graphs/adjacency matrix.py
593
3.796875
4
class Graph: def __init__(self,size): self.matrix = [] for i in range(size): self.matrix.append([0 for i in range(size)]) self.size = size def add_edge(self,v1,v2): self.matrix[v1][v2] = 1 def remove_edge(self,v1,v2): self.matrix[v1][v2] = 0 def printGraph(self,matrix): for row in matrix: for col in range(len(row)): print(row[col],end=' ') print() g = Graph(3) g.add_edge(0,1) g.add_edge(1,0) g.add_edge(2,1) g.add_edge(0,0) g.printGraph(g.matrix)
3fe66651dd3e0b87e315c401bbfe72f7a8f59e75
Nanko-Nanev/python_advanced
/8_multidimensional_lists_exercise/05_snake_moves.py
584
3.546875
4
from collections import deque (row, col) = [int(x) for x in input().split()] string_input = input() string = deque("") matrix = [] for _ in range(row): matrix.append([0] * col) while len(string) <= (row * col): string += string_input for r in range(row): for c in range(col): matrix[r][c] = string[0] string.popleft() for current_row in range(len(matrix)): if current_row % 2 == 1: matrix[current_row].reverse() else: pass for current_row in range(len(matrix)): print("".join(matrix[current_row]))
518113a96b21d94e0fcdb2dfdc30dda1bfe3db17
samir-0711/Leetcode-Python
/461. Hamming Distance.py
552
3.6875
4
import unittest class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ xor = x ^ y count = 0 for _ in range(32): count += xor & 1 xor = xor >> 1 return count class Test(unittest.TestCase): def test1(self): self.assertEqual(Solution().hammingDistance(1, 4), 2) def test2(self): self.assertEqual(Solution().hammingDistance(0, 0), 0) if __name__=="__main__": unittest.main()
b3c428042ac3e0039e26bada349b89888bbc44a2
VadimSquorpikkor/Python_Stepik
/1/1_12_week_exam/5_max_min.py
906
4.4375
4
# Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль # в три строки сначала максимальное, потом минимальное, после чего оставшееся число. # # На ввод могут подаваться и повторяющиеся числа. # # Sample Input 1: # 8 # 2 # 14 # # Sample Output 1: # 14 # 2 # 8 # # Sample Input 2: # 23 # 23 # 21 # # Sample Output 2: # 23 # 21 # 23 maxNum = int(input()) temp = int(input()) if temp > maxNum: minNum = maxNum maxNum = temp else: minNum = temp temp = int(input()) if temp > maxNum: midNum = maxNum maxNum = temp elif temp < minNum: midNum = minNum minNum = temp else: midNum = temp print(maxNum) print(minNum) print(midNum)
9ef323eb3bda856c5ac09fb984d169b704d76258
sarvparteek/Scientific_computation
/bracketingRootSearch2.py
951
3.8125
4
__author__ = 'sarvps' ''' Author: Sarv Parteek Singh Course: CS-600, Scientific Computation 1 HW: #5, Pr 5.4, 'Numerical methods for Engineers', 7th edition Brief: Root finding for a polynomial of degree 3 using bracketing methods ''' import _roots, _plot def f(x): return -12 - 21*x + 18*(x**2) - 2.75*(x**3) #Part(a): Two plots are generated: the first gives a holistic view and the second one a zoomed-in view _plot.graph(f, xl = -10.0, xu = 10.0, xlabel = 'x', ylabel = 'f(x)', title = 'Plot over wide range of x') _plot.graph(f, xl = -1.0, xu = 0.0, xlabel = 'x', ylabel = 'f(x)', title = 'Plot over a small range of interest of x') #Part (b) print("bisection:") _roots.bisect(f, xl = -1.0, xu = 0.0, es100 = 1.0, tv = -0.414689, debug = True) #tv obtained from graphical representation #Part(c) print("\nfalse position:") _roots.falsepos(f, xl = -1.0, xu = 0.0, es100 = 1.0, tv = -0.414689, debug = True) #tv obtained from graphical representation
cc027949a9f686d577c232ec662ee61bcb55889d
Zhuhh0311/leetcode
/array/majorityElement.py
2,589
3.53125
4
#给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 #你可以假设数组是非空的,并且给定的数组总是存在多数元素。 #最简单直接的想法,最开始解答忽略了数组长度为1的情况 #用时:268 ms 17.34% class Solution: def majorityElement(self, nums: List[int]) -> int: nums.sort() j=1 if len(nums) == 1: return nums[0] for i in range(len(nums)-1): if nums[i] == nums[i+1]: j += 1 if j > len(nums)/2: return nums[i] break else: j = 1 #184 ms, 在所有 Python3 提交中击败了97.67%的用户 #同样是先排序,然后如果出现次数超过n/2,则在数组的中间位置一定为要找的数 class Solution: def majorityElement(self, nums: List[int]) -> int: nums.sort() n = len(nums) // 2 return nums[n] #暴力解法,两层for循环嵌套,但是提交显示超出时间限制 时间复杂度O(n**2) class Solution: def majorityElement(self, nums: List[int]) -> int: n = len(nums) for i in range(n): c = 0 for j in range(n): if nums[i] == nums[j]: c += 1 if c > n/2: return nums[i] #利用哈希表,dic.get(i,0)即获得key为i的元素的value,如果值不在字典中返回default值 #48ms 击败 100% 方法对了简直是太快了 class Solution: def majorityElement(self, nums: List[int]) -> int: dic = {} set1 = set(nums) for i in nums: dic[i] = dic.get(i,0) + 1 for i in set1: if dic.get(i) > len(nums) // 2: return i #计数法,先set求集合,之后再使用list.count()函数计算出现次数 #40ms 击败100% class Solution: def majorityElement(self, nums: List[int]) -> int: set1 = set(nums) for i in set1: if nums.count(i) > len(nums) // 2: return i #摩尔投票法 抵消的思想 #188ms class Solution: def majorityElement(self, nums: List[int]) -> int: count = 1 n = len(nums) target = nums[0] for i in range(1,n): if nums[i] == target: count += 1 else: if count >= 1: count -= 1 else: target = nums[i] return target
26ce9e1e423de7d2d6c76937f40b22979caeb94e
xuyuchends1/python
/Fluent Python/6/6.3.py
2,099
4
4
from abc import ABC,abstractmethod from collections import namedtuple Customer=namedtuple('Customer','name fidelity') class LineItem: def __init__(self,product,quantity,price): self.product=product self.quantity=quantity self.price=price def total(self): return self.price*self.quantity class Order: def __init__(self,customer,cart,promotion=None): self.customer=customer self.cart=cart self.promotion=promotion def total(self): if not hasattr(self,'__total'): self.__total=sum(item.total() for item in self.cart) return self.__total def due(self): if self.promotion is None: discount=0 else: discount=self.promotion.discount(self) return self.total()-discount def fidelity_promo(order): """5% discount for customers with 1000 or more fidelity points""" return order.total() * .05 if order.customer.fidelity >= 1000 else 0 def bulk_item_promo(order): """10% discount for each LineItem with 20 or more units""" discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * .1 return discount def large_order_promo(order): """7% discount for orders with 10 or more distinct items""" distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * .07 return 0 def bast_promo(order): promos=[fidelity_promo,bulk_item_promo,large_order_promo] return max(promo(order) for promo in promos) joe = Customer('John Doe', 0) ann = Customer('Ann Smith', 1100) cart = [LineItem('banana', 4, .5), LineItem('apple', 10, 1.5),LineItem('watermellon', 5, 5.0)] Order(joe, cart, fidelity_promo) Order(ann, cart, fidelity_promo) banana_cart = [LineItem('banana', 30, .5), LineItem('apple', 10, 1.5)] Order(joe, banana_cart, bulk_item_promo) long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)] Order(joe, long_order, large_order_promo) o=Order(joe, cart, large_order_promo) bast_promo(o)
d8b147eb1071062406451ad9aecc7ccecb1f1948
adi0311/Data-Structures-and-Algorithms-in-Python
/Algorithms/kadanes_algorithm.py
456
4
4
#Kadane's Algorithm to calculate the maximum sum of the contiguous subarray of given array. def kadane(l): maxsum, cursum = l[0], l[0] for i in range(1, len(l)): cursum = max(cursum, l[i]+cursum) if cursum > maxsum: maxsum = cursum return maxsum n = int(input("Enter the size of the array: ")) l = list() print("Enter the array elements one by one") for i in range(n): l.append(int(input())) print(kadane(l))
02739c03106ec9796a0c8621884386d4302feace
omar00070/python_class
/game/game.py
1,570
3.625
4
import pygame import math backgound_color = (137, 223, 158) screen_width = 500 screen_height = 500 screen = pygame.display.set_mode((screen_width, screen_height)) screen.fill(backgound_color) run = True rect_color = (150, 150, 150) rectangle = (100, 45, 50, 50) grey = (150, 150, 150) class Mario: def __init__(self): self.x_pos = 150 self.y_pos = 50 self.height = 100 self.width = 100 self.color = grey def draw(self): rectangle = (self.x_pos, self.y_pos, self.width, self.height) pygame.draw.rect(screen, self.color, rectangle) def move_right(self): self.x_pos += 10 def move_left(self): self.x_pos -= 10 def jump(self): vel = 30 angle = math.pi/4 vel_x = int(vel * math.cos(angle)) vel_y = int(vel * math.sin(angle)) self.x_pos += vel_x self.y_pos += vel_y - 0.5 * 9.81 print(vel_x, vel_y) mario1 = Mario() while run: for event in pygame.event.get(): print(event) if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: pressed = pygame.key.get_pressed() if pressed[pygame.K_RIGHT]: if mario1.x_pos <= screen_width - mario1.width: mario1.move_right() if pressed[pygame.K_LEFT]: if mario1.x_pos >= 0: mario1.move_left() mario1.jump() screen.fill(backgound_color) mario1.draw() pygame.display.update()
5e7adf962352023c8db7af4b4a49467a58fab797
mahanghashghaie/rsp
/gen_rnd_password.py
3,786
3.53125
4
from bs4 import BeautifulSoup as bs import requests import re import sys import random import os import pyperclip def clean_html_tags(raw_html): """ cleanses a raw html string from html tags Parameters ---------- raw_html : str raw html string literal that is to be cleansed Returns ------- cleantext : str is the input string without html tags """ cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, '', raw_html) return cleantext def get_password_from_song_lyrics(num_of_pages, extra_text): """ generates password from song lyrics Parameters ---------- num_of_pages : int number of pages with song urls to be crawled extra_text : str string which will be appended to the extracted song lyrics Returns ------- password : str this is the stripped song lyrics appended with the extra_text """ content_list = get_content_overview_pages(num_of_pages) song_urls = extract_song_urls(content_list) rnd_index = random.randint(0,len(song_urls)-1) return extract_stripped_lyrics(song_urls[rnd_index]) + extra_text def get_content_overview_pages(num_of_pages): """ generates list of html documents Parameters ---------- num_of_pages : int number of pages with song urls to be crawled Returns ------- content_list : list contains the html source for the num_of_pages that have been crawled """ baseurl = "https://www.songtexte.de/songtexte.html" content_list = [] for i in range(num_of_pages): r = requests.get("https://www.songtexte.de/songtexte.html?seite={}".format(i+1)) content_list.append(r.text) return content_list def extract_song_urls(overview_content): """ extracts song lyric urls Parameters ---------- overview_content : list list of html document sources which contain song urls Returns ------- song_urls : list this is a list which contains all song lyric urls which can be found in overview_content """ song_urls = [] for page in overview_content: soup = bs(page, 'html.parser') for link in soup.findAll("div", {"class": "info"}): song_url = link.a.get("href") if song_url is not None: song_urls.append(song_url) return song_urls def extract_stripped_lyrics(song_url): """ extracts whitespace stripped song lyrics from url Parameters ---------- song_url : str url to the page which contains the song lyrics Returns ------- song_lyrics : str return the song lyrics stripped of whitespaces and cleansed from html tags """ r = requests.get(song_url) data = r.text soup = bs(data, 'html.parser') for link in soup.findAll("p", {"class": "lyrics"}): cleaned_content = clean_html_tags("".join(str(el) for el in link.contents)) return re.sub('\s+',' ',cleaned_content).replace(" ","") def main(): """ copies password to system clipboard Takes in command line arguments to generate the password and copy it to the clipboard. REMINDER: sys.argv[0] is always the script name. You should call this function as such: python3 gen_rnd_password.py 3 thisisappendedtotheoutput This call would take the song lyrics of the first 3 pages and then randomly select one of the songs to generate the password """ num_of_pages = 3 if len(sys.argv) > 1: num_of_pages = int(sys.argv[1]) extra_text = "no_extra_text" if len(sys.argv) > 2: extra_text = sys.argv[2] password = get_password_from_song_lyrics(num_of_pages, extra_text) pyperclip.copy(password) if __name__ == '__main__': main()
6d89392a11ae36d479965ad22d00582fd6949ee5
hassyGo/NLP100knock2015
/eriguchi/Chap1/chap1_4.py
1,346
3.75
4
#!/usr/bin/env python # coding: utf-8 """ 04. 元素記号 "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ. """ import re def match_word(p, word): w = p.match(word) term = w.group() return term def map_word(lst): dic = dict() # dictionary type num_lst = [1, 5, 6, 7, 8, 9, 15, 16, 19] # 1-origin for i, j in enumerate(lst): if (i+1) in num_lst: num_lst.remove(i+1) dic[j[0]] = i # 0-origin else: dic[j[0:2]] = i return dic def main(): p = re.compile("[a-zA-Z].*[a-zA-Z]") # the longest matching text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." print "Text: ", text word_lst = [match_word(p, i) for i in text.split()] # Only Alphabet map_dic = map_word(word_lst) # list -> dic print "Dictionary: ", map_dic if __name__ == "__main__": main()
74c11e761d9b7a08ef951a062ae9f5dfd956eb18
AllanBastos/Atividades-Python
/ESTRUTURA DE DADOS/Roteiro de revisão de Algoritmos/Distancia entre dois pontos.py
199
3.53125
4
x1, y1 = input().split() x2, y2 = input().split() x1, y1, x2, y2 = float(x1), float(y1), float(x2), float(y2) distancia = (((x2 - x1)**2) + ((y2 - y1)**2))**(1/2) print("{:.4f}".format(distancia))
2a08b7ea3fc08de983d5c2d4289f26973ab94132
tub212/PythonCodeStudy
/Python_Study/Lecture/Lecture_GCD_Large.py
180
3.90625
4
"""Lecture_GCD_Large""" def gcdlarge(num1, num2): """Return GCD number""" while num2 != 0: num1, num2 = num2, num1 % num2 print num1 gcdlarge(input(), input())
bd09f8848b1797dbcf64374e230893d4235daf40
netxeye/Python-programming-exercises
/answers/q20.py
1,432
3.953125
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from time import time def question20_devisable_by_7(end, start=0): ''' This function generator which uses for create iterate numbers, which are divisiable. paramater: start default value is 0 end the end of range, not included ''' item = start while item < end: if item % 7 == 0: yield item item += 1 def question20_devisable_by_7_1(end, start=0): ''' Testing while and range, I guess range would be faster than while loop ''' for item in range(start, end): if item % 7 == 0: yield item def question20_devisable_by_7_generator(end, start=0): ''' () could create gernerator. the way is same as list comperhensions looks like this way would be more effeiction ''' return (i for i in range(start, end) if i % 7 == 0) for i in range(20): print('the fist way by while') start_time = time() print(question20_devisable_by_7(1000)) print('---- %s seconds ----' % (time() - start_time)) print('the second way by () genterator') start_time = time() print(question20_devisable_by_7_generator(1000)) print('---- %s seconds ----' % (time() - start_time)) print('the third way, by using range and for') start_time = time() print(question20_devisable_by_7_1(1000)) print('---- %s seconds ----' % (time() - start_time))
83d85047200c71c9c040e6672c48cd82effb534d
ColdGrub1384/Pyto
/Pyto/Samples/SciKit-Image/plot_convex_hull.py
1,208
3.734375
4
""" =========== Convex Hull =========== The convex hull of a binary image is the set of pixels included in the smallest convex polygon that surround all white pixels in the input. A good overview of the algorithm is given on `Steve Eddin's blog <http://blogs.mathworks.com/steve/2011/10/04/binary-image-convex-hull-algorithm-notes/>`__. """ import matplotlib.pyplot as plt from skimage.morphology import convex_hull_image from skimage import data, img_as_float from skimage.util import invert # The original image is inverted as the object must be white. image = invert(data.horse()) chull = convex_hull_image(image) fig, axes = plt.subplots(1, 2, figsize=(8, 4)) ax = axes.ravel() ax[0].set_title('Original picture') ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_axis_off() ax[1].set_title('Transformed picture') ax[1].imshow(chull, cmap=plt.cm.gray) ax[1].set_axis_off() plt.tight_layout() plt.show() ###################################################################### # We prepare a second plot to show the difference. # chull_diff = img_as_float(chull.copy()) chull_diff[image] = 2 fig, ax = plt.subplots() ax.imshow(chull_diff, cmap=plt.cm.gray) ax.set_title('Difference') plt.show()
4b2e4ac2e4aeb16792faf04fbbd3a2b2e4e92de0
wilhelminayao/thinkful-porject
/tip_calculator/tip calculator.py
970
3.609375
4
from optparse import OptionParser parser = OptionParser() parser.add_option("-m", "--meal", dest="meal", type="float", help="price of meal") parser.add_option("-t", "--tax", dest="tax_percent", type="float", help="rate of the tax",default = 0.035 ) parser.add_option("-p", "--tip", dest="tip_percent", type="float",help="percent tip you want to leave") (options, args) = parser.parse_args() if not options.meal: parser.error("Please enter the price of meal") if not options.tip_percent: parser.error("Please leave tips") tax_value = options.meal * options.tax_percent meal_with_tax = tax_value + options.meal tip_value = meal_with_tax * options.tip_percent total = meal_with_tax + tip_value print "The initial price of the meal was ${0:.2f}.".format(options.meal) print "The tax is ${0:.2f} for tax.".format(tax_value) print "${1:.2f} tips you left".format(int(100*options.tax_percent), tax_value) print "The total of your meal is ${0:.2f}.".format(total)
24c59b14d7c211333587fb70e9e6fbae57c21454
sabbir421/python
/even & odd number from series .py
241
4.09375
4
print("*****if you want even value then take f=1 and if you want odd number then f=0 *******") i=int(input("starting value:")) n=int(input("ending value")) f=int(input("f")) while i<=n: i=i+1 if i %2==f: continue print(i)
5c8292c8f9ea5018f888e44262b46679e54e46bb
spaparrizos/Python
/formulas/temperature_trans.py
729
3.765625
4
#!/usr/bin/env python ######################################################### # Spyros Paparrizos # spipap@gmail.com # Temperature transformation ######################################################### # Python libraries import numpy as np, netCDF4, os, sys # Kelvin -> Celcius Kelvin = float(input("Temperature in Kelvin (K) : ")) Celsius = Kelvin - 273.15 print "Temperature in Kelvin (K):", Kelvin,"(K)","\nTemperature is Celsius degrees: ", Celsius, "(oC)" # Fahrenheit -> Celcius Fahrenheit = int(raw_input("Temperature is oF (F) : ")) Celsius = (Fahrenheit - 32) * 5.0/9.0 print "Temperature in Fahrenheit (F):", Fahrenheit,"(F)","\nTemperature is Celsius degrees: ", Celsius, "(oC)"
50fc1b291e015b386db47f9b2dae611fc3da6124
NipunCdev/Python_Basics
/Foundation Semester 1 - CW/DOC 333 Coursework report – 20200588/Question 2 .py
4,480
4.375
4
# Import math library for calculating Square import math # Creating Variables coefficientOfX2 = 0 coefficientOfX = 0 constantValue = 0 i = '' # Repatition Part while (i != 'X'): #to get only integer as user input. If you input string then you will get a error msg and program will start again while True: try: # Input Part - Get Input From User coefficientOfX2 = int(input("Enter the Coefficient Of X2\t: ")) coefficientOfX = int(input("Enter the Coefficient Of X\t: ")) constantValue = int(input("Enter the constant Value\t: ")) except ValueError: print("Integer Required!! Please Enter the Number Again") else: # Calculate the discriminant part of the quadratic equation partOfTheQuadraticEquation = coefficientOfX ** 2 - 4 * coefficientOfX2 * constantValue # Calculate and Display Roots only if partOfTheQuadraticEquation is equal to zero. if partOfTheQuadraticEquation == 0: # Output print("") print("The discriminant is zero -> There are two real identical roots") # Calculation to get Root Root_x = int(((-coefficientOfX) / (2 * coefficientOfX2))) # Output - if the input coefficient of X is possitive if coefficientOfX > 0: #ourput - if the coefficient of X2 is one if coefficientOfX2 == 1: print("") print("The roots of", "𝒙𝟐", "+", coefficientOfX, "𝒙", "+", constantValue,"= 0 are", Root_x, "and", Root_x) else: print("") print("The roots of", coefficientOfX2, "𝒙𝟐", "+", coefficientOfX, "𝒙", "+", constantValue, "= 0 are", Root_x, "and", Root_x) # Output - if the input coefficient of X is negative else: if coefficientOfX2 == 1: print("") print("The roots of", "𝒙𝟐", coefficientOfX, "𝒙", "+", constantValue, "= 0 are", Root_x, "and", Root_x) else: print("The roots of", coefficientOfX2, "𝒙𝟐", coefficientOfX, "𝒙", "+", constantValue,"= 0 are", Root_x, "and", Root_x) # Calculate and Display Roots only if partOfTheQuadraticEquation is greater than zero elif partOfTheQuadraticEquation > 0: # Output print("") print("The discriminant is grater than zero -> There are two real roots") # Calculation to get roots Root_x1 = int(((-coefficientOfX) + math.sqrt(partOfTheQuadraticEquation)) / (2 * coefficientOfX2)) Root_x2 = int(((-coefficientOfX) - math.sqrt(partOfTheQuadraticEquation)) / (2 * coefficientOfX2)) # Output - if the input coefficient of X is positive if coefficientOfX > 0: if coefficientOfX2 == 1: print("") print("The roots of", "𝒙𝟐", "+", coefficientOfX, "𝒙", "+", constantValue,"= 0 are", Root_x2, "and", Root_x1) else: print("") print("The roots of",coefficientOfX2, "𝒙𝟐", "+", coefficientOfX, "𝒙", "+", constantValue,"= 0 are", Root_x2, "and", Root_x1) # Output - if the input coefficient of X is negative else: #ourput - if the coefficient of X2 is one if coefficientOfX2 == 1: print("") print("The roots of", "𝒙𝟐", coefficientOfX, "𝒙", "+", constantValue, "= 0 are",Root_x2, "and", Root_x1) else: print("The roots of", coefficientOfX2,"𝒙𝟐", coefficientOfX, "𝒙", "+", constantValue, "= 0 are", Root_x2, "and", Root_x1) # Display the Message if partOfTheQuadraticEquation is less than zero else: print("") print("The discriminant is less than zero -> There are no real roots") i = input("Enter 'X' to exit / or press any key to continue the program again ") if i == 'X': break print("Your input:", i) print("The Program Is End")
a22ba9ca0f581d749ae03cf594258ce33ce4950f
PriyankaMN/OPENCV
/OPENCV/1_first_trial.py
622
3.53125
4
import numpy #library for high level mathematical function import cv2 #open cv img=cv2.imread('a.png') #reading a image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #gray scale convertion retval2,thresh1 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) #binary convertion retval2,thresh2 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV) cv2.imshow('col',img) #display image cv2.imshow('gray',gray) #cv2.imshow('1',thresh2) cv2.imshow('bin',thresh1) cv2.waitKey(0) #keyboad input from user cv2.destroyAllWindows() # destroys all windows created
455a92d13de2dcdfac4903783cf1151ffb9e5ff2
jamilcse13/python-and-flask-udemy
/22. lambdaFunction.py
587
4.3125
4
#Function definition is here sum = lambda arg1, arg2 : arg1 + arg2 # Now you can call sum as a function print("Value of total: ", sum(10,20)) print("Value of total: ", sum(20,20)) input() # Return Argument def sum(arg1, arg2): "Add both the parameters and return them" total = arg1+arg2 print("Inside the function: ", total) return total # Now you can call the sum function total = sum(10,20) print("Outside the function : ", total) # Inside the function: 30 #Outside the function : 30 #without return total #Inside the function: 30 #Outside the function : None