blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
c16c1ee60da5e0e32d9076c31317159d6435e83c
daniel-reich/ubiquitous-fiesta
/n3zH5NvzPXb2qd5N5_19.py
169
3.640625
4
def how_mega_is_it(n): import math if abs(n) < 100: return "not a mega milestone" else: k = int(abs(n)) return (len(str(k))-2)*"MEGA " + "milestone"
b8a164094d5ae3a8140d8cb301e98fa714a0f48e
Aasthaengg/IBMdataset
/Python_codes/p02546/s306222265.py
105
3.5625
4
S = input() n = len(S) S_a = list(S) if S[n-1] == 's' : print(S + 'es') else : print(S + 's')
d409f1faf2a568d79559ed06bcd317f17b78165f
Sanjay3234/PROJECT
/calculator.py
1,837
4.28125
4
# calculator project name=input("PLEASE ENTER YOUR NAME =") while name.isalpha()==False or len(name)<8 : if ' ' in name: break else: print("THE NAME YOU ENTERED IS INCORRECT") name=input("ENTER THE NAME AGEIN =") print("HELLO SIR ! NOW YOU CAN USE THE CALCULATOR FOR FOLLOWING OPERATIONS") print("Select the operation you want to perform") print("1.Add 2.Subtract 3.Multiply 4.Divide 5.Reminder 6.Quotient 7.Power") Choice=int(input("Enter your choice(1/2/3/4/5/6/7):")) if Choice == 1: num1 = int(input("Enter first number =")) num2 = int(input("Enter second number =")) sum=num1+num2 print("Sum of num1 and num2 =",num1+num2) elif Choice == 2: num1=int(input("Enter first number =")) num2=int(input("Enter second number =")) Difference=num1-num2 print("Difference of num1 and num2 =", num1 - num2) elif Choice == 3: num1=int(input("Enter first number =")) num2=int(input("Enter second number =")) Multiplication=num1*num2 print("Multiplication of num1 and num2 =", num1 * num2) elif Choice == 4: num1=int(input("Enter first number =")) num2=int(input("Enter second number =")) Divide=num1/num2 print("Division of num1 and num2 =", num1 / num2) elif Choice == 5: num1=int(input("Enter first number =")) num2=int(input("Enter second number =")) Quotiend=num1//num2 print("Quotient after dividing num1 and num2 =", num1 // num2) elif Choice == 6: num1=int(input("Enter first number =")) num2=int(input("Enter second number =")) Reminder=num1%num2 print("Reminder after dividing num1 and num2 =", num1 % num2) elif Choice == 7: num1=int(input("Enter first number =")) num2=int(input("Enter second number =")) power=num1**num2 print("Power of num1 by num2 =", num1 ** num2)
95af87d2f63c574d471565cf41e0875a48b0943b
simonmesmith/keras-lstm-boilerplate
/generator.py
3,928
3.59375
4
from __future__ import print_function import helper import modeller import numpy as np import random import sys def write(input_filename, output_filename, scan_length, output_length, creativity=0.2, epochs=25): # Set key variables. text = helper.get_text(input_filename) unique_strings = helper.get_unique_strings(text) unique_string_indices = helper.get_unique_string_indices(unique_strings) indices_unique_string = helper.get_indices_unique_string(unique_strings) model = modeller.get_model(input_filename, scan_length, epochs) # Create a function that returns a prediction from an array of predictions based on the specified "temperature." # This allows us to return a more or less creative (i.e. more or less probable) prediction. # To learn: Would like to have someone walk through each step of this function and what it's doing! def sample(predictions, temperature=1.0): predictions = np.asarray(predictions).astype('float64') # Converts the variable predictions to an array of type float64 predictions = np.log(predictions) / temperature # Converts the variable predictions to a logarithm of predictions divided by the temperature exp_predictions = np.exp(predictions) # Sets a variable to hold the exponential of predictions predictions = exp_predictions / np.sum(exp_predictions) # Sums array elements in the variable exp_predictions probabilities = np.random.multinomial(1, predictions, 1) # Sets a variable to sample from a multinomial distribution return np.argmax(probabilities) # "Returns the indices of the maximum values along an axis"; don't understand this fully # Create seed text and a generated_string variable to hold the generated string. random_start_index = random.randint(0, len(text) - scan_length - 1) # Sets the start index for the seed to a random start point with sufficient length remaining for an appropriate-length seed seed = text[random_start_index: random_start_index + scan_length] # Sets the seed, a string of scan_length length from the text that starts from the random start index variable generated_string = '' # Sets a generated_string variable to hold generated_string text # Generate text that's the output length (number of strings) specified for i in range(output_length): # Create an output of output_length length by looping that many times and adding a string each time # Vectorize the generated_string text. # To learn: Why do we set x[] = 1? Why does that 1 have a period following it? Assumption: one-hot encoding. x = np.zeros((1, scan_length, len(unique_strings))) # Set a variable to an array of the specified shape that will hold the generated_string text in vectorized form for t, char in enumerate(seed): # Loop through each character in the seed, with t as the character index and char as the character x[0, t, unique_string_indices[char]] = 1. # Append the character index from the seed (t) and the character index of the character to the variable x # Predict the next character for the seed text. predictions = model.predict(x, verbose=0)[0] # Set a variable to hold a prediction; x is the input data, verbosity of 0 to suppress logging next_index = sample(predictions, creativity) # Get the predicted next_index value from an array of predictions using the specified level of creativity next_string = indices_unique_string[next_index] # Set a next_string variable to an actual string using the inverse string indices variable # Add string to generated_string text. generated_string = generated_string + next_string # Create the seed for the next loop. seed = generated_string[-scan_length:] # Save outputs to file. text_file = open('outputs/' + output_filename, "w") text_file.write(generated_string) text_file.close()
1f870d7a38e67f27041d36bb40a22720fb3f6ffa
anurag5398/DSA-Problems
/Design/Singleton.py
893
3.625
4
#SINGLETON #__shared__ is a shared component for all instances #MONOSTATE class Test: __shared = dict() def __init__(self, word): self.__dict__ = self.__shared self.state = word def __number(self, temp): return temp no = 2213 def check(self): print(self.state) p1 = Test("abc") p2 = Test("xyz") print(p1.state, p2.state) print(p1._Test__shared) #FACTORY class CarType: def wheels(self): print("Has 4 wheels") class BikeType: def wheels(self): print("Has 2 wheels") class AutoType: def wheels(self): print("HAs 3 wheels") def factory(vehicle = "Car"): types = { "Car" : CarType, "Bike" : BikeType, "Auto" : AutoType } return types[vehicle]() car = "Car" c = factory(car) a = factory("Auto") b = factory("Bike") a.wheels() b.wheels() fn = "check"
ab27bbca60d4a4a184c731ac5095a801c9e1588e
MateuszLeo/AoC2019
/1/solution.py
477
3.640625
4
import os import math def part_1(mass: int) -> int: return math.trunc(mass / 3) - 2 def part_2(mass: int, result=0) -> int: value = part_1(mass) if value <= 0: return result return part_2(value, value + result) with open(f"{os.path.dirname(__file__)}/input.txt") as f: lines = f.readlines() p_1 = sum(part_1(int(line)) for line in lines) p_2 = sum(part_2(int(line)) for line in lines) print("part_1", p_1) print("part_2", p_2)
a8b7a32a82d992b28df61213dc57aff71d400938
ianzhang1988/PythonScripts
/algorithm/find_prime.py
1,392
3.90625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/6/23 21:03 # @Author : Ian.Zhang # @Email : ian.zhang.88@outlook.com # @File : find_prime.py import math def is_prime(i): sub_i = int(math.sqrt(i)) for j in range(2, sub_i + 1): if (i % j) == 0: return False return True def find_prime(n): for i in range(n): if is_prime(i): print(i) # find_prime(100) # https://stackoverflow.com/questions/453793/which-is-the-fastest-algorithm-to-find-prime-numbers # https://en.wikipedia.org/wiki/Sieve_of_Atkin # http://cr.yp.to/primegen.html # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes too much space def Sieve_of_Eratosthenes(limit): P = [2,3] sieve=[False]*(limit+1) for x in range(1,int(math.sqrt(limit))+1): for y in range(1,int(math.sqrt(limit))+1): n = 4*x**2 + y**2 if n<=limit and (n%12==1 or n%12==5) : sieve[n] = not sieve[n] n = 3*x**2+y**2 if n<= limit and n%12==7 : sieve[n] = not sieve[n] n = 3*x**2 - y**2 if x>y and n<=limit and n%12==11 : sieve[n] = not sieve[n] for x in range(5,int(math.sqrt(limit))): if sieve[x]: for y in range(x**2,limit+1,x**2): sieve[y] = False for p in range(5,limit): if sieve[p] : P.append(p) return P print(Sieve_of_Eratosthenes(100))
9a99a04a364ae01f34c406ea6f8c68aa56065afb
PhilomenaGMIT/Script-prog
/Labs/Topic03-variables/lab03.05-normalise.py
442
4.3125
4
#Program to take in a string, remove leading or trailing blanks, convert to lower case and output details inputstring = input('Please enter any string of characters: ') inlength = len(inputstring) outputstring = inputstring.strip().lower() inlength = len(inputstring) outlength = len(outputstring) print("That string normalised is {}".format(outputstring)) print("We reduced the length from {} to {} characters".format(inlength,outlength))
ab8ce2a6c417ae77110b19454325294aa91ea6dc
bcongdon/leetcode
/200-299/226-invert-binary-tree.py
1,065
3.828125
4
class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return self.invertTree(root.right) self.invertTree(root.left) root.left, root.right = root.right, root.left return root # Explanation # Pretty trivial, but I thought Max Howell's tweet was funny, so here # ya go. # Runtime - O(n) # Pretty clearly a traversal, so runtime will be O(n). We have to touch each # node in the tree exactly one time. # Space Complexity - O(n) # Using recursion, so at worst case we could have O(n) frames on the stack. # This could be done iteratively in O(1) space in the manner described below: from collections import deque def invertTreeIterative(self, root): to_be_swapped = deque([root]) while len(to_be_swapped) > 0: node = to_be_swapped.popleft() if not node: continue to_be_swapped.extend([node.left, node.right]) node.left, node.right = node.right, node.left return root
5cb9e761ff767010f4d6e56d45e0af4db13f5380
muralimohanreddy319/plagiarism
/CSPP1_2017_part-1_20176051-bagOfCodes.py
1,809
3.515625
4
'''bag of words''' import os import string '''function to calculate eucledian norm of vector of files''' def listsum(dic): k=0 for x in dic.keys(): k+=dic[x]**2 return k '''function to calculate word frequency of the files''' def wordfreq(l1): dic={} for i in range(len(l1)): c=0 for j in range(len(l1)): if(l1[i]==l1[j]): c+=1 dic[l1[i]]=c return dic dic1={};dic2={};s=0 a=[] b=[fname for fname in os.listdir(os.getcwd()) if fname.endswith('.txt')] for fname1 in b:#open the files in directory z=[] file1=open(fname1) f1=file1.read() f1=f1.lower() f1=f1.replace("\n"," ") l1=f1.split(" ") #convert the given file int list of words l1=[word.strip(string.punctuation)for word in l1] #remove the special characters #for i in fname: for fname2 in b:#take individual files from directory to compare if(fname1==fname2): z.append("null") else: f2=open(fname2) f2=f2.read() f2=f2.lower() f2=f2.replace("\n"," ") l2=f2.split(" ") l2=[word.strip(string.punctuation)for word in l2] dic1=wordfreq(l1)#calculate word frequency of file 1 if '' in dic1: del dic1[''] dic2=wordfreq(l2)#calclulate word frequency of file 2 if '' in dic2: del dic2[''] s=0 #To calculate dot product of the values of common words in both files. for x in dic1.keys(): for y in dic2.keys(): if(x==y): s+=dic1[x]*dic2[y] l1sum=0;l2sum=0 l1sum=listsum(dic1) #to calculate eucledian norm of vector of file1 l2sum=listsum(dic2) #to calculate eucledian norm of vector of file2 m=(l1sum**0.5)*(l2sum**0.5) #calculate percent of plagiarism percent=(s*100.0/m) percent=round(percent,4) z.append(percent) a.append(z) for i in a: print i
9178365000add62e5a0b697e3af7214154bd4d15
deronbrowne/Bookkeeper-Buddy
/input_check.py
1,261
3.609375
4
def check(level,prompt): a=['inventory', 'projects', 'restock', 'set goal', 'quit'] b=['create', 'edit', 'view', 'save & exit'] c=['add','change','delete','save & exit'] d=['inventory', 'items', 'done'] import My_Projects f=['items','overheads','hours','profit','done'] g=['yes','no'] h=['name','price'] import Inventory i=['name','quantity','price'] j=['date','time'] m=Inventory.inventory_record.keys() n=My_Projects.projects.keys() if level==1: options=a elif level==2: options=b elif level==3: options=c elif level==4: options=d elif level==6: options=f elif level==7: options=g elif level==8: options=h elif level==9: options=i elif level==10: options=j elif level==13: options=m elif level==14: options=n print ('\n') print ('\n'.join(options)) choice=str.lower(input(prompt + '\n' '\n')) while choice not in options: print ("Sorry, that isn't a valid choice. Try again.") print ('\n'.join(options)) print ('\n') choice=str.lower(input()) return choice
435d9b265adbb8f714504d3cf07ac232ffdbd5b8
Priti13pal/Codewayy_Python_Series
/Python_Task_5/Python_Task_5/mathSortFunction.py
870
4.25
4
# Math Function : import math num1 = -10 num2= 5 # returning the absolute value. print ("The absolute value of -10 is : ", end="") print (math.fabs(num1)) # returning the factorial of 5 print ("The factorial of 5 is : ", end="") print (math.factorial(num2)) # returning the ceil of -10 print ("The ceil of -10 is : ", end="") print (math.ceil(num1)) # Sort set : subjects = {'science', 'History', 'English', 'Reading'} subjects_sorted = sorted(subjects, reverse = True) print(subjects_sorted) # Sort List : numbers = [2, 8, 3, 1, 9] numbers_ascending = sorted(numbers) print(numbers_ascending) numbers_descending = sorted(numbers, reverse=True) print(numbers_descending) # Sort Tuple : subjects = {'science', 'History', 'English', 'Reading'} subjects_sorted = sorted(subjects, reverse = True) print(tuple(subjects_sorted))
3cef87b2c72426adb2b1bc3b1b237f731c6f00a1
luongnhuyen/luongnhuyen-labs-C4E17
/Lab01/search2.py
331
3.953125
4
nums = [3, 4, -99, 78, 4, -99, 3] x = int(input("Enter an integer: ")) # found= False # for num in nums: # if num == x: # found = True # break # if found: # print("Found") # else: # print("Not found") for num in nums: if num == x: print("Found") break else: print("Not found")
a76d4b8323d46274f839ecab576a5c425f1a2556
wangshaui123/cangku
/乘法口诀表.py
263
3.703125
4
i = 1 while i <= 9: j = 1 while j <= i: print('{}*{}={} '.format(i,j,i*j),end='') j += 1 print('') i += 1 for i in range(1,10): for j in range(1,i+1): print('{}*{}={} '.format(j,i,i*j),end='') print('')
924e4492b0557807f751a283e21f9cfb5f5780dd
harishv7/Python_Files
/Removes Vowels in a String.py
304
4.1875
4
def anti_vowel(text): vowels='aeiou' vowels_u=vowels.upper() str1 ='' str2='' str3='' for i in text: if i in vowels or i in vowels_u: str2 = str2 + i else: str1 = str1 + i for letter in str1: str3 = str3 + letter return str3
9aebd9d6d89db3189d74efc8b30fe72938f7d557
Saxena611/animesh_sde1_zelthy
/assignment_1/retrieve_validate_user_password.py
1,261
3.765625
4
import keyring class RetrieveUser: """ This simulates the login functionality verifies a registered user and matches password with one stored and allows user to login and send email. : param username: The email for which user has configured password. """ def __init__(self,i_username): self.i_username = i_username def validate_user(self): try: self.f = open('user_configation.txt',"r") li_user = self.f.read().split('\n') if self.i_username in li_user: print("Valid user.") return True print("User not registered. Please use the configure_user.py for registering gmail credentials safely.") return False except Exception as ex: print("Some problem in retrieving data ." + str(ex)) return False def fetch_password(self): if self.validate_user(): password = keyring.get_password(self.i_username,self.i_username) return password return None def validate_login(self,password2): curr_password = self.fetch_password() if password2.strip() == curr_password.strip(): return True return False
dc180bed0defa8aecbd3451ba66382ca151ee22a
Tansir93/PythonStudy
/PythonStudy/FirstPython/条件判断.py
704
4.3125
4
print("/n/n") print("~~~~~~~~~~~~~~~条件判断~~~~~~~~~~~~~~~~~~~") age = 20 if age >= 18:#根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print语句执行了 print('your age is', age) print('adult') age = 3 if age >= 18: print('your age is', age) print('adult') else: print('your age is', age) print('teenager') age = 3 if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid') print("/n/n") print("~~~~~~~~~~~~~~~input~~~~~~~~~~~~~~~~~~~") birth = input('birth: ')#input()返回的数据类型是str birth=int(birth)#int()把str转换成整数 if birth < 2000: print('00前') else: print('00后')
7e5fbbad584c339f5ad64362b0bf19c83ab56163
cmajorsolo/python-resharper
/divide_two_integers_test.py
1,199
3.6875
4
import unittest from divide_two_integers import Solution class divideTwoIntegersTest(unittest.TestCase): # def sample_test_1(self): # solution = Solution() # dividend = 13 # divisor = 3 # expected_result = 4 # actual_results = solution.divide(dividend, divisor) # self.assertEqual(expected_result, actual_results) # # def sample_test_2(self): # solution = Solution() # dividend = 7 # divisor = -3 # expected_result = -2 # actual_results = solution.divide(dividend, divisor) # self.assertEqual(expected_result, actual_results) # # def sample_test_3(self): # solution = Solution() # dividend = 18 # divisor = 3 # expected_result = 6 # actual_results = solution.divide(dividend, divisor) # self.assertEqual(expected_result, actual_results) def sample_test_4(self): solution = Solution() dividend = -1 divisor = 1 expected_result = -1 actual_results = solution.divide(dividend, divisor) self.assertEqual(expected_result, actual_results) if __name__ == '__main__': unittest.main()
48d8d9d7b4d843fd5b75518281080ff97729bf70
sbeaumont/fategenerator
/examples.py
3,844
4.40625
4
""" Examples of generators you can make with the tools. The expansion strings use a $[name_of_word_list] to randomly choose items from the word lists. This works recursively. If you have a word list with $[xxx] syntax in it, that will get expanded as well, so you can build more complex structures. You can use a | (the "or" sign) to have one expansion choose from multiple lists, so $[aaa|bbb] will give you one item from list aaa or list bbb. Adding a new list is really easy. All lists in the wordlists directory automatically get picked up. Just add a mynewlist.txt into the wordlists directory and refer to it in your expansion strings as $[mynewlist]. Wrap an expansion string in the lists.expand() (shorthand e()) function to let the generator do its magic. From that point you can get as creative as you want. This file shows some example uses. The Skillset and Character classes offer some intelligence in dealing with Fate characters and skill sets. The skills_modes.json and character_template.json files can be expanded with your own lists and templates. """ from random import choice, randint from wordlists import lists from skills import Skillset import string from character import character_templates, Character e = lists.expand # Create some zones, like a quick combat def zone(): return { 'name': lists.choice('zone'), 'aspects': [e(f"$[color] $[quality] $[material] {obj}") for obj in lists.sample('object_outside', 3)] } print("\nZones\n") for i in range(4): print(zone()) # Rube Goldberg machine generator print(e(f"\nRube Goldberg machine: The $[gadget]$[gadget]-{choice(string.ascii_uppercase)}{randint(1000, 9999)}\n")) for i in range(randint(5, 10)): print(e("$[color] $[material] $[object_outside|object_small] $[movement] $[direction]")) # A simple random town street generator: this one prints 5 to 10 stores. print("\nA Street\n") for i in range(randint(5, 10)): print(e("$[store]")) # NPC Maker print("\nSimple NPC") print(e("\n$[first_name_male|first_name_female] $[last_name]")) print(e("$[motivation] $[motivation] $[motivation]")) print(lists.sample('job'), Skillset.single_list(3)) print("\nAnother simple NPC, but with the more advanced +/- motivation generator") print(e("\n$[first_name_male|first_name_female] $[last_name]")) print(Character.motivations(3)) print(lists.sample('job'), Skillset.single_list(3)) # Generate one character for each archetype print("\nAn instance of each character template") for ct in character_templates: print(f"\n== {ct['name']} ==") print(Character.from_archetype(ct['name'])) # Convenient ways to create skill lists. # The "pyramid" creates a dictionary that collects all equal level skills together, indexed by skill level print("\nSingle skill list NPCs\n") print(lists.sample('job'), Skillset.single_list(3)) print(lists.sample('job'), Skillset.single_list(2)) print(lists.sample('job'), Skillset.single_list(1)) print("\nEasy ways to create skill pyramids\n") def_pyrmd = Skillset.default_pyramid() # Showing difference between flat list and pyramid version print(def_pyrmd.pyramid) print("(Flat list format)", def_pyrmd) print() print(Skillset.default_pyramid(3).pyramid) print(Skillset.default_pyramid(2).pyramid) print(Skillset.default_pyramid(1).pyramid) print(Skillset.single_list(2, "combat").pyramid) print("\nGenerate skill lists from Atomic Robo style modes\n") ss = Skillset.from_modes(["Action", "Automata", "Beast", "Hunter"]) print(f"Skillset: {ss}") print(f"Skillset pyramid: {ss.pyramid}") print("\nGenerate skill set from a combination of fixed skills and skill lists\n") pyramid_in = {3: ['combat', 'physical'], 2: ['Athletics', 'core'], 1: ['mental', 'Rapport', 'Fight', 'Drive']} ss2 = Skillset.from_pyramid(pyramid_in) print(f"Skillset {ss2.pyramid} from pyramid {pyramid_in}")
4a5d2461d230e6d46b000b0c5b223d7ad1801a7e
ManuBedoya/AirBnB_clone_v2
/web_flask/6-number_odd_or_even.py
1,541
3.5
4
#!/usr/bin/python3 """Modulo to find the flask """ from flask import Flask, render_template app = Flask(__name__) @app.route('/', strict_slashes=False) def index(): """The root of the page or index/default """ return 'Hello HBNB!' @app.route('/c/<text>', strict_slashes=False) def c_is(text): """Page to show the message C + a word in the url """ separate = text.split("_") return 'C {}'.format(' '.join(separate)) @app.route('/hbnb', strict_slashes=False) def hbnb(): """Page to show the message HBNB """ return 'HBNB' @app.route('/python/<text>', strict_slashes=False) def python_is(text="is cool"): """Page to show the message Python + a word or phrase in the url """ separate = text.split("_") return 'Python {}'.format(' '.join(separate)) @app.route('/number/<int:n>', strict_slashes=False) def is_number(n): """Page to show the message number + is a number """ return '{:d} is a number'.format(n) @app.route('/number_template/<int:n>', strict_slashes=False) def number_template(n): """Change the h1 tag with the number """ return render_template('5-number.html', number=n) @app.route('/number_odd_or_even/<int:n>', strict_slashes=False) def number_odd_or_even(n): """Change the h1 tag with the respecting information id is odd or even """ odd_even = 'even' if n % 2 == 0 else 'odd' return render_template('6-number_odd_or_even.html', number=n, odd_even=odd_even) app.run(debug=True, port=5000)
5b8e77097f03d94aaeb0c967ee21e0cdda55c422
johnprakashgithub/Learning
/python/crackit/nRoot.py
779
3.953125
4
class nRoot: def __init__(self,n): self.nthbase = float(1)/n def nRoot(self,number): print("The number {} and base {}".format(number,self.nthbase)) return(int(float(number) ** self.nthbase)) if __name__ == "__main__": sqrRt = nRoot(2) # for square root number=input("Enter the number to find square root : ") print("The squareroot of {} : {}".format(number,sqrRt.nRoot(number))) cubeRt = nRoot(3) # for cube root number=input("Enter the number to find cube root : ") print("The cuberoot of {} : {}".format(number,cubeRt.nRoot(number))) fourthRt = nRoot(4) # for fourth root number=input("Enter the number to find fourth root : ") print("The fourthroot of {} : {}".format(number,fourthRt.nRoot(number)))
463a51c308aacb61d17b62aca7c884fe840c7c17
Gaffey911/Gaffey
/oo-practice.py
986
3.5
4
class Role(object): def __init__(self,name): self.__name=name def getName(self): return self.__name def attack(self): return 0 class Magicer(Role): def __init__(self,name,level): super(Magicer,self).__init__(name) self.__level=level def getLevel(self): return self.__level def attack(self): return self.getLevel()*5 class Soldier(Role): def __init__(self,name,harm): super(Soldier,self).__init__(name) self.__harm=harm def getHarm(self): return self.__harm def attack(self): return self.getHarm() class Team(): l=[]*6 r=Role('') def addMember(self,r): self.l.append(r) return self.l def attackSum(self): sum=0 for i in self.l : sum=sum+i.attack() return sum a=Magicer('a',5) b=Soldier('b',50) print(a.attack()) print(b.attack()) t=Team() t.addMember(a) t.addMember(b) print(t.attackSum())
e90275623fa83438a8583c0569a5c7775f776c60
zabi-salehi/Coding-Problems
/Easy/Week 3/Project Rock Paper Scissors/rock_paper_scissors.py
345
3.5
4
''' Week 3 - Project Rock Paper Scissors @author: André Gilbert, andre.gilbert.77110@gmail.com Create a rock raper scissors mini-game. Implement a random function to generate rock, paper, or scissors. Implement a result function to declare the winner of the round. Implement a scorekeeper to keep track of the score. A game is won when the match score is: 2-0 or 2-1 '''
b3298d20ca9c979462c02764dfad0e7b0ab5c7f2
gavtoski/Data_Scraping_Basic
/Sample_Datascraping_CVS_att2.py
3,675
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 8 15:24:23 2020 @author: bin_h Data Scraping with Beautiful Soup based on Mr./Dr.? Phuc's guide with some modifications """ import bs4 from urllib.request import urlopen as uReq # Import stuff from urllib library from bs4 import BeautifulSoup as Soup # import BeautifulSoup and name it Soup import re def formaturl(url): if not re.match('(?:http|ftp|https)://', url): return 'http://cvs.com{}'.format(url) return url #Step 1: DOWNLOAD AND PARSE # define the url you want to scrape my_url = 'https://www.cvs.com/store-locator/cvs-pharmacy-locations/Colorado;jsessionid=VoD5BVVFRwudyOanePOv6Kt6w1DllckVoYTDb6WP' # Download your url's HTML file uClient = uReq(my_url) # Read your HTML file from the url page_html= uClient.read() uClient.close() # close the big HTML file to prevent scraping explosion #Parse the html, dissecting the code and assign meaning with BeautifulSoup # syntax is soup(filename, type to parse) # of course you have to define a variable to save the work after soup done parsing page_soup = Soup(page_html, "html.parser") #Step 2: EXTRACT THE ELEMENT OF INTEREST FROM THE HTML FILE # Soup sytax: object.findAll("hmtl tag category",{"tag subcategory":"tagname"}) # remember to save the container containers = page_soup.findAll("div", {"class":"states"}) container0 = containers[0].ul # After look at the HTML code, find the name of the graphics # card you want to use inside container # One needs to look at the actual html code for this # SYNTAX: object.tag.tag.tag.tag["attribute_name"] # "] # # Incase the previous syntax does not work, again use findAll href_loc_all = container0.findAll("a",href=True) # this is the list of all hyper links of CVS location in Colorado loc_num = len(href_loc_all) filename = "cvs_address.csv" f = open(filename,"w") #Write Header headers = "CVS_locations" f.write(headers) # Extract location one by one for ii in range(loc_num): href_loc_all0_raw = href_loc_all[ii] href_loc_all0 = href_loc_all0_raw['href'] # # add the http:// prepend to the url we just extracted loc_url0 = formaturl(href_loc_all0) # Extract store address from the second url uClient_loc0 = uReq(loc_url0) locpage_html = uClient_loc0.read() locpage_soup = Soup(locpage_html,"html.parser") add_container = locpage_soup.findAll("p",{"class":"store-address"}) store_loc = [] con_len = len(add_container) for jj in range(con_len) : store_loc = add_container[jj].text.strip() print(store_loc) f.write(store_loc + "\n") f.close # #!!!!!!!!!!! NOTE if object.div does not work use the find() filter # #Step 3: LOOP THROUGH ALL CONTAINERS and WRITE CSV FILE # filename = "" # f = open(filename,"w") # write command, w for write # #Write Header # headers = "brand, product_name, shipping" # f.write(headers) # for container in containers : # # Graphics card name # GPX_brand = container.div.div.a.img["title"] # # Extract name of the card # title_container = container.findAll("a",{"class":"item-title"}) # title = title_container[0].text # grab the text inside the cotainer # # Shipping # shipping_container = container.findAll("li",{"class":"price-ship"}) # ship_price = shipping_container[0].text.strip() # the strip() command removes space # print("brand: ",GPX_brand) # print("product_name:", title) # print("shipping", ship_price) # f.write(GPX_brand +"," + title + ","+ ship_price + "\n")
ead146c0e2ef523bd918c18966cbc7f2e0d5a885
crseiler/GraphCyclEDetection
/graph_detection.py
927
3.984375
4
"""Graph Class to create and identify vertices and edges. Additional method will be to identify if a graph is cyclic""" class Graph(object): def __init__(self, graph_array): """Initialize graph object""" self.__graph_array = graph_array def vertices(self): vertices = [] count = 0 for vertex in g: vertices.append(count) count += 1 return vertices """returns how many vertices are in graph""" return def edges(self): """returns the edges""" return self.generates_edges() def generates_edges(self): """generates the edges of graph""" return def is_cyclic(self): return if __name__ == "__main__": g = [[3],[2], [1,2,3,4], [2,3]] graph = Graph(g) print ("Name of all vertices:") print ','.join(map(str, (graph.vertices())))
cff8450446dad9e22aa0474a5a089e4e74c9f9d1
Ashutosh26121999/S_to_H_python_prog
/factorial.py
197
3.96875
4
def facto(i): if i == 0 or i == 1: return 1 else: return i * facto(i - 1) i = int(input("Enter the number")) print("given number {}! factorial is {}".format(i, facto(i)))
19471d795737e90876a117e5b4dfb185d8d04178
fduda/Intro_prog
/Semana 8/ex5/ngrams_rascunho3.py
1,080
3.53125
4
import copy def list_of_ngrams(text, n): lower_text = text.lower() lower_text = lower_text.strip() ngram_list = [] counter = 1 while counter <= n: temp_list = [] for i in range(len(lower_text)+1): temp_list.append(lower_text[i:i+counter]) ngram_list.append(temp_list) counter += 1 ngram_list = ngram_list[n-1] return ngram_list def remove_unwanted_characters(ngram_list): unwanted_characters = [".", ",", "!", "?", " ", "\n"] ngram_list_copy = copy.deepcopy(ngram_list) ngram_lenght = len(ngram_list_copy[0]) for ngram in ngram_list_copy: if len(ngram) != ngram_lenght: ngram_list.remove(ngram) for character in ngram: if character in unwanted_characters: ngram_list.remove(ngram) break return ngram_list f = open("english_1.txt", "r") text = f.read() f.close() ngrams_text = list_of_ngrams(text,2) print(remove_unwanted_characters(ngrams_text))
23e1359a2e0bb1fafe1c4ae4ed737ba1fb096430
Dragoshiz/tutorial
/homework.py
220
3.859375
4
age = int(input('Enter age: ')) if age == 5: print('Go to kindergarten you son of a bitch') elif age >= 6 and age <= 17: print("Go to grade 1 - grade 12") elif age >17: print("Go to epret szedni") else: print('Ense t
69813331b8892ddf90a9ef8dc474fd8fdf25cbef
PriyadarshiniSelvamani/LetsUpgrade-AI-ML
/Day 04/Day 04.py
1,595
4.3125
4
#!/usr/bin/env python # coding: utf-8 # In[7]: #Question 1 print("Floor division operator and modulo operator cannot be performed on complex numbers") a = 2+9j b = 7+8j print("Addition of two complex number is : ",a+b) print("Subtraction of two complex number is : ",a-b) print("Multiplication of two complex number is : ",a*b) print("Division of two complex number is : ",a/b) #print("Floor division of two complex number is : ",a//b) #print("Modulo of two complex number is : ",a%b) # #Question 2 # # *range()* **is a built-in function in python. It is used to generate a sequence of numbers within a given range. Depending # on the parameters passed user can decide where the series of number can begin as well as end.** # # # # In[8]: #example simple range function :range(stop) for i in range(10): print(i,end=" ") # In[9]: #example for range function with 2 parameters : range(start,stop) for i in range(10,20): print(i,end=" ") # In[11]: #example fr range function with 3 parameters : range(start,stop,step) for i in range (1,15,2): print(i,end=" ") # In[15]: #Question 3 a = 100 b = 50 subt = a-b print(subt) if subt > 25: print("Result of subtraction is greater than 25 so multiplication is",a*b) else: print("Result of subtraction is less than 25 so division is",a/b) # In[16]: #Question 4 lis = [10,56,89,42,90,46,92,12,57,49] for i in lis: if i%2==0: print("Result : ",i*i-2) # In[23]: #Question 5 lis1 = [6,49,8,12,14,20,4,17,20,28] for i in lis1: j = i/2 if j>7: print(i) # In[ ]: # In[ ]:
537ae40487fdda68dcec73089aec3b89d2da445d
akhiln007/python-repo
/censor.py
410
3.8125
4
def censor(text,word): length=len(word) astk='*' for j in range(length-1): astk=astk+'*' a=text.split() l=len(a) for i in range(l): if a[i]==word: a[i]=astk else: continue str1=' '.join(a) return str1 def main(): text=input("Enter the sentence:\t") word=input("Enter the word:\t") print(censor(text,word)) main()
f4cc13479cdbaec4c088f0f162905559c0e86987
MarcACard/python-exercises
/syntax_intro/count_up.py
279
4.21875
4
def count_up(start, stop): """Print all numbers from start up to and including stop. For example: count_up(5, 7) should print: 5\n 6\n 7\n """ for num in range(start, stop + 1): print(num) count_up(5, 7)
e5338664d66c7a53e05e5c87c6a70dd005d5822a
Ayush-Malik/PracAlgos
/search_an_element_in_a_sorted_and_pivoted_array.py
813
4.21875
4
# https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/ arr = list(map(eval , input().split(', '))) # Let's find the actual first index of rotated sorted array min_ele = arr[0] min_ele_index = 0 for i in range(1 , len(arr)): if arr[i] < min_ele: min_ele = arr[i] min_ele_index = i # print(f"{min_ele} : {min_ele_index}") def bin_search(ele , arr): first = 0 last = len(arr) - 1 while first <= last: mid = ((first + last) // 2) up_mid = (mid + min_ele_index) % len(arr) if ele == arr[up_mid] : return up_mid elif ele < arr[up_mid]: last = mid - 1 elif ele > arr[up_mid]: first = mid + 1 return -1 print(bin_search(int(input("Enter the element to be searched : ")), arr))
e2dac6a85a2df3c0a84dc66c33eb08fc2b96ae7b
liwaminaa/Hangman
/Hangman.py
689
4.09375
4
word=input("Type a word for someone to guess: ") word=word.lower() if(word.isalpha()== False): print("That's not a word!") guesses=[] maxfails=6 dash=[] print() print(len(word)) for x in word: dash.append("-") print(dash) print() guess=input("Guess a letter: ") for letter in word: if guess == letter: guesses.append(guess) print("correct") for letter in word: if guess != letter: guesses.append(dash) print("That's not right,try again") print() guess= input("Guess a letter:") listofguesses=[guess] print() for letters in guess: print(listofguesses) #dash= _ #dash * len(word) #print(dash) #dash.append() # print(dash)
72600febce0a07e6c48d9a67cf4b37f1da60542b
hunterkun/leetcode
/leetcode/python/15-Three-Sum.py
752
3.53125
4
''' 15. Three Sum ''' def threeSum(nums): counter = {} ret=[] for i in nums: if i not in counter: counter[i]=0 counter[i] += 1 if 0 in counter and counter[0] >= 3: ret.append((0, 0, 0)) nums2 = list(set(nums)) nums2.sort() for i in range(len(nums2)): if counter[nums2[i]] >= 2 and -2*nums2[i]!=nums2[i] and -2*nums2[i] in counter and counter[-2*nums2[i]]>0: ret.append((nums2[i], nums2[i], -2 * nums2[i])) for j in range(i + 1, len(nums2)): if - (nums2[i] + nums2[j]) in counter and counter[-(nums2[i] + nums2[j])] > 0 and - (nums2[i] + nums2[j]) > nums2[j]: ret.append((nums2[i], nums2[j], -(nums2[i] + nums2[j]))) return ret
f15d8cc70f83caf8a863c2073625cfe7fffd4783
zhzgithub/matplotlib
/animation_动画.py
517
3.59375
4
import matplotlib.pyplot as plt import numpy as np # from matplotlib import animation # animation:动画 import matplotlib.animation as ani fig,ax = plt.subplots() x = np.arange(0,2*np.pi,0.01) # 0~2*pi,步长为0.01的一维数组 line, = ax.plot(x,np.sin(x)) def animate(i): line.set_ydata(np.sin(x+i/10)) return line, def init(): line.set_ydata(np.sin(x)) return line, ani = ani.FuncAnimation(fig=fig,func=animate,frames=100,init_func=init,interval=20,blit=False) plt.show()
ac979d88dea900f071b64a8bd56350352c001735
Vaisvi/python-course
/basic/conditions.py
244
4.21875
4
a=10 if a>5: print("this is greater than 5") if a>15: print("this is greater than 15") if a==10: print("this is equal to 10") if a==5 or a<15: print("so this condition is true") print("any one of the is true")
4721af49ff4a0c115b91a520c230ba1ca85907a9
frasca17/pcs2-homework1
/Collections3.py
260
3.734375
4
from collections import namedtuple n = int(input()) columns = input() Student = namedtuple('Student', columns) students = [] for i in range(n): s = input().split() students.append(Student(*s)) print(sum([int(s.MARKS) for s in students])/len(students))
19e484e079e03dec0e5e4b303e90a103088cfd3e
radik2019/nkata
/Solve_For_X.py
4,076
3.609375
4
import re """ link: https://www.codewars.com/kata/59c2e2a36bddd2707e000079 kata's name: Solvwe For X """ # def solve_for_x(equation): # return equation # # print(solve_for_x('x - 5 = 20'), 25) # # print(solve_for_x('20 = 5 * x - 5'), 5) # # # def eq(es, es2=""): # dat1 = re.findall(r"[0-9x()+-/*=]", es) # es1 = re.findall(r"\d+|\D", "".join(dat1)) # if es1.index("=") == 1: # es2 = " ".join(es1[2:]) + " - " + es1[0] + " = 0" # elif es1.index("=") == len(es1) - 2: # es2 = " ".join(es1[:len(es1) - 2]) + " - " + es1[-1] + " = 0" # return es2 # # # def eq1(es): # df = eq(es).split(" ") # print(df) # return df.index("x") # # # def where(lst): # if lst.index("x") == 0: # if lst[lst.index("x") + 1] == "+": # print("plus") # elif lst[lst.index("x") + 1] == "-": # print("minus") # elif lst.index("x") != 0: # if lst[lst.index("x") + 1] == "+": # print(lst[lst.index("x") + 2:]) # return "plus" # elif lst[lst.index("x") + 1] == "-": # print(lst[lst.index("x") + 2:]) # return "minus" def numbers_to_float(lst): lst2=[] index = 0 if lst[0] == "-": lst2.append(float(lst[0] + lst[1])) index = 2 elif lst[0] != "-": lst2.append(float(lst[0])) index = 1 while index < len(lst): if lst[index] not in "-+*/": lst2.append(float(lst[index] + lst[index+1])) index += 2 elif lst[index] in "+-*/" and lst[index+1] == "-" : lst2.append(lst[index]) lst2.append(float(lst[index + 1] + lst[index + 2])) index += 3 elif (lst[index] in "+-*/") and (lst[index+1] != "-"): lst2.append(lst[index]) lst2.append(float(lst[index + 1])) index += 2 return lst2 def calc(stri1): dat1 = re.findall(r"[0-9()+-/*=.]", stri1) expr1 = re.findall(r"[0-9.]+|\D", "".join(dat1)) expr = numbers_to_float(expr1) while len(expr) > 1: if "*" in expr: first = expr[expr.index("*") - 1] second = expr[expr.index("*") + 1] for_paste = first * second expr[expr.index("*") - 1: expr.index("*") + 2] = [for_paste] elif "/" in expr: first = expr[expr.index("/") - 1] second = expr[expr.index("/") + 1] for_paste = first / second expr[expr.index("/") - 1: expr.index("/") + 2] = [for_paste] elif "+" in expr: first = expr[expr.index("+") - 1] second = expr[expr.index("+") + 1] for_paste = first + second expr[expr.index("+") - 1: expr.index("+") + 2] = [for_paste] elif "-" in expr: first = expr[expr.index("-") - 1] second = expr[expr.index("-") + 1] for_paste = first - second expr[expr.index("-") - 1: expr.index("-") + 2] = [for_paste] return expr[0] def remove_parenthese(math_expression): """ trasforma l'espressione racchiusa nelle parentesi, in ubn risultato ritornando lespressione senza parentesi """ dat1 = re.findall(r"[0-9()+-/*=.]", math_expression) math_expression = re.findall(r"[0-9.]+|\D", "".join(dat1)) start = "" stop = "" for i in range(len(math_expression)): if math_expression[i] == "(": start = i elif math_expression[i] == ")": stop = i break if start == "": return math_expression else: return ("".join(math_expression[:start]) + str(calc(''.join(math_expression[start+1 : stop]))) + ''.join(math_expression[stop + 1:])) def all_parenthes(math_expression): try: for i in range(math_expression.count("(")): math_expression = remove_parenthese(math_expression) return calc(math_expression) except TypeError: return "Espressione matematica errata" print(all_parenthes(input("----\t")))
4afe72fc9455242bc4a1a7878a48d6c8e536c3d7
eeee3/30-3-20
/2.py
166
3.859375
4
num=int(input("Ingrese su edad: ")) num1=1 contador=0 while num1<num: num1+=1 contador+=1 print("Desde 1 año hasta ", num, " hay ", contador, " años")
9dd17be8c183a2f9bdd7016ccabe51c1c95ec812
hooong/TIL
/algorithm/2/10.py
802
3.78125
4
# 스도쿠 검사 def is_correct(nums): for num in range(1,10): if not num in nums: return False return True sudoku = [] for _ in range(9): sudoku.append(list(map(int, input().split()))) # 각 행 검사 for r in range(9): row = sudoku[r] if not is_correct(row): print("NO") exit() # 각 열 검사 for c in range(9): col = [] for i in range(9): col.append(sudoku[c][i]) if not is_correct(col): print("NO") exit() # 각 사각형 검사 for r in range(3): for c in range(3): box = [] for i in range(r*3, r*3+3): for j in range(c*3, c*3+3): box.append(sudoku[i][j]) if not is_correct(box): print("NO") exit() print("YES")
4ea6dd9319f3bdbc82229f20e6dc6dc523ec035a
surajbnaik90/devops-essentials
/PythonBasics/PythonBasics/Iterators/iterator1.py
505
4.4375
4
#Create a list of items (you may use either strings or numbers in the list), #then create an iterator using the iter() function. #Use a for loop to loop "n" items, where n is the number of items in your list. #Each time round the loop, use next() on your list to print the next item. #hint: use the len() function rather than counting the number of items in the list. strings = ["B", "E" , "A" , "C" , "F" , "D"] iterator = iter(strings) for string in range(0,len(strings)): print(next(iterator))
655d25f4d87ab67db302f22df2b181003fd6e915
josdyr/exercism
/python/word-count/word_count.py
417
3.75
4
import re def word_count(phrase): phrase = phrase.lower() phrase = re.sub(r"[^a-zA-Z'\d]", " ", phrase) phrase = re.sub(r" '", " ", phrase) phrase = re.sub(r"' ", " ", phrase) phrase = phrase.split() phrase_list = {} for word in phrase: if word not in phrase_list: phrase_list.update({word: 1}) else: phrase_list[word] += 1 return phrase_list
2459b72991ac19ac275cd99e1015bfc8c59c5874
mottaquikarim/pydev-psets
/pset_classes/class_basics/p5.py
304
4.09375
4
""" Circle """ # Write a Python class named "Circle" constructed by a radius value and a class attribute for pi. You can use 3.14159 for the value of pi for simplicity. It should include two methods to calculate the "area" and the "perimeter" of a circle. Instantiate a Circle and call both methods.
ec560050a5c06cb68f4b040c24819a14ad813583
ahmedfadhil/PyTip
/maxHeap.py
1,014
3.984375
4
# Implementing maxheap algorithm # public functions: push, peek and pop # private functions: __swap, __floatUp, __bubbleDown class MaxHeap: def __init__(self, items=[]): super.__init__() self.heap = [0] for i in items: self.heap.append(i) self.__floatUp(len(self.heap) - 1) # Public functions def push(self, data): self.heap.append(data) self.__floatUp(len(self.heap) - 1) def pop(self): if len(self.heap) > 2: self.__swap(1, len(self.heap) - 1) max = self.heap.pop() self.bubbleDown(1) elif len(self.heap) == 2: max = self.heap.pop() else: max = False return max def peek(self): if self.heap[1]: return self.heap[1] else: return False # Non-public functions def __swap(self,i,j): pass def __floatUp(self,index): pass def __bubbleDown(self,): pass
12259a83f44714aec76262555c43a3dbba1f0823
pangfeiyo/PythonLearn
/甲鱼python/课程代码/第43讲/魔法方法:算术运算2.py
1,615
4.1875
4
class int(int): def __add__(self, oterh): return int.__sub__(self, oterh) a = int("5") print(a) b = int(3) print(b) print(a+b) # 反运算,加一个 r __radd__ # a + b ,当a的加法操作没有实现或不支持的时候,由b来执行加法操作 print("\n-- 反运算") class Nint(int): def __radd__(self, other): return int.__sub__(self, other) a = Nint('5') print(a) b = Nint(3) print(b) ''' 这里的print(a+b)结果为2,为什么不是正确答案8 因为上面的class int(int) 第一个int是类名,括号里的int是继承,类里的方法改变了int这个类型的加法运算。 而下面的Nint类也是继承int类型,因为在类int中已经改变了int类型的加法运算所以这里a,b=Nint(5,3) a+b不符合radd,采用add(被转为减法) ''' print(a+b) ''' 这里的print(1+b)结果为什么是2 1+Nint的时候,会按顺序执行数字1,加号,有Nint的数字,这时候发现Nint有radd,回去找第一个数字的add,没有,执行后面Nint的radd 变成3+1,因为3是Nint,继承了int类型,变成3-1 以上是个人理解,以下是ooxx7788的回复 是先看1有没有__add__,发现没有,那么执行的是Nint(3)的__radd__ 而Nint(3)的__radd__ 是int.__sub__(self,other)【因为继承了class int(int)】 self就是Nint(3),other就是1 ''' print(1+b) class Nint(int): def __rsub__(self, other): return int.__sub__(self, other) a = Nint('5') print(a) print(3-a) class Nint(int): def __rsub__(self, other): return int.__sub__(other, self) a = Nint('5') print(a) print(3-a)
c78034356fad8a43a1c2ff154edda8b4a46d5281
matias225/Computacion2
/ej4.py
475
3.515625
4
#!/usr/bin/python from os import fork, getpid, wait def main(): ret = fork() if(ret != 0): pid = getpid() for a in range(2): print("Soy el padre, PID "+str(pid)+", mi hijo es "+str(ret)) wait() print("Mi proceso hijo, PID "+str(ret)+" termino") else: childpid = getpid() for a in range(5): print("Soy el hijo, PID "+str(childpid)) print("PID "+str(childpid)+" terminando") main()
f5c2f364335639c35f22513542666fce260c66e1
edarakchiev/Modules
/01.calculate_logarithm.py
247
3.859375
4
from math import log def calculate_log(num, base): if base == "natural": return f"{log(num):.2f}" base = int(base) return f"{log(num, base):.2f}" number = int(input()) b = input() print(calculate_log(number, b))
d3716aa239928988cd8c3420687bb5ddec003320
ericxx1/Myraid
/tests/test.py
885
3.703125
4
from threading import Thread class i(object): pass i = i() i.i = 0; class Stack(Thread): def __init__(self): self.stack = {} def Add(self, statement): i.i +=1 self.stack[i.i] = statement def Select(self, x): return self.stack[x] def stmts(self): stack = {}; i = 0; for stmt in self.stack: i+=1 stack[i] = self.stack[i] return stack class Memory(Thread): def __init__(self): self.Collector = {} def Add(self, var_name, value): self.Collector[var_name] = value def Select(self, var_name): print self.Collector return self.Collector[var_name]; def VAR(*args): print args var_name = args[0] value = args[1] if not value.find('"') != -1: print "Var name: " + var_name print mem.Select(value) value = mem.Select(value) mem.Add(var_name, value) mem = Memory() mem.Add("dick", "dong") VAR("d", "dick") VAR("p", "d") print mem.Select("p")
83bc77fff1d6cc3d09f5e293eea4f2429c93dcb0
gabrielnavas/data_structure_and_algorithm_in_python
/opp/inheritance/database.py
1,971
3.5
4
class Database: def __init__(self): self.data = {} class ClientTable(Database): table_name = 'client' def insert_one(self, name): try: len_table = len(self.data[self.table_name]) + 1 new_client = {'id':len_table, 'name':name} self.data[self.table_name].append(new_client) except: new_client = {'id':1, 'name':name} self.data[self.table_name] = [new_client] def update_one(self, id, name): try: for client in self.data[self.table_name]: if client['id'] == id: client['name'] = name return True return False except: raise f'{id}, {name} not exists' def get_one(self, id): try: for client in self.data[self.table_name]: if client['id'] == id: return client except: return None return None def delete_one(self, id): try: for client in self.data[self.table_name]: if client['id'] == id: self.data[self.table_name].remove(client) return True except: raise f'{id} not exists' return False def get_all(self, id=None, name=None): try: if id and name: return [ client for client in self.data[self.table_name] if client['id'] == id and client['name'] == name ] if id and not name: return [ client for client in self.data[self.table_name] if client['id'] == id ] return [ client for client in self.data[self.table_name] if client['name'] == name ] except: raise f'{id} not exists' return []
39c93b4f200ea31a6aaf442490d802f07b74a971
lei-diva/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
238
4.0625
4
#!/usr/bin/python3 def uppercase(str): for letter in str: if ord(letter) >= 97 and ord(letter) <= 122: dif = 32 else: dif = 0 print("{:c}".format(ord(letter) - dif), end="") print()
b7ab08da2f79c2419645422a6de099e4cd1df741
manutdmohit/mypythonexamples
/pythonexamples/constructor2.py
306
3.96875
4
class Student: def __int__(self,name,rollno,marks): print('Creating instance variables and performing initialization...') self.name=name self.rollno=rollno self.marks=marks s1=Student('Ram',101,90) s2=Student('Sita',102,95) print(s1.name.s1.rollno,s1.marks) print(s2.name.s2.rollno,s2.marks)
97bc3bfde573f62922dec3d421f47dea846e7a4e
GradyLee/learn-python
/createcounter.py
666
3.953125
4
#!/usr/bin/env python3 # -*- coding utf-8 -*- ''' 利用闭包返回一个计数器函数,每次调用它返回递增整数 ''' def createCounter(): def auto_add(): n = 0 while True: n = n + 1 yield n x = auto_add() def counter(): return next(x) return counter if __name__ == "__main__": counterA = createCounter() print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5 counterB = createCounter() if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]: print('测试通过!') else: print('测试失败!')
7292e4e26b425a14869a5da8ac2bc9f836e0e0d9
loopDelicious/csinterviews
/cracking/arrays-strings/one_away.py
568
3.90625
4
"""there are 3 types of edits that can be performed on strings: insert a character, remove a character, or replace a character. given 2 strings, check if they are one edit (or zero edits) away. >>> one_away("pale","ple") True >>> one_away("pales","pale") True >>> one_away("pale","bale") True >>> one_away("pale","bake") False """ def one_away(str1, str2): """function to check if 2 strings are 1 (or less) edits away """ if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. WOOHOO!\n"
4ff9cbeb10f734170e2923956d5bf4646f3bcd1f
TaylenH/learningProjects
/Zenva/Python/VariablesAndOperators/PurchasingReceipt.py
1,256
3.828125
4
#Project printing out a receipt for store purchases made by a customer. #Showcases knowledge of variable assigning and mathmatic operators. #descripton and price of store items lovely_loveseat_description = ''' Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or white.''' lovely_loveseat_price = 254.00 stylish_settee_description = ''' Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28 inches deep. Black.''' stylish_settee_price = 180.50 luxurious_lamp_description = ''' Luxurious Lamp. Glass and iron. 36 inches tall. Brown with cream shade.''' luxurious_lamp_price = 52.15 sales_tax = .088 #customer one customer_one_total = 0 customer_one_itemization = "" #customer one purchases customer_one_total += lovely_loveseat_price customer_one_itemization += lovely_loveseat_description #customer one also buys Luxurious lamp customer_one_total += luxurious_lamp_price customer_one_itemization += luxurious_lamp_description #calculate tax customer_one_tax = customer_one_total * sales_tax customer_one_total += customer_one_tax #begin printing receipt print("Customer One Items:") print(customer_one_itemization) print("Customer One Total:") print(customer_one_total)
4dfae7405b59b54d8b94538f67cce274c76ffa9d
kaceyabbott/intro-python
/mydictionaries.py
1,736
3.734375
4
""" playing with dictionaries """ from pprint import pprint as pp def main(): """ test function :return: """ urls = { "google": "www.google.com", "yahoo": "yahoo.com", "twitter": "www.twitter.com", "wsu": "weber.edu" } print(urls,type(urls)) # access by key: [key] print(urls["wsu"]) #build dict with dict() constructor names_age = [('Alice',32),('mario',32),('hugo',21)] d = dict(names_age) print(d) #another way phonetic = dict(a = 'alpha', b = 'bravo', c = 'charlie', d = 'delta') print(phonetic) #make a copy e = phonetic.copy() print(e) #updating a dictionary update() stock = {'goog': 897, 'AAPL': 416, 'ibm':194} print(stock) stock.update({'goog':999, 'Yhoo':2}) print(stock) #iteration default is by key value for key in stock: print('{k} = {v}'.format(k = key, v = stock[key])) #iterate by values for val in stock.values(): print('val = ', val) #iterate by both key and value with: items() for items in stock.items(): print(items) for key, val in stock.items(): print(key, val) # test for membership in, not in via key print("goog" in stock) print("win" not in stock) #deleting: del keyworkd print(stock) del stock['Yhoo'] print(stock) #mutablility of dictionaries isotopes = { 'H': [1,2,3], 'He': [3,4], 'Li': [6,7], 'Be': [7,9,10], 'B': [10,11], 'C': [11,12,13,14] } pp(isotopes) isotopes['H'] += [4,5,6,7] pp(isotopes) isotopes['N'] = [13,14,15] pp(isotopes) if __name__ == '__main__': main() exit(0)
bb769498272a5af040aec697e04ccca40e19279a
clintonium-119/card_game
/board.py
9,333
3.796875
4
"""The highest level class in the game. the Board class is responsible for instantiating the players, guiding the active player's turn, drawing the active and inactive player's relevant information, and doing pretty much everything. The functionality that the Board class has is spread between a volume of smaller, more specific libraries for handling specific things""" import pygame from copy import copy import random from player import Player import deck import game_ui import click_hand_state import attacking_state import extra_options_lib import draw_enemy_lib import draw_player_lib import card_info_lib class Board(): # Method to initialize the gameboard and the players def __init__(self): self.game_board = pygame.image.load("background.bmp") self.game_board_rect = self.game_board.get_rect() self.button = None self.start_game_attr = False game_ui.screen.blit(self.game_board, (0,0)) pygame.display.set_caption("Card Game") # Highest level method in the Board class # Checks to see who is the active player and who is the enemy def play_game(self, screen_height, screen): self.start_game() self.draw_extra_options(screen) for index, player in enumerate(self.players): if player.active_player: enemy = self.players[int(not bool(index))] self.player_turn(screen, player, enemy) # High level method that defines the active player's turn def player_turn(self, screen, player, enemy): self.start_turn(screen, player, enemy) self.draw_player(player) self.draw_enemy(screen, enemy) card_info_lib.show_card_stats(self, screen, player) card_info_lib.expand_card(self, screen, player, enemy) self.check_guardian(enemy) self.button = self.get_event_button() self.right_click(game_ui.screen_height, game_ui.screen, player, enemy) self.click_hand(screen, player, enemy) if player.active_card_ix or player.active_card_ix == 0: click_hand_state.display_options(self, screen, player) click_hand_state.play_card(self, game_ui.screen_height, screen, player, enemy) click_hand_state.devote_card(self, game_ui.screen_height, screen, player, enemy) self.start_attack(game_ui.screen_height, game_ui.screen, player) if player.attacking_card: attacking_state.execute_attack(self, game_ui.screen_height, screen, player, enemy) attacking_state.attack_player(self, game_ui.screen_height, screen, player, enemy) attacking_state.animate_card(self, player) extra_options_lib.end_turn(self, player, enemy) extra_options_lib.extra_draw(self, screen, player, enemy) extra_options_lib.get_energy(self, screen, player, enemy) extra_options_lib.quit_game(self) self.end_game() # Function that only runs once at the beginning of the game def start_game(self): if self.start_game_attr == False: self.players = [] self.player_1 = Player("Player 1", "Ari", deck.player_1_deck, game_ui.screen) self.player_2 = Player("Player 2", "Coda", deck.player_2_deck, game_ui.screen) random.shuffle(self.player_1.deck) random.shuffle(self.player_2.deck) self.players.append(self.player_1) self.players.append(self.player_2) self.player_1.draw_starting_hand() self.player_2.draw_starting_hand(1) self.player_1.active_player = True self.start_game_attr = True # Collection of functions from the draw_player_lib responsible for drawing # the visual aspects of the player def draw_player(self, player): draw_player_lib.player_hand(self, game_ui.screen_height, player) draw_player_lib.player_battlefield(self, game_ui.screen_height, player) draw_player_lib.player_stats(self, player) # Collection of functions from the draw_enemy_lib responsible for drawing # the visual aspects of the enemy def draw_enemy(self, screen, enemy): draw_enemy_lib.enemy_battlefield(self, game_ui.screen_height, enemy) draw_enemy_lib.enemy_stats(self, enemy) draw_enemy_lib.show_enemy_stats(self, screen, enemy) # Draws all of the extra options for the player # Includes get energy, draw a card, end the turn, and attack enemy directly def draw_extra_options(self, screen): screen.blit(game_ui.energy, game_ui.energy_rect) screen.blit(game_ui.draw, game_ui.draw_rect) screen.blit(game_ui.next_turn, game_ui.next_turn_rect) screen.blit(game_ui.enemy, game_ui.enemy_rect) # A VERY important function that gets called very frequently to redraw # pretty much everything on screen. Any time anything on the board changes, # this function must be called def refresh_screen(self, screen, player, enemy): game_ui.screen.blit(self.game_board, (0,0)) self.draw_extra_options(screen) self.draw_player(player) self.draw_enemy(screen, enemy) card_info_lib.show_card_stats(self, screen, player) # A function for maintaining a player's upkeep when they start a new turn. # Draws them a card, refreshes their devotion pool, removes their limit # on devoting cards, wakes up any of their sleeping cards def start_turn(self, screen, player, enemy): if player.upkeep == False: player.devotion_pool = copy(player.devotion_total) extra_options_lib.draw_card(self, player) player.devotion_limit = 0 for card in player.battlefield: if card.first_turn: card.first_turn = False if card.attacked: card.attacked = False player.upkeep = True self.refresh_screen(screen, player, enemy) # Checks to see if the enemy has any guardian Characters in their battlefield. # If they do, it limits the options that the active player has in terms # of attacking def check_guardian(self, enemy): if enemy.battlefield == []: enemy.guardian = False else: for card in enemy.battlefield: if "guardian" in card.keywords: enemy.guardian = True elif "guardian" not in card.keywords: enemy.guardian = False # Checks for mouse clicks and keyboard presses def get_event_button(self): for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: return 1 elif event.button == 3: return 3 if event.type == pygame.QUIT: return "q" elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: return "q" # Right clicks are like state refreshers. If any state is active on a # player's turn, it cancels out those states and removes the click hand # options. def right_click(self, screen_height, screen, player, enemy): if self.button == 3: player.attacking_card = None player.active_card_ix = None screen.blit(game_ui.devote, (-300,-300)) screen.blit(game_ui.play, (-300, -300)) self.refresh_screen(screen, player, enemy) # If a card in your hand is clicked, this enters the click hand state def click_hand(self, screen, player, enemy): if self.button == 1: pos = pygame.mouse.get_pos() for index, card in enumerate(player.hand): if card.rect.collidepoint(pos): self.refresh_screen(screen, player, enemy) player.active_card_ix = index # If a card on the battlefield is clicked, if that card is awake, enters # the attacking state def start_attack(self, screen_height, screen, player): if self.button == 1: pos = pygame.mouse.get_pos() for card in player.battlefield: if card.rect.collidepoint(pos): if card.attacked == False: if card.first_turn == False: print("attack") player.attacking_card = card else: print("summoning sickness") else: print(f"{card.name} has already attacked this turn") # Function that ends the game. This is called when a player's health # is reduced to zero. def end_game(self): if self.player_1.life_total <= 0 or self.player_2.life_total <= 0: game_ui.screen.fill((0,0,0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit()
f72af081a2daa2a4545b54a652f140be8182cc26
bellos711/python_practice
/python/fundamentals/forloop_basic2.py
4,276
4.53125
5
import math # Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". # Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5] def biggie_size(arr): for i in range(0, len(arr)): if(arr[i] > 0): arr[i]="big" return arr print(biggie_size([-1,3,5,-5]),"\n\n") # Count Positives - Given a list of numbers, create a function to replace the last value with the number of positive values. # (Note that zero is not considered to be a positive number). # Example: count_positives([-1,1,1,1]) changes the original list to [-1,1,1,3] and returns it # Example: count_positives([1,6,-4,-2,-7,-2]) changes the list to [1,6,-4,-2,-7,2] and returns it def count_positives(arr): positivesCount = 0 for i in range(0, len(arr)): if(arr[i]>=0): positivesCount += 1 arr[len(arr)-1] = positivesCount return arr print(count_positives([-1,1,1,1])) print(count_positives([1,6,-4,-2,-7,-2]),"\n\n") # Sum Total - Create a function that takes a list and returns the sum of all the values in the list. # Example: sum_total([1,2,3,4]) should return 10 # Example: sum_total([6,3,-2]) should return 7 def sum_total(arr): sum = 0 for i in range(0, len(arr), 1): sum += arr[i] return sum print(sum_total([1,2,3,4])) print(sum_total([6,3,-2]),"\n\n") # Average - Create a function that takes a list and returns the average of all the values.x # Example: average([1,2,3,4]) should return 2.5 def average(arr): sum = 0 for i in range(0, len(arr), 1): sum += arr[i] return (float(sum/len(arr))) print(average([1,2,3,4]),"\n\n") # Length - Create a function that takes a list and returns the length of the list. # Example: length([37,2,1,-9]) should return 4 # Example: length([]) should return 0 def length(arr): if(len(arr)<=0): return 0 else: lengthVariable = 0 for i in arr: lengthVariable+=1 return lengthVariable print(length([37,2,1,-9])) print(length([]),"\n\n") # Minimum - Create a function that takes a list of numbers and returns the minimum value in the list. # If the list is empty, have the function return False. # Example: minimum([37,2,1,-9]) should return -9 # Example: minimum([]) should return False def minimum(arr): if(len(arr)<=0): return 0 else: minNum = arr[0] for i in range(0,len(arr),1): if(arr[i]<=minNum): minNum=arr[i] return minNum print(minimum([37,2,1,-9])) print(minimum([]),"\n\n") # Maximum - Create a function that takes a list and returns the maximum value in the list. # If the list is empty, have the function return False. # Example: maximum([37,2,1,-9]) should return 37 # Example: maximum([]) should return False def maximum(arr): if(len(arr)<=0): return 0 else: maxNum = arr[0] for i in range(0,len(arr),1): if(arr[i]>=maxNum): maxNum=arr[i] return maxNum print(maximum([37,2,1,-9])) print(maximum([]),"\n\n") # Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the list. # Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 } def ultimate_analysis(arr): ultimate_analysis_dictionary = { "sumTotal":sum_total(arr), "average":average(arr), "minimum":minimum(arr), "maximum":maximum(arr), "length":length(arr) } return ultimate_analysis_dictionary print(ultimate_analysis([37,2,1,-9]),"\n\n") # Create a function that takes a list and return that list with values reversed. # Do this without creating a second list. (This challenge is known to appear during basic technical interviews.) # Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37] def reverse_list(arr): temp = 0 last = (len(arr)-1) mid = math.floor((len(arr))/2) for i in range(0, mid, 1): temp = arr[i] arr[i] = arr[last-i] arr[last-i] = temp return arr print(reverse_list([37,2,1,-9]))
5923a13cb030f647735736e65bc8e08e1ecc5544
X-H-W/xhw
/所有.py/练习/lol.py
2,735
3.9375
4
''' 游戏:英雄联盟 新手指导: 1、注册帐号 2、登录帐号 3、选择服务器 4、创建名称 人物职业 ''' lolo = '新手指导' print(lolo.center(40)) print('*'*40) print('*'*40) print('第一步:%s\n第二步:%s\n第三步:%s\n'%('注册','登录','选择服务器')) print('*'*40) lol = [{'name':'123','passwd':'321'}] while True: print('*'*40) print('1、登录','2、注册','4、进入''3、退出') register_login = int(input('请输入你要选择的功能序号')) def register():# 注册 # 创建一个函数 name = input('输入你要注册的帐号') zhanghao_list = [] for dictionary in lol: zhanghao_list.append(dictionary['name']) if name in zhanghao_list: print('帐号已存在,请重新输入') elif name not in zhanghao_list: passwd = input('请输入你的密码') # 创建一个字典 dic = {} dic['name']= name dic['passwd'] = passwd lol.append(dic) print('注册成功') # 登录 def login(): name = input('输入你的帐号') for dictionary in lol: zhanghao_list = [] zhanghao_list.append(dictionary['name']) if name not in zhanghao_list: print('帐号错误,请重新出入') elif name in zhanghao_list: pswd = input('请输入密码') i = 0 length = len(lol) dic = {}# 字典 while i <= length -1: dic = lol[i] if dic['name'] == name: mimas = int(dic['passwd']) break else: i += 1 dic = {} if pswd == mimas: print('欢迎来到英雄联盟') # 服务器 def server(): name = input('输入要进入的服务器') dm = '德玛西亚' zhanghao_listt = [{'name':'德玛西亚'}] for name in zhanghao_listt: zhanghao_listt.append(dictionary['name']) if name in zhanghao_listt: print('欢迎来到联盟') elif name not in zhanghao_listt: print('没有这个服务器') dic = {} dic['name'] = name zhanghao_listt.append(dic) print('进入') print('密码错误') if register_login == 2: register() elif register_login == 1: login() elif register_login == 3: print('祝你玩的愉快') break elif server == 4: server() print('欢迎进入德玛西亚')
8faa9db64dcc41f33aad728c9b39b99f46013596
btjd/DSA
/MergeSort.py
1,814
4.09375
4
from random import shuffle def merge_sort(sequence): print ">> 1. sequence ", sequence res = [] if len(sequence) < 2: return sequence mid = len(sequence)//2 left_half = merge_sort(sequence[:mid]) right_half = merge_sort(sequence[mid:]) l = 0 r = 0 while l < len(left_half) and r < len(right_half): if left_half[l] > right_half[r]: res.append(right_half[r]) print "2-1. Adding %d to res from right instead of %d from left" % (right_half[r], right_half[r]) r += 1 else: res.append(left_half[l]) print "2-2. Adding %d to res from left instead of %d from right" % (left_half[l], right_half[r]) l += 1 # If we exhaust one of the sublists, just add the rest of what remains print "3. res is: ", res print "3. Left half: ", left_half[l:] res += left_half[l:] print "3. Right half: ", right_half[r:] res += right_half[r:] return res alist = [7, 8, 6, 4, 1, 5, 3, 0, 9, 2] res = merge_sort(alist) print res ### Let's do a test ### # def test_selection_sort(): # alist = [i for i in range(100)] # shuffle(alist) # res = merge_sort(alist) # assert res == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, # 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, # 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, # 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, # 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, # 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, # 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, # 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, # 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, # 91, 92, 93, 94, 95, 96, 97, 98, 99]
fcc18ad31dc79e76d2484157d039043ba21636df
nikyayulestari/phyton-candy
/LatihanJilid2_3.py
534
4.0625
4
print 'Mencari Nilai Terkecil dan Nilai Terbesar' a=input('Masukkan Variabel 1 : ') b=input('Masukkan Variabel 2 : ') c=input('Masukkan Variabel 3 : ') if a < b and a < c: print 'Nilai Terkecil adalah', a elif b < a and b < c: print 'Nilai Terkecil adalah', b elif c < a and c < b: print 'Nilai Terkecil adalah', c if a > b and a > c: print 'Nilai Terbesar adalah', a elif b > a and b > c: print 'Nilai Terbesar adalah', b elif c > a and c > b: print 'Nilai Terbesar adalah', c
0991fd866517e2a5849c23b060d39812899fadb6
Michael242039/Assignment2
/assignment2-1.py
544
3.90625
4
#Created by: Michael Taylor #Created on: September 30, 2017 #Created for ICS3U #This program calculates the height of a man based off of how long hes been falling import ui GRAVITY = 9.81 def calculate_button_pressed(sender): seconds = float(view['seconds_input'].text) view['seconds_label'].text = "{0:.2f}".format(seconds) height = (100 - (GRAVITY*seconds)/2) if height < 0: height = 0 view['man'].y = -(height*5)+500 view['height_label'].text = 'height: ' + "{0:.2f}".format(height) + 'm' view = ui.load_view() view.present('sheet')
d8006c027980b25bd721ec44973c8f25d181a12b
sergeynikifforov/Hydrogen_plots
/sat_graph_count.py
512
3.8125
4
#count the vapor pressure of water on temperature import matplotlib.pyplot as plt import math from scipy.interpolate import CubicSpline import numpy as np f = open('test.txt', 'r') print('Please, input temperature in Celsium') T = float(input()) print('Please, input the whole pressure in Kpa') P = float(input()) x = list() y = list() for line in f: a = line.split(' ') x.append(float(a[0])) y.append(float(a[1])) cs = CubicSpline(x, y) print('The pressure of saturated vapor in KpA:') print(cs(T))
d086baf2025aee89f9fb234e8228bb7cff20f3a5
srabani743/lab1
/main.py
3,428
3.890625
4
from math import * # Zad1. Napisz pierwszy skrypt, w którym zadeklarujesz po dwie zmienne każdego typu a następnie wyświetl te zmienne i1 = 2 i2 = 4 f1 = 1.4 f2 = 2.9 s1 = "python" s2 = "pycharm" c1 = 2 + 3j c2 = 8 - 4j print("Zad1") print(i1) print(i2) print(f1) print(f2) print(s1) print(s2) print(c1) print(c2) # Zad2. Stwórz skrypt kalkulator, w którym wykorzystać wszystkie podstawowe działania arytmetyczne print("Zad2") print("1.Dodawanie") print("2.Odejmowanie") print("3.Dzielenie") print("4.Mnożenie") dzialanie = input("Wybierz dzialanie(podaj cyfre): ") if dzialanie in ("1", "2", "3", "4"): l1 = float(input("Wybierz 1 liczbe: ")) l2 = float(input("Wybierz 2 liczbe: ")) if dzialanie == "1": print(l1, "+", l2, "=", l1+l2) elif dzialanie == "2": print(l1, "-", l2, "=", l1-l2) elif dzialanie == "3": print(l1, "/", l2, "=", l1 / l2) elif dzialanie == "4": print(l1, "*", l2, "=", l1 * l2) else: print("Nieprawidlowy numer dzialania") # Zad3. Napisz skrypt, w którym stworzysz operatory przyrostkowe dla operacji: +, -, *, /, **, % print("Zad3") a = 3 print("a = ", a) a += 2 print("a += 2", a) a -= 3 print("a -= 3", a) a *= 3 print("a *= 3", a) a /= 2 print("a /= 2", a) a **= 2 print("a **= 2", a) a %= 2 print("a %= 2", a) # Zad4. Napisz skrypt, który policzy i wyświetli następujące wyrażenia: print("Zad4") print(exp(10)) print(pow((log((5 + pow(sin(8), 2)))), 1 / 6)) print(floor(3.55)) print(ceil(4.80)) # Zad.5 Zapisz swoje imie i nazwisko w oddzielnych zmiennych wszystkie wielkimi literami. # Użyj odpowiedniej metody by wyświetlić je pisane tak, że pierwsza litera jest wielka a poszostałe małe. # (trzeba użyć metody capitalize) print("Zad5") imie = "JAKUB" nazwisko = "PIETKIEWICZ" print(str.capitalize(imie) + " " + str.capitalize(nazwisko)) # Zad.6 Napisz skrypt, gdzie w zmiennej string zapiszesz fragment tekstu piosenki z powtarzającymi się słowami # np. „la la la”. Następnie użyj odpowiedniej funkcji, która zliczy występowanie słowa „la”. (trzeba użyć metody count) piosenka = """Black bird, black moon Black sky, black light Black, everything black Black heart Black Keys, black diamonds Black out, everything black Black, black, everything, everything All black, everything, everything All black, everything, everything All black, everything, everything, black""" print("Zad6") print("Liczba slow w piosence:", piosenka.count("black") + piosenka.count("Black")) # Zad.7 Do poszczególnych elementów łańcucha możemy się odwoływać przez podanie indeksu. # Np. pierwszy znak zapisany w zmiennej imie uzyskamy przez imie[0]. # Zapisz dowolną zmienną łańcuchową i wyświetl jej drugą i ostatnią literę, wykorzystując indeksy indeks = "Awokado" print("Zad7") print(indeks) print("Druga litera:", indeks[1]) print("Ostatnia litera:", indeks[len(indeks) - 1]) # Zad.8 Zmienne łańcuchowe możemy dzielić wykorzystaj zmienną z Zad. 6 i spróbuj ją podzielić na poszczególne wyrazy. # (trzeba użyć metody split) print("Zad8") print(piosenka.split()) # Zad.9 Napisz skrypt, w którym zadeklarujesz zmienne typu: string, float i szestnastkowe. # Następnie wyświetl je wykorzystując odpowiednie formatowanie. nitka = "nitka" splawik = 3.14 heksa = hex(20) print("Zad9") print("String: %s" % nitka) print("Float: %d" % splawik) print("Hex: %s" % heksa)
dff4011b25e14229d5620b5e16bcb77d5b3f4efe
moidshaikh/hackerranksols
/codewars/python/strip_comments.py
1,426
4.25
4
''' https://www.codewars.com/kata/51c8e37cee245da6b40000bd/train/python Given an input string of: apples, pears # and bananas grapes bananas !apples The output expected would be: apples, pears grapes bananas The code would be called like so: result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) # result should == "apples, pears\ngrapes\nbananas"''' def strip_comments(strng, markers): final = [] lines = strng.split('\n') for line in lines: tmpstring = line for marker in markers: if marker in line: tmpstring = line[:line.find(marker)] final.append(tmpstring) return final[:-1] strng = 'apples, pears # and bananas\ngrapes\nbananas !apples' lines = ['apples, pears # and bananas', 'grapes', 'bananas !apples'] # lines = strng.split('\n') markers = ['#', '!'] res = strip_comments('apples, pears # and bananas\ngrapes\nbananas !apples', ['#', '!']) e_res = 'apples, pears\ngrapes\nbananas' print(len(res), len(e_res)) # strip_comments('a #b\nc\nd $e f g', ['#', '$']), 'a\nc\nd') # strip_comments(' a #b\nc\nd $e f g', ['#', '$']), ' a\nc\nd') # strip_comments('apples, pears # and bananas\ngrapes\nbananas !apples', ['#', '!']), 'apples, pears\ngrapes\nbananas') # strip_comments('a #b\nc\nd $e f g', ['#', '$']), 'a\nc\nd') # strip_comments(' a #b\nc\nd $e f g', ['#', '$']), ' a\nc\nd')
d22956c9953fe782f63eefc4191f8674683b5c76
JnKesh/Hillel_HW_Python
/HW5/Desks and Students.py
231
3.734375
4
a = int(input("Students in Class 1: ")) # Class 1 b = int(input("Students in Class 2: ")) # Class 2 c = int(input("Students in Class 3: ")) # Class 3 print("Need to buy desks:", a // 2 + b // 2 + c // 2 + a % 2 + b % 2 + c % 2)
eb3e7546706b992ffdc4a17c61cecffcb3157241
laminsurachman/learning_python2
/if.py
353
4.0625
4
"""a = 7 b = 8 c = 9 if a < b : print( a, " is smaller than", b ) if a > b: print (a,"is smaller than", b ) elif b >= c: print(b," is smaller than", c ) else : print( c, " islarger than",b,"and",a) a = 7 b = 8 if a >b : print(a, "is smaller than", b) elif b > a : print(b, "is bigger than", a) """
1e2c9009a02817daf3414898eb10bd5f051cd6ca
0xEitan/CryptoPals
/set1/ex3-xor-cipher/main.py
1,886
3.625
4
import string def score_english_sentence(s): # not the best way to score a sentencte # repeated 'E' will score the highest... # http://pi.math.cornell.edu/~mec/2003-2004/cryptography/subs/frequencies.html FREQUENCY = { 'E': 12.02, 'T': 9.10, 'A': 8.12, 'O': 7.68, 'I': 7.31, 'N': 6.95, 'S': 6.28, 'R': 6.02, 'H': 5.92, 'D': 4.32, 'L': 3.98, 'U': 2.88, 'C': 2.71, 'M': 2.61, 'F': 2.30, 'Y': 2.11, 'W': 2.09, 'G': 2.03, 'P': 1.82, 'B': 1.49, 'V': 1.11, 'K': 0.69, 'X': 0.17, 'Q': 0.11, 'J': 0.10, 'Z': 0.07, } # assume an english sentence has at least two words in it if ' ' not in s: return 0 score = 0 for word in s.split(' '): for letter in word: if letter.upper() in FREQUENCY: score += FREQUENCY.get(letter.upper(), 0) return score def xor_string(s, key): return ''.join(chr(ord(s[i]) ^ key) for i in xrange(len(s))) def main(xored): possibilities = dict() for key in xrange(0x100): decoded = xor_string(xored, key) if any(c not in string.printable for c in decoded): continue score = score_english_sentence(decoded) possibilities[score] = (key, decoded) best_score = max(possibilities) best_guess = possibilities[best_score] print "Best guess with score {0} and xor key {1}: {2}".format(best_score, best_guess[0], best_guess[1]) if __name__ == '__main__': xored = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' main(xored.decode('hex'))
eb9d2ebb5b2a9ad9c24c69cf3751e30cafd99828
davidgillard/formation
/exercices/chapitre2/02-volume_cone.py
638
3.9375
4
# -*- coding: UTF-8 -*- # fichier : 02-volume_cone.py # auteur : David GILLARD """Ecrire un programme qui à partir de la saisie d'un rayon et d'une hauteur, calcul le volume d'un cone droit (on rappelle que le volume du cône est donné par : V = (pi*r^2*h)/3 ou r et h sont respectivement le rayon et la hauteur du cylindre """ import math print(""" Veuillez entrer les valeurs de r et h (en séparant ces valeurs à l'aide de virgules) :""") r, h = eval(input()) # le eval verifie que les deux valeurs ont été saisies volume = (math.pi * r * r * h)/ 3 print("Le volume du cône est de : {:.2f}".format(volume), "m3")
434b7be741f4416aabbdff304547d8a5217b7cc7
saurin94/Cracking-the-Coding-Interview
/Arrays and Strings/Palindrome Permutation.py
433
3.5625
4
def palindrome_check(s): d = {} s = s.lower().replace(" ","") for i in s: d[i] = d.get(i, 0) + 1 counter = 0 for ch, count in d.iteritems(): if count % 2 != 0: counter += 1 if counter <= 1: return True else: return False print palindrome_check("sas sas") print palindrome_check("Tact coa") print palindrome_check("tac cat") print palindrome_check("rin sau")
dad709ab02854f49073116621cb4e84ac858ee01
flerchy/codestyle-core
/ml_quality/datasets/shit/if_else.py
309
4.0625
4
age = 27 if age > 21 print "You can buy beer" else print "You are too young to buy beer" name = "cam" if name is "buck": print ("what up buck") elif name is "cam": print ("what up cam") elif name is "sammy": print ("what up sammy") else: print("please sign up for the site")
5f24041bef0b396c7548ab95f6a16b3cde599978
aheirich/GAN_inversion
/python/sumX.py
195
3.515625
4
import sys f = open(sys.argv[1], "r") sum = 0 count = 0 for line in f.readlines(): word = line.strip() value = float(word) sum = sum + value count = count + 1 print("mean", sum / count)
875d254f9ee0b3f0942fa7855af500073b460fe0
prefrontal/coding-practice
/Effective Python/Chapter 1 - Pythonic Thinking/012 - Else Loops.py
499
4.46875
4
# Effective Python # 012 - Avoid else blocks after for a while loops # Python lets you have an else block following a LookupError for i in range(3): print (i) else: print ("Else") # Break statements will skip the else block for i in range(3): print (i) if i == 1: break else: print ("Else") # Else runs immediately when an empty list is evaluated # or when a while loop is False for x in []: print ("Nope") else: print ("Yep") while False: print ("Nu-uh") else: print ("Yep yep")
6eac27c3049c987fee4a82874fdd82c4ae7640c1
czs108/LeetCode-Solutions
/Easy/110. Balanced Binary Tree/solution (1).py
983
3.859375
4
# 110. Balanced Binary Tree # Runtime: 3232 ms, faster than 5.10% of Python3 online submissions for Balanced Binary Tree. # Memory Usage: 17.6 MB, less than 100.00% of Python3 online submissions for Balanced Binary Tree. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # Recursive def isBalanced(self, root: TreeNode) -> bool: if not root: return True else: def get_depth(node: TreeNode) -> int: if not node: return 0 else: return max(get_depth(node.left), get_depth(node.right)) + 1 depth_diff = abs(get_depth(root.left) - get_depth(root.right)) <= 1 balance_child = self.isBalanced(root.left) and self.isBalanced(root.right) return depth_diff and balance_child
5a5c0eb934355ad6e72bd01826c52afaf418ff27
DevanLawal/Nim
/main.py
347
3.921875
4
#This function will repeat for each person Score = 0 #while function that will be true running = True while running: Choice = int(input("1 or 2?: ")) if Choice > 20: running == True #adding our inputted number to the score Score += Choice print(Score) else: running = False #Make the function stop when 20 is hit
0a7f5e8e20ccd59f13ec739e45576809fc956833
Nikhil-Sudhan/PasswordManager
/menu.py
3,429
3.5625
4
from database import store_password,find_user,find_password,delete import array import random import pyperclip from cryptography.fernet import Fernet passw=input('Please provide the master password to start the password manager: ') if passw=='Password': print('Welcome to the password manager') else: print('Incorrect password') exit() print('-'*40) print(('-'*18)+'Menu'+('-'*18)) print('1. Create your new password') print('2. Find a passwoed for a site or app') print('3. Find all sites and apps connected to an email') print('4. Delete the information you added') print('-'*40) choice=input(': ') while choice != 'Q': if choice =='1': print('Please provide the name of the site or app you want to generate a password for: ') app_name=input() MAX_LEN=(int(input('Enter the length of password: '))) DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'm', 'n', 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y','z'] UPCASE_CHARACTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q','R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z'] SYMBOLS = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>','*', '(', ')', '<'] COMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS + SYMBOLS rand_digit=random.choice(DIGITS) rand_upper=random.choice(UPCASE_CHARACTERS) rand_lower=random.choice(LOCASE_CHARACTERS) rand_symbol=random.choice(SYMBOLS) rand_digit = random.choice(DIGITS) rand_upper = random.choice(UPCASE_CHARACTERS) rand_lower = random.choice(LOCASE_CHARACTERS) rand_symbol = random.choice(SYMBOLS) temp_pass = rand_digit + rand_upper + rand_lower + rand_symbol for x in range(MAX_LEN - 4): temp_pass = temp_pass + random.choice(COMBINED_LIST) temp_pass_list = array.array('u', temp_pass) random.shuffle(temp_pass_list) password = "" for x in temp_pass_list: password = password + x ans=input("Type -yes- to display passowrd: ") if ans =="yes": print(password) pyperclip.copy(password) spam=pyperclip.paste() print('-'*30) print('Your password has now been created and copied to your clipboard') print('-'*30) user_email=input('Please provide a user email for this app or site: ') username=input('Please provide a username for this app: ') if username ==None: username ='' url =input('Please provide the url of the site: ') store_password (password,user_email,username,url,app_name) break if choice =='2': print('Please provide the name of the site or app you want to find the password: ') app_name = input() find_password(app_name) break if choice =='3': print('Please provide the email that you want to find accounts for: ') user_email=input() find_user(user_email) break if choice =='4': print('Provide the app name you want to delete: ') app_name=input() delete(app_name) break else: choice=menu() exit()
7149b1a1480a4ff470e3f57dcf3a720d8402222a
Lex-Lexus/python_learning
/password_generator.py
1,395
3.75
4
# импорт библиотек import random as rnd # обьявление функций def generate_password(length: int, chars: str): password = '' for _ in range(length): password += rnd.choice(chars) return password # инициализируем переменные digits = '0123456789' lowercase_letters = 'abcdefghijklmnopqrstuvwxyz' uppercase_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' punctuation = '!#$%&*+-=?@^_' chars = '' # основной код password_quantity = int(input('Количество паролей для генерации: ')) password_lenght = int(input('Длина одного пароля: ')) if input('Включать ли цифры 0123456789? д/н: ') == 'д': chars += digits if input('Включать ли прописные буквы ABCDEFGHIJKLMNOPQRSTUVWXYZ? д/н: ') == 'д': chars += uppercase_letters if input('Включать ли строчные буквы abcdefghijklmnopqrstuvwxyz? д/н: ') == 'д': chars += lowercase_letters if input('Включать ли символы !#$%&*+-=?@^_? д/н: ') == 'д': chars += punctuation if input('Исключать ли неоднозначные символы il1Lo0O? д/н: ') == 'д': for char in 'il1Lo0O': chars = chars.replace(char, '') for _ in range(password_quantity): print(generate_password(password_lenght, chars))
9e1d8d0c24159c1cd3acd5dfcf7608fab3482693
shincap8/holbertonschool-machine_learning
/math/0x03-probability/binomial.py
1,867
4.15625
4
#!/usr/bin/env python3 """class Binomial that represents a binomial distribution""" class Binomial: """Binomial""" def __init__(self, data=None, n=1, p=0.5): """class constructor""" if data is None: if n <= 0: raise ValueError("n must be a positive value") if p <= 0 or p >= 1: raise ValueError("p must be greater than 0 and less than 1") self.n = int(n) self.p = float(p) else: if type(data) is not list: raise TypeError("data must be a list") if len(data) <= 2: raise ValueError("data must contain multiple values") mean = sum(data) / int(len(data)) dif = [] for i in data: dif.append((i - mean) ** 2) var = sum(dif) / len(dif) ptemp = 1 - (var / mean) self.n = int(round(mean / ptemp)) self.p = float(mean / self.n) def pmf(self, k): """Calculates the value of the PMF for a given number of 'successes'""" if k < 0: return 0 if k <= self.n: k = int(k) factor1, factor2, factor3 = 1, 1, 1 for i in range(1, (self.n + 1)): factor1 = factor1 * i for j in range(1, (k + 1)): factor2 = factor2 * j for l in range(1, (self.n - k + 1)): factor3 = factor3 * l return ((factor1 / (factor2 * factor3)) * (self.p ** k) * ((1 - self.p) ** (self.n - k))) return 0 def cdf(self, k): """Calculates the value of the CDF for a given number of 'successes'""" if k < 0: return 0 prob = 0 for i in range(int(k)+1): prob = prob + self.pmf(i) return (prob)
782a2a06d2c47fb105e52770046973f7a405495a
AbiramiRavichandran/DataStructures
/Tree/Tilt.py
539
3.5625
4
class Node: def __init__(self, data): self.data = data self.left = self.right = None def get_tilt(root): if not root: return 0 l = get_tilt(root.left) r = get_tilt(root.right) get_tilt.tilt += abs(l - r) return l + r + root.data if __name__ == "__main__": root = Node(4) root.left = Node(2) root.right = Node(9) root.left.left = Node(3) root.left.right = Node(8) root.right.right = Node(7) get_tilt.tilt = 0 get_tilt(root) print(get_tilt.tilt)
2eedffc57b13e8c490d7024fc8ee5016a61286c4
zepler2011/leetcode_solution
/zshen/dfs-combi-permu/generate-parentheses-lc427.py
839
3.625
4
class Solution: """ @param n: n pairs @return: All combinations of well-formed parentheses """ def generateParenthesis(self, n): results = [] self.dfs(n, 0, 0, [], results) return results def dfs(self, n, lcnt, rcnt, pare, res): if len(pare) == 2*n and lcnt==rcnt: res.append(''.join(pare)) return if lcnt < n: pare.append('(') lcnt += 1 self.dfs(n, lcnt, rcnt, pare, res) pare.pop() lcnt -= 1 if lcnt >0 and rcnt < n and lcnt > rcnt: pare.append(')') rcnt += 1 self.dfs(n, lcnt, rcnt, pare, res) pare.pop() rcnt -= 1 return """ TODO: 梳理第二个if 条件 """
b1d0330d9d8c50187636fcf06ae0b2451ae54ce8
JeongHwan-dev/Crawling_with_Python
/Ch01_FundamentalCrawling/loadHTMLDocument.py
815
3.515625
4
from bs4 import BeautifulSoup # index.html 을 불러와서 BeautifulSoup 객체를 초기화해 soup에 저장 soup = BeautifulSoup(open("index.html"), "html.parser") # 1. 불러온 html 문서를 출력 print(soup) print("=" * 50) # 2. soup 를 사용하여 <p> 태그 부분의 텍스트를 출력 print(soup.find("p")) print(soup.find("p").get_text()) print("=" * 50) # 3. class 가 "elice" 인 <div> 태그 부분의 텍스트를 출력 print(soup.find("div")) print("-" * 50) print(soup.find("div", class_="elice")) print("-" * 50) print(soup.find("div", class_="elice").get_text()) print("=" * 50) # 4. id 가 "main" 인 <div> 태그 부분의 텍스트를 출력 print(soup.find("div")) print('-' * 50) print(soup.find("div", id="main")) print('-' * 50) print(soup.find("div", id="main").get_text())
2cce6b1dc9ee1f0d35e9e48336fcdc3afef2c8bd
Itamar-Farias/TST_P1_UFCG
/unidade3/custo_empregada/custo_empregada.py
966
3.765625
4
# coding: utf-8 # Itamar da Silva Farias 115210021 # Programação I salario_base = float(raw_input()) dias_trabalhado = int(raw_input()) custo_diario_transporte = float(raw_input()) print "O salário base é R$ %.2f" % salario_base FGTS = 0.08 * salario_base gasto_do_empregado = salario_base + FGTS salario_liquido = salario_base custo_total_transporte = dias_trabalhado * custo_diario_transporte if custo_total_transporte > 0.06 * salario_base: salario_liquido -= 0.06 * salario_base gasto_do_empregado += custo_total_transporte - (0.06 * salario_base) if salario_base <= 1317.07: INSS = 0.08 * salario_base elif salario_base > 1317.08 and salario_base <= 2195.12: INSS = 0.09 * salario_base else: INSS = 0.11 * salario_base gasto_do_empregado += 0.12 * salario_base salario_liquido -= INSS print "O custo mensal para o empregador é de R$ %.2f" % gasto_do_empregado print "O salário líquido que o trabalhador irá receber no mês é R$ %.2f" % salario_liquido
2dc88fa7f009df8ae37b5dfc6b40723a2d4b4fe7
SaiSujithReddy/CodePython
/StringListsOrder_v1.py
1,303
3.796875
4
output=[] text=["abcd","ce","", "","fgh"] converted_list=[list(x) for x in text] max_length= len(max(converted_list,key=len)) for l in converted_list: padding=max_length-len(l) l.extend(['']*padding) for items in zip(*converted_list): output.extend(list(items)) print(''.join(output)) #order is O(n+m) where n is the number of characters of the longest word and m is the number of words in the input # # input = ['aaa...aaa', 'a', 'a', 'a'..., 'a', 'a', 'a', 'a'] # len(input[0]) = 10 ^ 9 # len(input) = 10 ^ 9 # # 10 ^ 9 * 10 ^ 9 # // reverse # sort # of # all # the # words # based # on # length # // remove # the # words # no # longer # present - reduces # the # loop # complexity or create # a # new # array # with remaning characters of the word # // Can # you # hear # me ? # # // time - O(n + m + m) - O(2 # mn) - O(mn) # # # def string_to_char_array(element): # return list(element) # # # input = ['abc', 'd', 'ef'] # input_list = [] # # for x in input: # input_list.append(string_to_char_array(x)) # # print(input_list) # # # get largest word length # max_length_word = max([len(x) for x in input_list]) # # for i in range(0, max_length_word): # for y in input_list: # # if (len(y) > i): # print(y[i]) # else: # continue
38377bc5dc1b45fc11d2912ce0b23f4d40461d26
eroicaleo/LearningPython
/interview/leet/189_Rotate_Array.py
487
3.515625
4
#!/usr/bin/env python3 import math class Solution: def rotate(self, nums, k): l = len(nums) d = math.gcd(k, l) for i in range(d): p, q, prev = i, (i+k)%l, nums[i] while q != i: tmp = nums[q] nums[q] = prev p, q, prev = q, (q+k)%l, tmp nums[i] = prev return nums nums = [1,2,3,4,5,6,7] k = 3 nums = [-1,-100,3,99] k = 2 sol = Solution() print(sol.rotate(nums, k))
3ba30563efc136aa40850d7fe386ee371ef7252b
AVNest/py-checkio-solutions
/home/min_max.py
746
3.5625
4
def _min_max(*it, key=lambda x: x, cmp_func=lambda x, y: x < y): if len(it) == 1: it = it[0] res_val = None for val in it: if res_val is None or cmp_func(key(val), key(res_val)): res_val = val return res_val def min(*it, key=lambda x: x): return _min_max(*it, key=key) def max(*it, key=lambda x: x): return _min_max(*it, key=key, cmp_func=lambda x, y: x > y) assert max(3, 2) == 3 assert min(3, 2) == 2 assert max([1, 2, 0, 3, 4]) == 4 assert min("hello") == "e" assert max(2.2, 5.6, 5.9, key=int) == 5.6 assert min([[1,2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0] assert min(abs(i) for i in range(-10, 10)) == 0 assert max(filter(str.isalpha, "@v$e56r5CY{]")) == 'v' print('Good')
9ad3227676689fcd19a3ca3e4443931900af58be
YSCodingArena/Code_Arena
/Programs/Qtn14.py
430
4.03125
4
''' Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. Suppose the following input is supplied to the program: Hello world! Then, the output should be: UPPER CASE 1 LOWER CASE 9 ''' strip = input() lower = upper = 0 for let in strip: if let.islower(): lower+=1 if let.isupper(): upper+=1 print ("UPPER CASE", upper) print ("LOWER CASE", lower)
21ded74da3270a9f6cdadb463485f39aa78035d5
ankit27kh/JetBrains-Python-Learning-Track
/Medium Projects/Numeric Matrix Processor/processor.py
7,180
4
4
class MatrixProcessor: def __init__(self): self.menu() def menu(self): print("""1. Add matrices 2. Multiply matrix by a constant 3. Multiply matrices 4. Transpose matrix 5. Calculate a determinant 6. Inverse matrix 0. Exit""") n = input('Your choice: ') if n in ['1', '2', '3', '4', '5', '6', '0']: if n == '1': self.add() elif n == '2': self.const_multi() elif n == '3': self.mat_multi() elif n == '4': self.transpose() elif n == '5': self.determinant() elif n == '6': self.inverse() elif n == '0': self.exit() else: print('Invalid choice') self.menu() def add(self): A = input('Enter size of first matrix: ').split() rowsA = [] print('Enter first matrix:') for i in range(int(A[0])): rowsA.append(input().split()) B = input('Enter size of second matrix: ').split() rowsB = [] print('Enter second matrix:') for i in range(int(B[0])): rowsB.append(input().split()) if A != B: print('The operation cannot be performed.') else: print('The result is:') ans = [] for x in range(int(A[0])): ans.append([float(i) + float(j) for i, j in zip(rowsA[x], rowsB[x])]) for i in ans: for j in i: print(j, end=' ') print() print() self.menu() def const_multi(self): A = input('Enter size of matrix: ').split() rowsA = [] print('Enter matrix:') for i in range(int(A[0])): rowsA.append(input().split()) c = float(input()) print('The result is:') for i in rowsA: for j in i: print(float(j) * c, end=' ') print() print() self.menu() def mat_multi(self): A = input('Enter size of first matrix: ').split() rowsA = [] print('Enter first matrix:') for i in range(int(A[0])): rowsA.append(input().split()) B = input('Enter size of second matrix: ').split() rowsB = [] print('Enter second matrix:') for i in range(int(B[0])): rowsB.append(input().split()) if A[1] == B[0]: ans = [] for i in range(int(A[0])): row = [] for k in range(int(B[1])): row1 = [] for j in range(int(A[1])): row1.append([float(rowsA[i][j]) * float(rowsB[j][k])]) row.append(sum([sum(i) for i in row1])) ans.append(row) print('The result is:') for i in ans: for j in i: print(float(j), end=' ') print() print() else: print('The operation cannot be performed.') self.menu() def transpose(self): print() print("""1. Main diagonal 2. Side diagonal 3. Vertical line 4. Horizontal line""") n = input() if n in ['1', '2', '3', '4']: A = input('Enter matrix size: ').split() rowsA = [] print('Enter matrix:') for i in range(int(A[0])): rowsA.append(input().split()) print('The result is:') if n == '1': for i in range(int(A[1])): for j in range(int(A[0])): print(rowsA[j][i], end=' ') print() elif n == '2': for i in range(int(A[1]) - 1, -1, -1): for j in range(int(A[0]) - 1, -1, -1): print(rowsA[j][i], end=' ') print() elif n == '3': for i in range(int(A[0])): for j in range(int(A[1]) - 1, -1, -1): print(rowsA[i][j], end=' ') print() else: for i in range(int(A[0]) - 1, -1, -1): for j in range(int(A[1])): print(rowsA[i][j], end=' ') print() else: print('Invalid choice') self.menu() def determinant(self): A = input('Enter matrix size: ').split() if A[0] != A[1]: print('Invalid input') self.menu() else: rowsA = [] print('Enter matrix:') for i in range(int(A[0])): rowsA.append(input().split()) print('The result is:') print(self.solve_det(rowsA)) def solve_det(self, matrix): if len(matrix) == 1: return float(matrix[0][0]) if len(matrix) == 2: return float(matrix[0][0]) * float(matrix[1][1]) - float(matrix[0][1]) * float(matrix[1][0]) else: i = 1 total = 0 temp = matrix[1:] for t in range(len(matrix)): new = [] for q in range(len(temp)): new.append(temp[q][0:t] + temp[q][t+1:]) total = total + ((-1) ** (i + t + 1)) * float(matrix[i - 1][t]) * self.solve_det(new) return total def inverse(self): A = input('Enter matrix size: ').split() if A[0] != A[1]: print('Invalid input') self.menu() else: rowsA = [] print('Enter matrix:') for i in range(int(A[0])): rowsA.append(input().split()) det = self.solve_det(rowsA) if det == 0: print("This matrix doesn't have an inverse.") print() self.menu() else: cofactor_matrix = [] for i in range(len(rowsA)): temp = rowsA.copy() temp.pop(i) for t in range(len(rowsA)): new = [] for q in range(len(temp)): new.append(temp[q][0:t] + temp[q][t + 1:]) cofactor_matrix.append(((-1) ** (i + 1 + t + 1)) * self.solve_det(new)) co_matrix = [] for i in range(len(rowsA)): co_matrix.append(cofactor_matrix[i*(len(rowsA)):(i+1)*len(rowsA)]) new = [] for i in range(len(co_matrix)): for j in range(len(co_matrix)): new.append(co_matrix[j][i]) new1 = [] for i in range(len(rowsA)): new1.append(new[i*(len(rowsA)):(i+1)*len(rowsA)]) for i in new1: for j in i: print(float(j) / det, end=' ') print() print() self.menu() def exit(self): pass mat = MatrixProcessor()
2a1810d504057bd010a28167e199389aef2333d7
ajboxjr/Tweet-Generator
/class1/vocab-game/main.py
1,610
3.65625
4
from vocabcard import * from vocabset import * dictionary = [] vocab_sets = [] class Game(object): def __init__(self): self.vocab_sets = [] self. dictionary = [] def get_dictionary(self): with open('/usr/share/dict/words', 'r') as f: self.dictionary = f.read().split() def get_set(self, deck_name): for deck in self.vocab_sets: if deck.title == deck_name: return deck return None def new_set(self, set_name): self.vocab_sets.append(VocabSet(set_name)) print("Sucessfuly added {}".format(set_name)) def view_sets(self): for deck in self.vocab_sets: print(deck.title) def mainloop(self): option = None while option != 'q': option = int(input("Which option would you like")) if option ==1: title = input("What would you like name this?") game.new_set(title) if option == 2: game.view_sets() deck = game.get_set(input("Which set")) card_amt = int(input("How many cards would you like to add")) for _ in range(card_amt): name = input("What would you like to name this deck") definition = input("{}. Definition: ".format(name)) card = VocabCard(name, definition) deck.add_card(card) print("sucessfully added {}".format(card.name)) if __name__ == '__main__': game = Game() game.mainloop()
d07248bb4caecdfcc6184dc4f3119caf4561c7c2
yyl/another-challenge
/elevator.py
3,069
3.796875
4
#!/usr/bin/python import collections from task import Task class Elevator(object): def __init__(self, eid): self._id = eid self._capacity = 10 self._size = 0 self._cur_floor = 0 self._tasks = collections.defaultdict(list) self._destinations = collections.deque() self._direction = 0 @property def cur_floor(self): return self._cur_floor @property def capacity(self): return self._capacity @property def size(self): return self._size @property def idle(self): return self._direction == 0 @property def destination(self): if len(self._destinations) == 0: return None return self._destinations[-1] @property def status(self): return "elevator %d: current floor %d, destination %s, %d tasks" % \ (self._id, self.cur_floor, self.destination, self.size) def addDestination(self, dest): self._destinations.appendleft(dest) if self.destination > self._cur_floor: self._direction = 1 else: self._direction = -1 def addTask(self, task): assert(isinstance(task, Task)) self._tasks[task.destination].append(task) self._size += 1 if self.idle: if self.cur_floor != task.cur_floor: self.addDestination(task.cur_floor) self.addDestination(task.destination) print "elevator %d takes %s" % (self._id, task) # return True if the elevator is full def isFull(self): return self._size == self._capacity def isUp(self): return self._direction == 1 def isDown(self): return self._direction == -1 def hasNext(self): return len(self._destinations) > 0 # check if the given task is within the current trip def within(self, task): if self.isUp(): return self.cur_floor == task.cur_floor and self.destination >= task.destination if self.isDown(): return self.cur_floor == task.cur_floor and self.destination <= task.destination # move elevator by one step def move(self): # move only if not idle if not self.idle: if self.isUp(): self._cur_floor += 1 else: self._cur_floor -= 1 # release current floor arrived = self._tasks.pop(self._cur_floor, None) if arrived: self._size -= len(arrived) print "elevator %d release %d tasks at floor %d" % \ (self._id, len(arrived), self.cur_floor) # check if meet destination if self._cur_floor == self.destination: self._destinations.pop() self._direction = 0 if self.hasNext(): if self._destinations[-1] > self.cur_floor: self._direction = 1 else: self._direction = -1
d09561179591495583c5d1926db23798eb3017b0
ashwanisharma384/Hackerrank-contests-python37
/pattern_string_sequence.py
122
3.5
4
# string="subsequence" # pattern="sue" st=input()[8:-1] pt=input()[9:-1] n=0 for p in pt: n += st.count(p) print(n)
fcd0238d94a4b749c390efb15d4e07583ee0bf82
Minions1128/91_suggestions_improve_python
/10_lazy_evaluation.py
624
3.578125
4
# -*- coding: UTF-8 -*- # Oct 29th, 2016 # Lazy Evaluation(惰性计算) """1. 避免必要的计算 if x and y时,如果x为False,y没必要计算 if x or y是,若x为True,y没必要计算 * 以下举例,使用注释的if会更快""" from time import time t = time() abbr = ['cf.', 'e.g.', 'ex.', 'etc.', 'fig.', 'i.e.', 'Mr.', 'vs.'] for i in range(1000000): for w in ('Mr.', 'Hat', 'is', 'chasing', 'the' , 'black', 'cat', '.'): if w in abbr: # if w[-1] == '.' and w in abbr: pass print 'total run time:' print time()-t
1f7a18ff95a44ef694be931214067a009df68d7b
AnaGVF/Programas-Procesamiento-Imagenes-OpenCV
/Ejercicios - Febrero22/RestaImagenesOpenCV.py
595
3.515625
4
# Resta de Imágenes OpenCV # Nombre: Ana Graciela Vassallo Fedotkin # Expediente: 278775 # Fecha: 22 de Febrero 2021. import cv2 from matplotlib import pyplot as plt import numpy as np im1 = cv2.imread('img/huesos2.bmp', 2) im2 = cv2.imread('img/popo.bmp', 2) dimensiones = im1.shape r = dimensiones[0] c = dimensiones[1] im3 = np.zeros((r, c), dtype=np.int32) im3 = cv2.subtract(im1, im2) plt.subplot(1, 3, 1) plt.imshow(im1, 'gray') plt.title('Imagen 1') plt.subplot(1, 3, 2) plt.imshow(im2, 'gray') plt.title('Imagen 2') plt.subplot(1, 3, 3) plt.imshow(im3, 'gray') plt.title('Imagen Resultado') plt.show()
0f9be6df0996ae9498490671647fcf5c20a5e9bc
grammatek/PhonTranscripts
/src/accuracy_test.py
2,801
3.59375
4
""" Performs accuracy tests for syllabification and stress algorithms. Reference files should be in csv format: word,phonetic_transcr,syllabified_phonetic_transcr and: word,phonetic_transcr,syllabified_phonetic_transcr_with_stress_labels We are testing syllabification and stress labeling on transcribed words, i.e. we take as input the correct phonetic transcription. """ import argparse from datetime import datetime import syllab_stress.tree_builder as tree_builder import syllab_stress.syllabification as syllabification import syllab_stress.stress as stress from entry import PronDictEntry def init_ref_dict(dict_file, separator): """Init the reference dictionary, 'ref_str' is the reference version of either a syllabified or a syllabified and stress labeled transcription""" pron_dict = [] for line in dict_file: word, transcr, ref_str = line.split(separator) entry = PronDictEntry(word, transcr, reference=ref_str.strip()) pron_dict.append(entry) return pron_dict def create_tree_list(pron_dict): tb = tree_builder.TreeBuilder() tree_list = [] for entry in pron_dict: t = tb.build_compound_tree(entry) tree_list.append(t) return tree_list def parse_args(): parser = argparse.ArgumentParser(description='Accuracy tests for syllabification and stress labeling') parser.add_argument('i', type=argparse.FileType('r'), help='Reference file') parser.add_argument('-t', '--type', type=str, default='syllab', choices=['syllab', 'stress'], help="Type of test to run: 'syllab' or 'stress'") parser.add_argument('-s', '--sep', type=str, default=',', help=("Separator used in the reference file")) return parser.parse_args() def main(): args = parse_args() ref_file = args.i test_type = args.type separator = args.sep ref_dict = init_ref_dict(ref_file, separator) tree_dict = create_tree_list(ref_dict) syllabified = syllabification.syllabify_tree_dict(tree_dict) if test_type == 'stress': syllabified = stress.set_stress(syllabified) mismatches = [] with open(str(datetime.now().time()) + '_' + test_type + '_mismatches.csv', 'w') as f: for entry in syllabified: if test_type == 'syllab': hypothesis = entry.dot_format_syllables() else: hypothesis = entry.stress_format() if entry.reference_transcr != hypothesis: mismatches.append(entry.word + '\t' + entry.reference_transcr + '\t' + hypothesis) f.write(entry.word + '\t' + entry.reference_transcr + '\t' + hypothesis + '\n') print(str(len(mismatches))) print(str(len(mismatches)/len(ref_dict) * 100) + '%') if __name__ == '__main__': main()
ff1259002b9eba66b4e6126a09cf91fec1ec0e84
AlainVicious/arabigosRomanos
/init.py
2,482
3.5
4
import os from numeros.Convert import numerosConvert def imprimeMenu(): os.system('cls') menuH1 = "MENU" menuOp1 = "1.-Convertir Romano a Arabigo" menuOp2 = "2.-Convertir Arabigo a Romano" menuOp3 = "3.-Salir" menuFoot = "Seleccione la opcion deseada..." print('\u250F',''.center(32,'\u2501'), '\u2513') print('\u2503',menuH1.center(32),'\u2503') print('\u2523',''.center(32,'\u2501'),'\u252B') print('\u2503',menuOp1.ljust(32),'\u2503') print('\u2503',menuOp2.ljust(32),'\u2503') print('\u2503',menuOp3.ljust(32),'\u2503') print('\u2503',''.center(32,'\u2501'),'\u2503') print('\u2503','Seleccione una opcion...'.ljust(32),'\u2503') print('\u2517',''.center(32,'\u2501'), '\u251B') return def fun_repetir(SN): hayError = False repetir = False pasaOtra = True while not hayError: if SN == 'S': repetir = True break elif SN == 'N': repetir = False break else: SN = input('teclee S o N: ').upper() return repetir def init(): opcion = 0 salir = False convert = numerosConvert() while not salir: imprimeMenu() opcion = int(input('opcion: ')) siVolver = '' siSalir = '' repetir = True if opcion == 1: while repetir: os.system('cls') romanoInput = input('ingresa el numero romano: ').upper() arabigo = convert.romano_a_arabigo(romanoInput) print('Romano: {0} Arabigo: {1}'.format(romanoInput, arabigo)) repetir = fun_repetir(input('Desea hacer otra convercion?(S/N) ').upper()) elif opcion == 2: while repetir: os.system('cls') arabigoInput = int(input('ingresa el numero arabigo: ')) romano = convert.arabigo_a_romano(arabigoInput) print('Arabigo: {0} Romano: {1}'.format(arabigoInput, romano)) repetir = fun_repetir(input('Desea hacer otra convercion?(S/N) ').upper()) elif opcion == 3: siSalir = input('Seguro que desea salir?(S/N) ') if siSalir.upper() == 'S' or siVolver == 'N': salir = True input('presione cualquier tecla para continuar...') exit() else: input('Opcion no valida!') init()
308b6635f0931b521fb30955929137c2d12eca42
mdeangelo272/deep-learning-tutorial
/multi-layer-network/autograd_linear_model.py
1,917
3.625
4
# Example of three-layer network using pytorch tensors along with autograd import torch device = torch.device("cpu") device = torch.device("cuda") # Specify the size of your batch, data, hidden layers, and labels N = 128 # Batch size: How many data points you feed in at a time data_dim = 1000 # Dimension of data vector, remember one data point is one dimensional H_1 = 2000 # Dimension of first hidden layer H_2 = 100 # Dimension of second hidden layer label_dim = 10 # Dimension of label, the output/answer corresponding to your initial data of dim of 1000 learning_rate = 1e-5 # Set data x = torch.randn(N, data_dim, device=device) y = torch.randn(N, label_dim, device=device) def initialize_uniform_weights(weights, in_dim): k_sqrt = in_dim ** (-.5) return weights * (2 * k_sqrt) - k_sqrt # Set weights w_1 = torch.rand(data_dim, H_1, device=device, requires_grad=True) # Shape: 128 X 2000 w_2 = torch.rand(H_1, H_2, device=device, requires_grad=True) # Shape: 2000 X 100 w_3 = torch.rand(H_2, label_dim, device=device, requires_grad=True) # Shape: 100 X 10 with torch.no_grad(): w_1 = initialize_uniform_weights(w_1, data_dim) w_2 = initialize_uniform_weights(w_2, H_1) w_3 = initialize_uniform_weights(w_3, H_2) w_1.requires_grad = True w_2.requires_grad = True w_3.requires_grad = True # Start Training for i in range(1000): # Start forward pass y_pred = x.mm(w_1).clamp(min=0).mm(w_2).clamp(min=0).mm(w_3) # Compute loss loss = (y_pred - y).pow(2).sum() print(i, loss.item()) # Use autograd to compute pass loss.backward() with torch.no_grad(): w_1 -= learning_rate * w_1.grad w_2 -= learning_rate * w_2.grad w_3 -= learning_rate * w_3.grad # Manually zero gradients after running backward pass w_1.grad.zero_() w_2.grad.zero_() w_3.grad.zero_() print(y_pred[0]) print(y[0])
6b92774a638f317f465db4207237a1ceec376a2e
ggyudongggyu/20201208commit
/practice/math/1735.py
445
3.828125
4
from math import gcd def lcm(x, y): return x*y // gcd(x,y) def gcd(x, y): while y: x, y = y , x%y return x a, aa = map(int, input().split()) b, bb = map(int, input().split()) if aa==bb: x = a+b y = gcd(x, aa) if y!=1: print(x//y, aa//y) else: print(x, aa) else: x = lcm(aa, bb) y = a*x//aa + b*x//bb z =gcd(x,y) if z==1: print(y, x) else: print(y//z, x//z)
6b3718506540e73b3b1dba329d2e95f18f9b99b9
Chavezsa/python-leetcode
/[21]Merge Two Sorted Lists.py
1,896
4.21875
4
# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # # Example: # # Input: 1->2->4, 1->3->4 # Output: 1->1->2->3->4->4 # # # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 解法1, 我的解法, 不够Pythonic def mergeTwoLists1(self, first: ListNode, second: ListNode) -> ListNode: dummy = ListNode(-1) traversed = dummy while first or second: if first and not second: traversed.next = first break elif not first and second: traversed.next = second break else: if first.val < second.val: traversed.next = ListNode(first.val) first = first.next else: traversed.next = ListNode(second.val) second = second.next traversed = traversed.next return dummy.next # comes from https://leetcode.com/problems/merge-two-sorted-lists/discuss/9771/Simple-5-lines-Python def mergeTwoLists2(self, first: ListNode, second: ListNode) -> ListNode: if first and second: if first.val > second.val: first, second = second, first first.next = self.mergeTwoLists2(first.next, second) return first or second # comes from https://leetcode.com/problems/merge-two-sorted-lists/discuss/9771/Simple-5-lines-Python def mergeTwoLists3(self, first: ListNode, second: ListNode) -> ListNode: if not first or second and first.val > second.val: first, second = second, first if first: first.next = self.mergeTwoLists(first.next, second) return first
b9d2b54d0aa727762f811184d81c18ffd671fc49
kimurakousuke/MeiKaiPython
/chap06/list0609.py
194
4.0625
4
# 使用enumerate函数遍历并输出字符串内的所有字符(从1开始计数) s = input('字符串:') for i, ch in enumerate(s, 1): print('第{}个字符:{}'.format(i, ch))
ab7dba69b8238ae6937be046efdd67fec2bbcd2e
kingkaki/Python-Design-Patterns
/Facade/facade.py
1,575
3.53125
4
# -*- coding: utf-8 -*- # @Author: King kaki # @Date: 2018-07-22 14:22:22 # @Last Modified by: King kaki # @Last Modified time: 2018-07-22 14:38:51 class EventManager: ''' 总事务负责人 ''' def __init__(self): print('EventManager: let me talk to the folks\n') def arrange(self): self.hotelier = Hotelier() self.hotelier.bookHotel() self.florist = Florist() self.florist.setFlowerRequirements() self.caterer = Caterer() self.caterer.setCuisine() self.musician = Musician() self.musician.setMusicType() ''' 各类负责人 ''' class Hotelier(): def __init__(self): print('Arranging the Hotel for Marriage?') def _isAvailable(self): print('Is the hotel free for the event on given day?') return True def bookHotel(self): if self._isAvailable(): print('Registered the Boking\n') class Florist(): def __init__(self): print('Flower for the Event?') def setFlowerRequirements(self): print('carnations & roses\n') class Caterer(): def __init__(self): print('Food arrangements for the event?') def setCuisine(self): print('Chinese & Continental Cuisine to be served\n') class Musician(): def __init__(self): print('Music arrangements for the marriage?') def setMusicType(self): print('Jazz and classical\n') ''' 你只需要询问总负责人即可 ''' class You(): def __init__(self): print('You:: Marriage Arrangements?') def askEventManager(self): print("You:: let's contact the Manager") m = EventManager() m.arrange() def __del__(self): print('Wonderful!') y = You() y.askEventManager()
6b8f3bed1ae8957f75998295e6722f3834ecd394
mochiyam/algorithms_and_data_structures
/Assignment1/q4/Quicksort.py
681
4.15625
4
''' ''' def quicksort(A, lo, hi): ''' This function computes quicksort :param: A: Array that will be sorted :param: lo and hi: pointers used to partitioning Time Complexity: O(N*log(N)) ''' if hi > lo: pivot = A[lo] left, right = partition(A, lo, hi, pivot) quicksort(A, lo, left-1) quicksort(A, right, hi) def partition(A, lo, hi, pivot): mid = lo while mid <= hi: if A[mid] < pivot: A[mid], A[lo] = A[lo], A[mid] lo += 1 mid += 1 elif A[mid] == pivot: mid += 1 else: A[mid], A[hi] = A[hi], A[mid] hi -= 1 return lo, mid
e5b78a1cb1ce9e3c4366f6281002780a4f264fc8
vector67/advent-of-code-2019
/Day 1/1.py
230
3.65625
4
import math print() sum_nums = 0 with open('data.txt', 'r') as f: lines = f.readlines() for line in lines: line = line.strip() print(line) sum_nums += math.floor(int(line)/3) - 2 print(sum_nums)