blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
c9f15d2bcda55de467e3673f73d80ea07524d1e0
smirnoffmg/codeforces
/230A.py
352
3.5
4
# -*- coding: utf-8 -*- s, n = map(int, raw_input().split()) dragons_and_points = [] for i in xrange(n): dragons_and_points.append(tuple(map(int, raw_input().split()))) dragons_and_points.sort() for power, treasure in dragons_and_points: if s > power: s += treasure else: print('NO') break else: print('YES')
f2df5ca1e0f47be584f77de58f0f14b4427afe30
smirnoffmg/codeforces
/465A.py
263
3.5
4
# -*- coding: utf-8 -*- n = int(raw_input()) number = raw_input() diff = 0 one = True for i in xrange(n): if number[i] == '1' and one: diff += 1 one = True if number[i] == '0' and one: diff += 1 one = False print(diff)
0016f064ede3097fe07bd3ea4c8282c58dd22448
smirnoffmg/codeforces
/474A.py
461
3.859375
4
# -*- coding: utf-8 -*- from string import maketrans r_transtab = maketrans( 'qwertyuiop' 'asdfghjkl;' 'zxcvbnm,./', 'wertyuiopp' 'sdfghjkl;;' 'xcvbnm,.//' ) l_transtab = maketrans( 'qwertyuiop' 'asdfghjkl;' 'zxcvbnm,./', 'qqwertyuio' 'aasdfghjkl' 'zzxcvbnm,.' ) direction = raw_input() word = raw_input() if direction == 'L': print(word.translate(r_transtab)) else: print(word.translate(l_transtab))
9b3991a950dc93f7311925ac96143f6ef1c07864
smirnoffmg/codeforces
/621A.py
336
3.703125
4
# -*- coding: utf-8 -*- n = int(raw_input()) numbers = map(int, raw_input().split()) numbers.sort(reverse=True) result = 0 odd = 0 for i in numbers: if i % 2 == 0: result += i else: if odd: result += odd result += i odd = 0 else: odd = i print(result)
dd75d06ea44d0a66eeb8922063c9804f6a92bcc9
thomasathul/MusicPlayerDemo
/Daily_Assignments/Day-1 Assignment/problem_set_4.py
1,171
3.609375
4
def ipadd(string): list1 = list(string.split(".")) decimal = 0 i = 3 for num in list1: decimal += (int(num)*pow(256, i)) i -= 1 return decimal def isogram(string): set1 = set(string) list1 = list(string) return "It is an isogram" if len(set1) == len(list1) else "It is not an isogram" def mexican_wave(string): new = [] for i in range(len(string)): new.append("{0}{1}{2}".format( string[:i], string[i].upper(), string[i+1:])) return new def large_num(string): num = int(string) res = 0 i = 1 while num//i > 0: temp = (num // (i * 10)) * i + (num % i) i *= 10 if temp > res: res = temp return res def shuffle(string): list1 = list(string) list1.sort(reverse=True) return "".join(x for x in list1) def word_freq(string): return string.count('a') def rgb_hex(tup): R, G, B = tup return "0x{:02x}{:02x}{:02x}".format(R, G, B) def accumulate(string): temp = "" for i in range(1, len(string)+1): temp += string[i-1]*i if i != len(string): temp += '-' return temp
bc5afd281dca2da2360a3e724238c8974e836261
thomasathul/MusicPlayerDemo
/3_Implementation/main.py
1,577
4.0625
4
""" Main function (Login and Signup """ from authenticate import SignUp, LogIn import menu def main(): """ Main method contains login and signup features :return: """ print("\n-----Welcome to MSS----- \n 1. Login \n 2. Signup") tryexit = 1 choice = None while tryexit: try: choice = int(input("\nChoose 1/2: ")) tryexit = 0 except ValueError: print("Only choice 1 or 2 is allowed") if choice == 2: print("\n--Create Account--") signobj = SignUp(input("Username (Email): "), input("Password (Min. 8 characters): ")) if signobj.usernameexist(): if signobj.usernamevalidity() and signobj.passwordvalidity(): signobj.saveindatabase() print("\nAccount Successfully created") else: print("Bad Username/Password, Check again") else: print("Account with this email already exists") if choice == 1: error = 1 while error: print("\n--Log In--") loginobj = LogIn(input("Username:"), input("Password: ")) print("---------") if loginobj.searchindatabase() == "Incorrect": print("\nWrong password") elif loginobj.searchindatabase() == 0: print("\nAccount doesn't exist") else: error = 0 print("\nLogin Successful!") print("Redirecting...") menu.__menu__() if __name__ == "__main__": main()
650702a684e00a7cb8d471e1c6eba314247b8312
SofiaShaposhnyk/ElementaryTasks
/tests/test_FibSequence.py
1,265
3.765625
4
import unittest import FibSequence class TestFibSequence(unittest.TestCase): def test_get_fib_sequence_valid_value(self): expected = "2, 3, 5, 8, 13, 21, 34, 55, 89" result = FibSequence.get_fib_sequence(1, 100) self.assertEqual(result, expected) def test_validate_args_negative_value(self): args = ["-5", "10"] expected = False, "Invalid arguments. Limits should be positive." result = FibSequence.validate_args(args) self.assertEqual(result, expected) def test_validate_args_text_value(self): args = ["1", "end"] expected = False, "Invalid arguments. Limits should be integer." result = FibSequence.validate_args(args) self.assertEqual(result, expected) def test_validate_args_invalid_value(self): args = ["1", "100", "1000"] expected = False, "Enter two positive limits to generate a sequence." result = FibSequence.validate_args(args) self.assertEqual(result, expected) def test_validate_args_valid_value(self): args = ["100", "1000"] expected = (100, 1000) result = FibSequence.validate_args(args) self.assertEqual(result, expected) if __name__ == "__main__": unittest.main()
5c2f075d9533e74f1d842018ab786669bf9b1fb3
SofiaShaposhnyk/ElementaryTasks
/NumSequence.py
719
3.703125
4
import sys import math def validate(args): if len(args) == 2: try: limit = int(args[1]) except ValueError: return "Limit should be integer." else: if limit > 0: return limit else: return "Limit should be positive." else: return "Enter one number to generate a sequence." def get_sequence(number): limit = int(math.sqrt(number)) return ", ".join(map(str, tuple(range(0, limit + 1, 1)))) if __name__ == "__main__": validation_result = validate(sys.argv) if type(validation_result) == int: print(get_sequence(validation_result)) else: print(validation_result)
84d608ba0fb808788426d769ed00a290f3f8407f
wako057/python
/src/exo00/part02.py
717
3.53125
4
# coding=utf-8 import random, math import locale locale.setlocale(locale.LC_ALL, '') print("############## Part 2 ##############") print("============== Exo 3 ==============") max = 1000000 print("Tableau de 0 a ") print("{0:n}".format(max).rjust(18)) l = list(range(0, max)) for k in range(0, 10): x = random.randint(0, l[-1]) iter = 0 a = 0 b = len(l) - 1 while a <= b: iter += 1 m = (a + b) // 2 if l[m] == x: position = m break elif l[m] < x: a = m + 1 else: b = m - 1 print("k=", k, "x=", "{0:n}".format(x).rjust(10, " "), "itération=", iter, " log2(len(l))=", math.log(len(l)) / math.log(2))
e4a9b638113ed3256094c0704997133349cadc9a
danigunawan/vgg_frontend
/siteroot/controllers/retengine/utils/timing.py
503
3.515625
4
#!/usr/bin/env python import time class TimerBlock: """ Class for timing groups of statements. Used to time blocks of statements contained within a 'with' block e.g. with TimerBlock() as t: <statements> Upon exit from the block, the time taken is stored in t.interval """ def __enter__(self): self.start = time.time() return self def __exit__(self, *args): self.end = time.time() self.interval = self.end - self.start
f21bd1ca010757daee9cbd8e412c4dea216e8c35
artpods56/Matura-Informatyka-Python
/2019 Maj - Rozszerzenie/main.py
2,133
3.546875
4
"""" plik = open("przyklad.txt","r") def czy_potega3(liczba): x = 0 i = 0 while x <= liczba: x = pow(3,i) # print(f"{x} and {liczba}") if x == liczba: return True else: i += 1 return False for liczba in plik: liczba = int(liczba) if czy_potega3(liczba) == True: print(liczba) plik.close() #################################################################### plik = open("liczby.txt","r") def silnia(liczba): i = 1 x = 1 while i <= liczba: x *= i # print(i) i += 1 return x for liczba in plik: suma = 0 liczba = liczba.strip() for char in liczba: char = int(char) suma += silnia(char) # print(f"{suma} i {liczba}") liczba = int(liczba) if suma == liczba: print(f"{suma} to suma siln cyft liczby {liczba}") """"" def nwd(a, b): a = int(a) b = int(b) if b > 0: # print(a, b, a%b) return nwd(b, a%b) return a liczby = [] dzielniki = [] plik = open("przyklad.txt","r") for liczba in plik: liczba = int(liczba.strip()) liczby.append(liczba) #print(liczby) try: i = 1 for liczba in liczby: dzielniki.append(nwd(liczby[i - 1], liczby[i])) # print(f"{nwd(liczby[i - 1], liczby[i])} to najwiekszy dzielnik liczb {liczby[i - 1]} i {liczby[i]}") i += 1 except IndexError: pass print(dzielniki) i = 1 dl_ciag = 0 naj_dl_ciag = 0 start_ciag = 0 try: for i in range(1,500) # print(f"{dzielniki[i-1]} to dzielnik liczb {liczby[i-1]} oraz {liczby[i]}") if i > 1: if d == dzielniki[i] and dzielniki[i] > 1: print(dzielniki[i]) dl_ciag += 1 elif d != dzielniki[i]: if dl_ciag > naj_dl_ciag: naj_dl_ciag = dl_ciag dl_ciag = 0 start_ciag = liczby[i-dl_ciag] d = dzielniki[i] i += 1 except IndexError: pass print(naj_dl_ciag)
623d3b30ad71234981f371de03393dfc239fc574
SamanHashemi/Blue_v1.0
/Actions/Time.py
797
3.703125
4
import datetime import random class Time: def __init__(self): # Trigger words from time self.trigger_words = ["time"] self.priority = 1 def time(self) -> str: now = datetime hour = now.hour minute = now.minute responses = ["Oh, right now it's", "It's", ] if hour > 12: time = str(hour-12) + ":" + str(minute) + "PM" elif hour == 12: time = str(12) + ":" + str(minute) + "PM" elif hour == 0: time = str(12) + ":" + str(minute) + "AM" elif hour < 12: time = str(hour) + ":" + str(minute) + "AM" responses = ["Oh, right now it's " + time, "It's " + time, time + " Is the time"] return str(responses[random.randint(0, len(responses)-1)])
34fb9ad3ecabb18dd4aad355e5fd35e841968157
rnb1984/msc_python
/Algorithms and Datastructures/Prim.py
2,516
3.953125
4
""" Prim Prim's algorithm for minimum spanning trees. Uses Adjcent Matrix. """ import csv file_in = 'stdin' #################################################################################### # Prim Algorithm #################################################################################### def prim(graph, vertices): # initialize the MST and the set X T = set(); X = set(); # select an arbitrary vertex to begin with X.add(0); while len(X) != vertices: crossing = set(); # for each element x in X, add the edge (x, k) to crossing if # k is not in X for x in X: for k in range(vertices): if k not in X and graph[x][k] != 0: crossing.add((x, k)) # find the edge with the smallest weight in crossing edge = sorted(crossing, key=lambda e:graph[e[0]][e[1]])[0]; # add this edge to T T.add(edge) # add the new vertex to X X.add(edge[1]) return T, graph #################################################################################### # Time Algorithm #################################################################################### def readin_graph( file_name ): """ Read in file as graph """ # open the file and get read to read data vertices,num_cities,poss_routes = 0,0,0 graph = [] matrix_in = [] with open (file_name + '.csv', 'rb') as file_in: read = csv.reader(file_in) count =0 for row in read: # retrieve first to integers if count == 0: num_cities = int(row[0]) vertices = num_cities # initialize the graph graph = [[0]*vertices for _ in range(vertices)] elif count == 1: poss_routes = int(row[0]) # store all routes else: # populate the graph u, v, weight = int(row[0]), int(row[1]), float(row[-1]) #print 'row[0]', u, v, weight graph[u][v] = weight graph[v][u] = weight count = count+1 return graph, vertices print "____"*20 g,v = readin_graph( file_in ) T, graph = prim( g,v ) _sum = 0 for edge in T: _sum = _sum + graph[ edge[0] ][ edge[-1] ] print edge[0], edge[-1], graph[ edge[0] ][ edge[-1] ] print _sum from timeit import Timer t = Timer(lambda: prim( g,v ) ) print 'prim', t.timeit(number=1000)
14905df9290c6e1a9017c3747997db20348b6487
mpigrobot/python
/P11/P11-9.py
258
3.96875
4
class Person(object): address='Earth' def __init__(self,name): self.name=name print Person.address p1=Person('Bob') p2=Person('Alice') print p1.address print p2.address Person.address='China' print p1.address print p2.address
6cb17801eff358c27cf2e1a6dd6d44ed6bd6e0e8
mpigrobot/python
/P13/13-19.py
342
3.828125
4
#!/usr/bin/python # -*- coding: utf-8 -*- class Fib(object): def __init__(self, num): a, b, L = 0, 1, [] for n in range(num): L.append(a) a, b = b, a + b self.numbers = L def __str__(self): return str(self.numbers) __repr__ = __str__ f = Fib(10) print f
01cae8ba3abea26904f3b6327d1ac26d9f1f50bf
mpigrobot/python
/P10/10-6.py
373
3.734375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # 匿名函数有个限制,就是只能有一个表达式,不写return,返回值就是该表达式的结果。 print filter(lambda s: s and len(s.strip()) > 0, ['test', None, '', 'str', ' ', 'END']) def is_not_empty(s): return s and len(s.strip()) > 0 print filter(is_not_empty, ['test', None, '', 'str', ' ', 'END'])
b0e4be581e2e383be0e897cdef7171aa5d112108
mpigrobot/python
/P13/13-12.py
536
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- class Student(object): # def get_score(self): # return self._score def set_score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value s = Student() # s.set_score(60) #设置成绩 s.set_score(60) # print s.get_score() #获取成绩 # s.set_score(1000) # print s.get_score()
353e702379ebc8a6b91a62470dee0c0b4ead68c8
mpigrobot/python
/P13/13-3.py
778
3.953125
4
#!/usr/bin/python # -*- coding: utf-8 -*- class Student(object): def __init__(self, name, score): self.name = name self.score = score def __str__(self): return '(%s: %s)' % (self.name, self.score) __repr__ = __str__ def __cmp__(self, s): if self.name < s.name: return -1 elif self.name > s.name: return 1 else: return 0 L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77),100,'Hello,MPIG'] print sorted(L) # 上述 Student 类实现了__cmp__()方法,__cmp__用实例自身self和传入的实例 s 进行比较, # 如果 self 应该排在前面,就返回 -1,如果 s 应该排在前面,就返回1,如果两者相当,返回 0。
49aff59b84406daf53b2c976a2ab435d18a64299
mpigrobot/python
/P5/square.py
152
4
4
import math def area_of_circle(x): s=math.pi*x*x return s r=int(input('Բİ뾶')) print(area_of_circle(r))
c5c8aee344ad853d5c7f77f0f0e9571cf00f71d7
mpigrobot/python
/P4/p4-11.py
213
4.0625
4
try: num1 = int(input('Enter the first number:')) num2 = int(input('Enter the second number:')) print num1/num2 except ValueError as e : print 'You are wrong!' finally: print'The end.' raise e
553b566c6561d1af6e1e00f6bcc1d6b157f0d134
mpigrobot/python
/P4/p4-1.py
196
3.96875
4
try: num1 = int(input('Enter the first number:')) num2 = int(input('Enter the second number:')) print num1/num2 except ZeroDivisionError : print 'The second number cannot be zero'
d87ef401715c1dac44490f3508dd3db5ebb9be08
sanapplegates/Python_qxf2_exercises
/employee.py
417
3.65625
4
class shopping_cart: cart = 0 def __init__(self, item, total): self.item = item self.total = total shopping_cart.cart += 1 def count(self): print ("Total items %d" %shopping_cart.count) def display_cart(self): print ("item : ", self.item, ", total: ", self.total) emp1 = shopping_cart("apple", 20) emp1.display_cart() print("Total items " , shopping_cart.count)
42e25fed3a11b28f2bd4eb5070ce2ff7034eeda1
sanapplegates/Python_qxf2_exercises
/bmi.py
288
4.28125
4
#calculate the bmi of user #user height in kg print("Enter the user's weight(kg):") weight = int(input()) #user height in metres print("Enter the user's height(metre) :") height = int(input()) #Body Mass Index of user bmi = weight/(height*height) print("bmi of user:",bmi)
303095966a5100ec69e9e3036b72ae09c869e0db
maddiecousens/Skills-Assessments
/functions/assessment.py
7,415
4.375
4
# PART ONE # 1. We have some code which is meant to calculate an item cost # by adding tax. Tax is normally 5% but it's higher in # California (7%). # Turn this into a function. Your function will pass in # the default tax amount (5%), a state abbreviation, and the # cost amount as parameters. # If the state is California, apply a 7% tax within the function. # Your function should return the total cost of the item, # including tax. # If the user does not provide a tax rate it should default to 5% def cost_with_tax(cost, state, tax = 0.05): """ Return total cost given cost, state of purchase, and tax. This function takes in the cost of an item, the state of the purchase, and the tax ammount. Tax is defaulted at 0.05. If the state is California, tax is set at 0.07. If tax is passed as a percentage, it will be converted to a decimal representation of percentage. Examples: >>> print cost_with_tax(10, 'CA') 10.7 >>> print cost_with_tax(20.0, 'TX', 18) 23.6 >>> print cost_with_tax(50, 'California', 0.7) Please enter State as an abbreviation None """ #If tax is entered as whole number, convert to percentage if tax >= 1: tax = tax/100.0 #Check whether state entered as abbreviation. if len(state) > 2: print "Please enter State as an abbreviation" return if state == "CA": tax = 0.07 #Accounts for user error in input type try: total_cost = cost + (cost * tax) except TypeError: print "Please enter cost and tax as a number" return return total_cost ##################################################################### # PART TWO # 1. (a) Write a function, `is_berry()`, which takes a fruit name as a string # and returns a boolean if the fruit is a "strawberry", "cherry", or # "blackberry". # (b) Write another function, shipping_cost(), which calculates shipping cost # by taking a fruit name as a string, calling the `is_berry()` function # within the `shipping_cost()` function and returns `0` if ``is_berry() # == True``, and `5` if ``is_berry() == False``. def is_berry(fruit_name): """ Takes string, returns True/False whether fruit is "strawberry", "cherry", or "blackberry". This function takes in a string and returns true if the string is a "strawberry", "cherry", or "blackberry", and False otherwise. Ignores CASE. >>> print is_berry("BLACKberry") True >>> print is_berry("watermelon") False """ #Note, doesn't account for if user enters integer. if fruit_name.isalpha(): return fruit_name.lower() in ["strawberry", "cherry", "blackberry"] else: print "Please only enter alpha characters" def shipping_cost(fruit_name): """ Take string, returns 0 if fruit is "strawberry", "cherry", or "blackberry", otherwise 5. >>> shipping_cost("BLACKberry") 0 >>> shipping_cost("watermelon") 5 """ if is_berry(fruit_name): return 0 else: return 5 # 2. (a) Write a function, `is_hometown()`, which takes a town name as a string # and evaluates to `True` if it is your hometown, and `False` otherwise. # # (b) Write a function, `full_name()`, which takes a first and last name as # arguments as strings and returns the concatenation of the two names in # one string. # # (c) Write a function, `hometown_greeting()`, which takes a home town, a # first name, and a last name as strings as arguments, calls both # `is_hometown()` and `full_name()` and prints "Hi, 'full name here', # we're from the same place!", or "Hi 'full name here', where are you # from?" depending on what `is_hometown()` evaluates to. def is_hometown(town_name): """ Returns boolean of whether town name is 'berkeley'. Ignores case. Example: >>> print is_hometown("BERKELEY") True >>> print is_hometown("El Cerrito") False """ return town_name.lower() == "berkeley" def full_name(first_name, last_name): """ Inputs first and last name as two strings and returns concatenated string. Uses string method title() to print first letter uppercase. Example: >>> print full_name("maddie", "COusens") Maddie Cousens """ return (first_name.title() + " " + last_name.title()) #Another way to do this would be: #return " ".join([first_name.title(), last_name.title()]) def hometown_greeting(town_name, first_name, last_name): """ Takes in three strings, calls town_name and returns string based on boolean. This function takes in town name, first and last name, calls function town_name to determine if the town name is the same as the coders home town. If True, print's message saying they are from the same place, using the full_name function. If False, uses full_name function in print statement to ask where user is from >>> print hometown_greeting("BERKELEY", "maddie", "cousens") Hi, Maddie Cousens, we're from the same place! >>> print hometown_greeting("Concord", "Yogi", "Bear") Hi Yogi Bear, where are you from? """ if is_hometown(town_name): return "Hi, {}, we're from the same place!".format(full_name(first_name, last_name)) else: return "Hi {}, where are you from?".format(full_name(first_name, last_name)) ##################################################################### # PART THREE # 1. Write a function ``increment()`` with a nested inner function, ``add()`` # inside of it. The outer function should take ``x``, an integer which # defaults to 1. The inner function should take ``y`` and add ``x`` and ``y`` together. # 2. Call the function ``increment()`` with x = 5. Assign what is returned to a variable name, addfive. Call # addfive with y = 5. Call again with y = 20. # 3. Make a function that takes in a number and a list of numbers. It should append # the number to the list of numbers and return the list. def increment(x=1): """ Returns a function object, which contains a copy of the value x, and the function add(). I believe the function object is called a 'closure'. Examples: >>> type(increment()) <type 'function'> >>> increment(5)(1) 6 """ def add(y): """ The add function has access to x because it's in scope """ return x + y return add #Create function object addfive addfive = increment(5) #Pass 5, 20 as arguments to addfive addfive(5) addfive(20) def number_appending(number, numbers): """ Takes in a number and a list of numbers, appends number to list. Example: >>> number_appending(5, [1,2,3,4]) [1, 2, 3, 4, 5] >>> number_appending('hi', [1,2,3,4]) Please enter an number to append """ if type(number) in [int, float]: numbers.append(number) return numbers #NOTE, can't write return numbers.append(number) --> returns None else: print "Please enter an number to append" # Doc Strings Testings if __name__ == "__main__": import doctest result = doctest.testmod() if result.failed == 0: print "ALL TESTS PASSED" #####################################################################
4274c82a045ec95daf4c2d77a7954283829306d7
xueer828/practice_code
/python/practice_py/find_2nd_num.py
291
3.890625
4
#find the 2nd largest number def find_2nd(data): if(len(data)<=1): return -1 mx=data[0] scd=-1 for x in xrange(1,len(data)): if(data[x] > mx): scd = mx mx = data[x] elif data[x] > scd: scd = data[x] return scd if __name__ == '__main__': d=[9,3] print find_2nd(d)
c4759dc87e930ac48c13ff16cde5290d71958471
jasminks/ASTR260
/astr260homedirectory/JasminS_EX2_p1b.py
213
3.53125
4
from math import exp import math a=1. b=2. x=1. y=1. for k in range (10): if x > 0: x=y*(a+x**2) else: x= def g(x,y): return b/(x**2+a) for k in range (100): x=f(x,y) y=g(x,y) print x,y
6d1ee772276ad42b49ff73d9487f13bfcf2fddc2
jasminks/ASTR260
/astr260astr260directory/SilvaJ_FINAL_Trap.py
642
3.53125
4
#pi=3.14159265 #c=3*(10**8) #h=(6.636*(10**-34)) #k=1.38*(10**-23) #k2= (2*pi*h*(1/c)*(1/c)*(k**4)*((1/h)**4)) #"k2" is constant beginning of problem k2=8.66432176013e-09 def f(x): from math import e return (x**3)/((e**x) - 1.) a=0.1 b=100 h=0.1 N=int((b-a)/h) if N%2!=0: N=N+1 s1 = 0. s2 = 0. st = 0.5*f(a) + 0.5* f(b) for k in range(1,N/2+1): s1+=f(a+(2*k-1)*h) for k in range(1,N/2): s2+=f(a+2*k*h) for k in range(1,N): st+=f(a+k*h) s = h/3.*(f(a)+f(b)+4*s1+2*s2) st = st*h y = st*k2 #where this is integral multiplied by constant values print "SB constant value using the Trapezoid rule is",y,"\n"
dd5b97ccd64384e8b7f2a71ac500eb4f8d006ee2
jasminks/ASTR260
/astr260homedirectory/trap.py
146
3.59375
4
import math def f(x): return math.exp(-x**2.) N=30 A=0.0 B=3.0 h=(B-A)/N s= 0.5*f(A)+0.5*f(B) for k in range (1,N): s+=f(A+k*h) print (h*s)
ae243d7b52ffc7a999003db36d3fc61147382273
petrov-lab/tuba-seq
/tuba_seq/pmap.py
5,713
3.515625
4
"""Parallel (multi-threaded) map function for python. Uses multiprocessing.Pool with error-resistant importing. There are two map functions: 1) pmap(function, iterable) -> rapid fork-based multi-threaded map function. 2) low_memory_pmap(function, iterable) -> a more memory-efficient version intended for function calls that are individually long & memory-intensive. """ import os from warnings import warn from pickle import PicklingError from progressbar import ProgressBar, Bar, Percentage from time import sleep import numpy as np try: import multiprocessing except ImportError: print("Cannot import 'multiprocessing' module. Parallelization not possible.") pmap = map low_memory_pmap = map larger_iter_pmap = map CPUs = 1 finally: CPUs = multiprocessing.cpu_count() CHUNKS = 50*CPUs def pmap(func, Iter, processes=CPUs): with multiprocessing.Pool(processes=processes) as P: return P.map(func, Iter) def low_memory_pmap(func, Iter, processes=int(round(CPUs/2)), chunksize=1): with multiprocessing.Pool(processes=processes) as P: return [result for result in P.imap(func, Iter)] def large_iter_pmap(func, Iter, processes=CPUs, status_bar=True, nice=True, wait_interval=1): if nice: os.nice(10) try: with multiprocessing.Pool(processes=processes) as P: size = max(1, int(round(len(Iter)/CHUNKS))) rs = P.map_async(func, Iter, chunksize=size) maxval = rs._number_left bar = ProgressBar(maxval=maxval, widgets=[Bar('=', '[', ']'), ' ', Percentage()]) while not rs.ready(): sleep(wait_interval) bar.update(maxval - rs._number_left) bar.finish() return rs.get() except PicklingError: warn("Lambda functions cannot be Pickled for Parallelization. Using single Process.", RuntimeWarning) return list(map(func, Iter)) class _mid_fastq_iter(object): def __init__(self, filename, seq_id, start, stop): self.filename = filename self.seq_id = seq_id self.start = start self.stop = stop def __iter__(self): self.f = self.filename.open('rb') self.f.seek(self.start) # Find the beginning of the next FASTQ header lines = [] for i, line in zip(range(5), self.f): lines.append(line) if line.startswith(self.seq_id): break else: raise RuntimeError("Took more than 4 lines to find header in middle of FASTQ file (start pos: {:}, stop pos: {:}, file length: {:}):\n".format( self.start, self.stop, self.filename.stat().st_size)+'\n'.join(lines)) self.f.seek(self.f.tell() - len(line)) return self def __next__(self): if self.f.tell() < self.stop: header = self.f.readline() dna = self.f.readline() self.f.readline() qc = self.f.readline() return header, dna, qc else: self.f.close() raise StopIteration def __exit__(self): self.f.close() compressions = dict(gzip='gunzip',gz='gunzip', bz2='bunzip2', lzma='unxz', xz='unxz') from pathlib import Path def fastq_map_sum(in_fastq, out_filenames, func, CPUs=CPUs-1, temp_dir_prefix='tmp', uncompress_input=True): """Asynchronously processes an input fastq file. Processes reads from a single FASTQ file by distributing the analysis work *and* I/O. A thread is devoted to reading the input FASTQ, threads are devoted to writing to every output file, and a number of worker threads communicate with these I/O threads to process the reads. Job queues mediate thread interactions. Inputs: ------- in_fastq : Input FASTQ filename. Must be uncompressed. out_files : List of output filenames. Compression must be smart_open compliant. func : func(fastq_read_iter, out_filenames) -> tuple of sum-able objects. """ in_file = Path(in_fastq) if in_file.suffix in compressions and uncompress_input: algorithm = compressions[in_ext] print("Uncompressing", in_fastq, 'with', algorithm, "(Cannot parallel-process a compressed file)...") os.system([algorithm, in_fastq]) in_file = Path(in_file.stem) file_length = in_file.stat().st_size start_positions = np.linspace(0, file_length, CHUNKS, False).round().astype(int) stop_positions = np.r_[start_positions[1:], file_length] sample = in_file.name.partition('.fastq')[0] Dir = Path(temp_dir_prefix+sample) with in_file.open('rb') as f: seq_id = f.readline().partition(':'.encode('ascii'))[0] Iter = [(_mid_fastq_iter(in_file, seq_id, start, stop), [str(Dir / head / (str(start)+tail)) for head, tail in map(os.path.split, out_filenames)]) for start, stop in zip(start_positions, stop_positions)] for head, tail in map(os.path.split, out_filenames): os.makedirs(head, exist_ok=True) (Dir / head).mkdir(parents=True, exist_ok=True) with multiprocessing.Pool(processes=CPUs) as P: rs = P.starmap_async(func, Iter, chunksize=1) outputs = rs.get() intermediate_files = list(zip(*[outfiles for it, outfiles in Iter])) for f, i_files in zip(out_filenames, intermediate_files): os.system("cat "+' '.join(i_files)+" >> "+f) for File in i_files: os.remove(File) (Dir / f).parent.rmdir() Dir.rmdir() return list(map(sum, zip(*outputs))) if type(outputs[0]) == tuple else sum(outputs)
e129e27b4be8a5ad78bad47819fc9a60f10c410a
CMT040307/First
/First attempt.py
657
3.8125
4
def master(): #name and age name = input("What is your name?") age = int(input("How old are you?")) print("Hello", name) gender = input("Are you male or female?") if gender.upper() == "MALE": print("I am male too :)") else: print("Nice, I am male") fav_food = input("What is your favourite food?") if fav_food.upper() == "PIZZA": print("That's my favourite food too :) ") else: print("That's a great favourite food! Mine is pizza :) ") restart = input("Would you like to restart? yes = 1/no = 0") if restart.lower() == "1": master() else: exit() master()
38179717b10493e88e3763bd31da34707767ed05
Alessandro-Francia/Compiti-per-10-12
/es_3.py
486
3.9375
4
vocali = ["a","e","i","o","u", " "] while True: italiano = input ("dimmi una parola o una frase in italiano") rovarspraket = "" for lettera in italiano: if lettera not in vocali: rovarspraket += lettera + "o" + lettera else: rovarspraket += lettera print ("la parola in rovarspraket è", rovarspraket) continuare = input ("scrivi 'si' se vuoi inserirne un'altra ") if continuare != "si": break
71438d0ad0f123c96fb350704843653d31b79562
bekahbooGH/Trees
/binary-trees.py
4,571
4.125
4
# Implement a Binary Tree data structure class Binary_Node(): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def descendants_preorder(self): print(self.data) if self.left: self.left.descendants_preorder() if self.right: self.right.descendants_preorder() def descendants_inorder(self): if self.left: self.left.descendants_inorder() print(self.data) if self.right: self.right.descendants_inorder() def descendants_postorder(self): if self.left: self.left.descendants_postorder() if self.right: self.right.descendants_postorder() print(self.data) # OUTPUT: 7 1 34 2 0 # STACK def count_nodes(self): count = 1 # Line 1 if self.left: # Line 2 count += self.left.count_nodes() # Line 3 if self.right: # Line 4 count += self.right.count_nodes() # Line 5 return count # Line 6 def height(self): if not self: return 0 if self.left: lheight = self.left.height() if self.right: rheight = self.left.height() if lheight > rheight: return lheight+1 else: return rheight+1 def printGivenLevel(self, level): if not self: return elif level == 1: print(self.data, end=" ") elif level > 1: self.left.printGivenLevel(level - 1) self.right.printGivenLevel(level - 1) def level_order_traversal(self): h = self.height for i in range(h): self.printGivenLevel(i) class Binary_Tree(): def __init__(self, root=None): self.root = root def add_node(self, node): # first check to see if the root of our tree is empty if self.root == None: self.root = node return else: def check_children(self, node): if not self.left: self.left = node return if not self.right: self.right = node return check_children(self.left, node) check_children(self.root, node) # Replace a node def replace_node(self, node_to_replace, new_node): nodes_to_visit = [self.root] # current = self.root # [9] while nodes_to_visit: current = nodes_to_visit.pop(0) # 9 if current.data == node_to_replace.data: # 9 == 8 node_to_replace.data = new_node.data return else: nodes_to_visit.extend([current.left, current.right]) print(nodes_to_visit) # def preorderTraversal(self, root): # # -> List[int]: # # return the preorder traversal of its nodes' values. # if not root: # return [] # if root: # return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) def preorderTraversal(self, root): # -> List[int]: if not root: return [] # if root: # return root.val + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) print("String: root.right") print(root.right) print("Self.preorderTraversal") print(self.preorderTraversal(root.right)) print("type preorder Traversal") print(type(self.preorderTraversal(root.right))) def inorderTraversal(self, root): # -> List[int]: # if root == None: root_list = [] def fxn(root): if root == None: return root_list else: fxn(root.left) root_list.append(root.val) fxn(root.right) fxn(root) return root_list node10 = Binary_Node(10) b_tree = Binary_Tree() b_tree.add_node(node10) # print(root) node5 = Binary_Node(5) b_tree.add_node(node5) node8 = Binary_Node(8) b_tree.add_node(node8) node15 = Binary_Node(15) b_tree.add_node(node15) node7 = Binary_Node(7) b_tree.add_node(node7) node10.descendants_preorder() print() node10.descendants_inorder() print() node10.descendants_postorder() # STACK # A: count_nodes(node7) count=5 Line 5 # Return 5 print(node5.count_nodes()) print() node10.height()
86a8f02df08ee0de1e9f3c613f096430637bd717
kellywzheng/mycd
/mycd.py
5,252
3.625
4
import sys import re ''' Reduce multiple consecutive forward-slashes ("/") to one forward-slash Remove any sequence that consists of a file name component (other than "." or ".."), followed by "/", followed by the file name component ".." ''' def simplify(directory): while True: old_dir = directory directory = re.sub("//+", '/', directory) # replace multiple "/" to a single slash idx = directory.find('[A-Za-z0-9]+/../') # find the first occurence of "filename/../" if idx > 0: prev_idx = directory.rfind('/', 0, idx) # find the last occurence of "/" in the range 0 to idx idx = idx + 4 # increment idx to now be at the start of the next file name component directory = directory[0:prev_idx + 1] + directory[idx: ] # remove the "/../" sequence if directory == old_dir: # break out of loop when the above conditions no longer apply break return directory ''' Given the current directory path and a new directory path, return either a new path or an error message ''' def get_new_path(curr_dir, new_dir): curr_dir_stack = [] curr_dir_split = curr_dir.split("/") # Split the current directory by "/" and add to stack for split in curr_dir_split: if split: curr_dir_stack.append(split) new_dir_split = new_dir.replace("/", "!/!").split("!") # Keep "/" in the new path when splitting new_dir_split = [x for x in new_dir_split if x != ""] if ( # Check if the new directory path is valid not new_dir_split[0].isalnum() and new_dir_split[0] != "/" and new_dir_split[0] != "." and new_dir_split[0] != ".." ): return(new_dir + ":" + " No such file or directory") if new_dir_split[0] == "/": # If the new directory path contains a leading "/" new_dir_stack = [] ''' OLD VERSION of the for loop for split in new_dir_split: if split and split.isalnum(): # Fill stack according to the path in new_dir new_dir_stack.append(split) new_dir_split.remove(split) ''' j = 0 size = len(new_dir_split) for i in range(size): if ( # Check if the new directory path is valid not new_dir_split[j].isalnum() and new_dir_split[j] != "/" and new_dir_split[j] != "." and new_dir_split[j] != ".." ): return(new_dir_split[j] + ":" + " No such file or directory") if new_dir_split[j] and new_dir_split[j].isalnum(): new_dir_stack.append(new_dir_split[j]) new_dir_split.remove(new_dir_split[j]) if j != 0: j -= 1 else: j += 1 continue stack = process_stack(new_dir_stack, new_dir_split) else: stack = process_stack(curr_dir_stack, new_dir_split) result = "" # Create a path based on the stack if not stack: result = "/" else: for section in stack: if section: result += "/" result += section return(result) ''' Given a stack and a list of a split directory path, update the stack based on the commands seen in the list ''' def process_stack(stack, split_list): for i in range(0, len(split_list)): if split_list[i] == "..": if stack: stack.pop() elif split_list[i] == "." or split_list[i] == "/": continue else: stack.append(split_list[i]) return stack ''' Run the example test cases ''' def run_tests(): test_pairs = [ ("/", "abc"), ("/abc/def", "ghi"), ("/abc/def", ".."), ("/abc/def", "/abc"), ("/abc/def", "/abc/klm"), ("/abc/def", "../.."), ("/abc/def", "../../.."), ("/abc/def", "."), ("/abc/def", "..klm"), ("/abc/def", "//////"), ("/abc/def", "......"), ("/abc/def", "../gh///../klm/.") ] for pair in test_pairs: new_directory = simplify(pair[1]) print(get_new_path(pair[0], new_directory)) def main(): if len(sys.argv) == 1: run_tests() return elif len(sys.argv) == 3: curr_directory = sys.argv[1] new_directory = sys.argv[2] new_directory = simplify(new_directory) print(get_new_path(curr_directory, new_directory)) else: print("Invalid input") return if __name__ == "__main__": main()
635cf28c6d55c10d3de2eade919273696764bdd1
belochenko/python-algorithm
/codewars/snail_sort.py
2,069
3.859375
4
# Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. # array = [[1,2,3], # [4,5,6], # [7,8,9]] # snail(array) #=> [1,2,3,6,9,8,7,4,5] # For better understanding, please follow the numbers of the next array consecutively: # array = [[1,2,3], # [8,9,4], # [7,6,5]] # snail(array) #=> [1,2,3,4,5,6,7,8,9] # Classic solutin def snail(array): snail = [] n = len(array) n2 = n*n row_len = n col_len = n row_start = 0 col_start = 0 count = 0 n_count = 0 if not array[0]: return [] while True: ## Move right for c in range(col_start, col_start + row_len): snail.append(array[row_start][c]) count += 1 n_count += 1 if n_count >= n2: return snail col_start += (count - 1) row_start += 1 col_len -= 1 count = 0 ## Move down for r in range(row_start, row_start + col_len): snail.append(array[r][col_start]) count += 1 n_count += 1 if n_count >= n2: return snail row_start += (count - 1) col_start -= 1 count = 0 row_len -= 1 ## Move left for c in range(col_start, col_start - row_len, -1): snail.append(array[row_start][c]) count += 1 n_count += 1 if n_count >= n2: return snail col_start -= (count - 1) row_start -= 1 col_len -= 1 count = 0 ## Move up for r in range(row_start, row_start - col_len, -1): snail.append(array[r][col_start]) count += 1 n_count += 1 if n_count >= n2: return snail row_start -= (count - 1) col_start += 1 count = 0 row_len -= 1 #Python-style solution def snail_python(array): out = [] while len(array): out += array.pop(0) array = list(zip(*array))[::-1] # Rotate return out
9889724ee39f3f308ef0e7356729fb4ed73ae0c9
hanhan1280/mips241
/test/big/generate-single-op.py
1,942
3.578125
4
#!/usr/bin/env python3 import fileinput import struct import sys import signal signal.signal(signal.SIGINT, lambda x, y: sys.exit(0)) def get_skel(s): """Get a tuple representing an instrution skeleton. Args: s: String of chars in {0, 1, x} of the skeleton Returns: Tuple (before, length, after), where - before is the number before the mask - length is the length of x's in the mask - after is the number after the mask """ i = 0 # get number before x's before = 0 while i < len(s): if s[i] != 'x': assert s[i] == '0' or s[i] == '1' before += before before += int(s[i]) else: break i += 1 # get number of x's xlen = 0 while i < len(s): if s[i] == 'x': xlen += 1 else: break i += 1 # get number of 0s after x's zerolen = 0 while i < len(s): if s[i] == '0': zerolen += 1 else: break i += 1 # get number afer x's after = 0 while i < len(s): assert s[i] == '0' or s[i] == '1' after += after after += int(s[i]) i += 1 return (before, xlen, zerolen, after) def gen_from_skel(skel): """ Iterator for all possible instructions, given a skeleton. See get_skel(s). Args: skel: skel, from get_skel Yields: A next possible instruction in machine code, as a word. """ (before, xlen, zerolen, after) = skel increment = 1 << (after.bit_length() + zerolen) result = (before << (xlen + zerolen + after.bit_length())) + after for i in range(1 << xlen): yield result result += increment for line in fileinput.input(): line = line.strip() for instruction in gen_from_skel(get_skel(line)): sys.stdout.buffer.write(struct.pack('>I', instruction))
4be0f306a11be87ba2bea6c955205f19e993eb2d
yolkoo95/personal-web
/appstore/cachefile/generator.py
1,137
3.828125
4
# the program will generate greet message according to server/client time # and select a wallpaper number randomly # 'wallpaper_num' for select a wallpaper # 'greet' will change with time # 'date' to record date of time # 'color_mode' to change the background color at night import random, time def generator(): # format time into something like Sat Mar 08 22:12:03 2020 cur_time = time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) wallpaper_daytime = random.randint(0, 22) wallpaper_night = random.randint(23, 30) # display different greet information at different time date = cur_time[0:10] hour = int(cur_time[11:13]) greet = 'Good' color_mode = 'bg-white' if 5 <= hour < 13: greet += ' Morning' wallpaper = wallpaper_daytime elif 13 <= hour < 19: greet += ' Afternoon' wallpaper = wallpaper_daytime else: greet += ' Evening' wallpaper = wallpaper_night color_mode = 'bg-whitesmoke' return { 'wallpaper_num': wallpaper, 'greet': greet, 'date': date, 'color_mode': color_mode, }
092af5d39ab8a46b6ca23b6c5d352c47ff780810
nahuelv/frro-soporte-2019-11
/practico_03/ejercicio_02.py
1,022
3.609375
4
# Implementar la funcion agregar_persona, que inserte un registro en la tabla Persona # y devuelva de los datos ingresados, el id del nuevo registro. import sqlite3 import datetime from practico_03.ejercicio_01 import reset_tabla def conexion (): db = sqlite3.connect('C:\\Users\\Nahuel\\Desktop\\db_python.db') return db def agregar_persona(nombre, nacimiento, dni, altura): con = conexion() c = con.cursor() query = "INSERT INTO Persona (nombre, fechaNacimiento, dni, altura) VALUES (?,?,?,?)" datos = (nombre, datetime.datetime.strftime( nacimiento, "%Y-%m-%d"), dni, altura) c.execute(query, datos) c.close() con.commit() con.close() return c.lastrowid @reset_tabla def pruebas(): id_juan = agregar_persona('juan perez', datetime.datetime(1988, 5, 15), 32165498, 180) id_marcela = agregar_persona('marcela gonzalez', datetime.datetime(1980, 1, 25), 12164492, 195) assert id_juan > 0 assert id_marcela > id_juan if __name__ == '__main__': pruebas()
7f200a512c5821b826df1a6eec5259ef91484125
nahuelv/frro-soporte-2019-11
/practico_01_cvg/ejercicio_08.py
547
4.21875
4
""" Definir una función superposicion() que tome dos listas y devuelva True si tienen al menos 1 miembro en común o devuelva False de lo contrario. Escribir la función usando el bucle for anidado. """ lista_1 = ["a", "b", "c"] lista_2 = ["b", "d", "e"] def superposicion (lista1, lista2): for i in range (0, len(lista1)): for j in range (0, len(lista2)): if lista1[i]==lista2[j]: return True return False assert superposicion(["a","b"],["f","b"]) == True print(superposicion(lista_1, lista_2))
b88a715b7625b1b27f47e9cb6098e00e8e616f7e
lexruee/project-euler
/problem_9.py
326
4.125
4
# -*- coding: utf-8 -*- """ A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc """ def main(): #TODO pass if __name__ == '__main__':main()
3c5f799e3a18974c27dea21f2f4f29d57746028b
lexruee/project-euler
/problem_25.py
365
3.796875
4
# -*- coding: utf-8 -*- def fibonacci(n): fn1 = 1 fn2 = 1 if n<2: return fn1 for i in xrange(2,n): fn = fn1 + fn2 fn2 = fn1 fn1 = fn return fn1 print fibonacci(12) i = 12 f = 0 while True: f = fibonacci(i) if len(str(f))==1000: break i +=1 print "%s-th fib number has 1000 digits" % i
56e091e0215e5f1072d5b1f78eae6b6d783389e8
chotu07/test1
/test1.py
3,164
4.09375
4
# list is a collection of homogenous and heterogenous data types l=[1,2,3,4] type(l) list=[1,2,3,4,5] print(list[0]) #1.append is used to add one more l=[1,2,3,4] l.append(5) print(l) #2. extend is used to add or merge the two lists l1=[1,2,3,4] l2=[5,6,7] l1.extend(l2) print(l1) #3.remove is used to eliminate the value l=[1,2,3,4] l.remove(4) print(l) #4.insert is used to add the value in a required index position l=[2,3,4,5] l.insert(0,1) print(l) #5.pop is used to delete the last index value from the list l=[1,2,3,45,6,7] l.pop() print(l) #6. sort is used to give the priority to integers even strings also presented in the list l=[3,2,4,1] l.sort() print(l) #7.reverse is used to be as it is l=[1,2,3,4,5] l.reverse() print(l) #2. tuple #1.index is used to used to find the index value t=(1,2,3,4,5) t.index(4) print(t.index(4)) l=[1,2,3,4,5] l.index(2) print(l.index(2)) #2.count is use dto find the number of accurences t=(1,2,2,2,3,4,4,5) t.count(2) print(t.count(2)) #3.string is collection of words enclosed between quatations s="python" s="welcome to python" # string formating s1="welcome to" s2=" python" print (s1+s2) age = 22 address = "banglore" s=" age is %s, and im living in %s"%( age, address) print(s) # string methods #1.upper is used to covert the letters into uppercase s="welcome" print(s.upper()) #2.lower s="PYTHON" print(s.lower()) #replace s="wlcome to python" print(s.replace("python","banglore")) #strip is by default removes starting space s=" welcome to python " print(s) s="wlcomreto python" print(s.strip("python")) #index s="hello" print(s[0]) print(s[-1]) # to count no of accurances s="welcome" print (s.count("w")) print(s.count("o")) #split s="welcome to python" print(s.split('o')) print(s.split('to')) s="welcome to python" print(s.startswith("python")) #capitalise is used to make the first capital letter s="welcometp python" print(s.capitalize()) s="welcome to world" print(s.find('wo')) #4.format s="welcome to world" print(s.format()) #slicing can be used to find the subsequence based on index l=[1,2,3,4,5,6,7,8,9] print(l[3:]) print(l[3:7]) print(l[-4:]) print(l[-5:-1]) print(l[0:-1]) s=["welcome to python"] print(s[:-1]) print(s[-6:]) #control flow statements #1.conditional statements #1.simple if n=10 if n%2==0: print('even') #if else n=5 if n%2==0: print('even') # else: # print('odd') # n=2 # if n==1: # print('english') # elif n==2: # print('hindi') # elif n==3: # print('telugu') # #programme # n=2 # if n==2: # print('hello') # else: # print('not valid') #2.looping statements # #1.for loop # l=[1,2,3,4,5] # for i in l: # print(i) # list=[1,2,3,4,5,6,7,8] # even=[] # odd=[] # for i in list: # if i%2==0: # even.append(i) # else: # odd.append(i) # print(even) # print(odd) #while loop # n=1 # while n<=10: # print(n) a=1 even=[] odd=[] while a<=10: if a%2==0: even.append(a) else: odd.append(a) a+1 print(even) print(odd)
e0bddd821d6aae829c97600cc1ae62c614275d91
HarshMule20/Python_Practices
/array/delete.py
204
3.84375
4
from array import * arr=array('i',[]) for i in range(5): a=int(input("Enter value= ")) arr.append(a) print(arr) for i in range(5): if(i==2): arr.remove(arr[i]) break print(arr)
2bad6c4aa30bef8d12f781f049c302556d57a8ae
HarshMule20/Python_Practices
/polymorphism/value.py
193
3.671875
4
class val: def __init__(self,m1,m2): self.m1=m1 self.m2=m2 def __str__(self): return '{} {}'.format(self.m1, self.m2) v1=val(4,5) v2=val(6,4) print(v1) print(v2)
29bdc660d07f403bd5610a1ec2e9a7f57e5b7cca
HarshMule20/Python_Practices
/class/compare_two_numbers.py
363
3.8125
4
class addition: #def __init__(self): # self.a = int(input("Enter the first value: ")) # self.b = int(input("Enter the second value: ")) def show(self,a,b): self.a=a self.b=b if self.a==self.b: return True obj=addition() if obj.show(7,7): print("They are same") else: print("They are different")
0ebad3149b9a0b6366753473c6d2eddd630215a8
Ammo-byte/Spirit-Trackr
/distancecalculator/spirittrackr.py
1,869
3.734375
4
import pandas as pd import numpy as np #Haversine Formula to calculate the distance between two points on a sphere, (code sample from Google) def haversine_distance(latitude1, longitude1, latitude2, longitude2): r = 6371 phi1 = np.radians(latitude1) phi2 = np.radians(latitude2) delta_phi = np.radians(latitude2 - latitude1) delta_lambda = np.radians(longitude2 - longitude1) a = np.sin(delta_phi / 2)**2 + np.cos(phi1) * np.cos(phi2) * np.sin(delta_lambda / 2)**2 res = r * (2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))) return np.round(res, 2) #In a real app, this current latitude and longitude would be fetched in real time via Google Maps API #However, Google Maps API is paid, so we cannot use their services at this time #For this demo, the user manually enters their latitude and longitude currentlatitude = float(input("What is your current latitude?")) currentlongitude = float(input("What is your current longitude?")) landmarks = pd.DataFrame(data={ 'Landmark': ['Kwakiutl Statue', 'Neyagawa Park', 'Bronte Harbour'], 'Lat' : [43.723047, 43.457796, 43.394591], 'Lon' : [-79.721298, -79.729519, -79.708563] }) distances_km = [] for row in landmarks.itertuples(index=False): distances_km.append( haversine_distance(currentlatitude, currentlongitude, row.Lat, row.Lon) ) landmarks['Distance (km)'] = distances_km print (landmarks) #Output to determine whether or not to send notification if distances_km[0] < 5: print("You are nearby the Kwakiutl Statue!") else: print("You are not nearby the Kwakiutl Statue!") if distances_km[1] < 5: print("You are nearby Neyagawa Park!") else: print("You are not nearby Neyagawa Park!") if distances_km[2] < 5: print("You are nearby Bronte Harbour!") else: print("You are not nearby Bronte Harbour!")
13408d2173708d52c7f39c106995a546acb734a2
OlegAvdienokTaskGit/Python-slices-tasks
/slice_6.py
404
3.640625
4
""" Дана строка, вывести все нечётные индексы. Возьмём всю строку, и пройдемся по ней, начиная с 2 элемента, используя шаги (шаг в 2 символа). Так как первый индекс [0], то отсчет идёт от первого символа. """ string = "0123456789" print(string[1::2])
d9a2d697214d347ceb8c188dd339bfbf3e60ff10
arkajitb/DataStructures
/secondweek_second.py
1,439
4.0625
4
# Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. # Example 1: # Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac" # Example 2: # Input: S = "ab##", T = "c#d#" # Output: true # Explanation: Both S and T become "". # Example 3: # Input: S = "a##c", T = "#a#c" # Output: true # Explanation: Both S and T become "c". # Example 4: # Input: S = "a#c", T = "b" # Output: false # Explanation: S becomes "c" while T becomes "b". # Note: # 1 <= S.length <= 200 # 1 <= T.length <= 200 # S and T only contain lowercase letters and '#' characters. class Solution: def backspaceCompare(self, S: str, T: str) -> bool: S = list(S) T = list(T) counter_S = [] counter_T = [] for i in range(len(S)): if(S[i] == '#'): if(len(counter_S) == 0): continue; else: counter_S.pop() else: counter_S.append(S[i]) for i in range(len(T)): if(T[i] == '#'): if(len(counter_T) == 0): continue; else: counter_T.pop() else: counter_T.append(T[i]) if(counter_S == counter_T): return True else: return False
5203ff3707c3eccf69e8794cc7a41897538bde10
BillBillBillBill/qlcoder
/755a/solve.py
559
3.65625
4
# coding: utf-8 import os def find_max_size_file(dir_path): dirs_and_files = os.listdir(dir_path) dirs_and_files_path = map(lambda x: dir_path + "/" + x, dirs_and_files) max_file_size_in_path = map(lambda x: (x, os.path.getsize(x)) if os.path.isfile(x) else find_max_size_file(x), dirs_and_files_path) if not max_file_size_in_path: return ("", 0) max_file = max(max_file_size_in_path, key=lambda s: s[1]) return max_file if __name__ == '__main__': print find_max_size_file('/home/bill/Desktop/github/qlcoder/755a/root')
3a539262ecf0f63733dd89c374b1ae57dd515977
creichelt/100daysofpython_beginner
/003_treasureisland.py
1,094
4.03125
4
print("Welcome to Treasure Island!\n") print("\nYour mission is to find the treasure...|") print("\nWARNING: not intended for children!\n") cross = input("You're at a cross road. Do you want to take 'left' or 'right'? ").lower() if cross == 'left': lake = input("You came to a lake. There is an island in the middle. Do you want to 'wait' for a boat or 'swim' across? ").lower() if lake == 'wait': color = input("You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow, and one green. Which color do you choose? ").lower() if color == 'yellow': print("You found the treasure!") print("You win!") elif color == 'green': print("You get showered wih acid...") print("Game over!") elif color == 'red': print("Blades come crashing down on you...") print("Game over!") elif lake == 'swim': print("A sea monster grabs your leg....") print("Game over!") elif cross == 'right': print("You fall into a pit...") print("Game over!")
ef5a89c7fccc71073f3d4809b89e73fe5a126983
nortxort/tinybot-rtc
/apis/other.py
3,454
3.671875
4
""" Contains functions to fetch info from different simple online APIs.""" import util.web def urbandictionary_search(search): """ Searches urbandictionary's API for a given search term. :param search: The search term str to search for. :return: defenition str or None on no match or error. """ if str(search).strip(): urban_api_url = 'http://api.urbandictionary.com/v0/define?term=%s' % search response = util.web.http_get(url=urban_api_url, json=True) if response['json'] is not None: try: definition = response['json']['list'][0]['definition'] return definition.encode('ascii', 'ignore') except (KeyError, IndexError): return None else: return None def weather_search(city): """ Searches worldweatheronline's API for weather data for a given city. You must have a working API key to be able to use this function. :param city: The city str to search for. :return: weather data str or None on no match or error. """ if str(city).strip(): api_key = '' if not api_key: return 'Missing api key.' else: weather_api_url = 'http://api.worldweatheronline.com/premium/v1/weather.ashx?key=%s&q=%s&format=json' % \ (api_key, city) response = util.web.http_get(url=weather_api_url, json=True) if response['json'] is not None: try: pressure = response['json']['data']['current_condition'][0]['pressure'] temp_c = response['json']['data']['current_condition'][0]['temp_C'] temp_f = response['json']['data']['current_condition'][0]['temp_F'] query = response['json']['data']['request'][0]['query'].encode('ascii', 'ignore') result = '%s. Temperature: %sC (%sF) Pressure: %s millibars' % (query, temp_c, temp_f, pressure) return result except (IndexError, KeyError): return None else: return None def whois(ip): """ Searches ip-api for information about a given IP. :param ip: The ip str to search for. :return: information str or None on error. """ if str(ip).strip(): url = 'http://ip-api.com/json/%s' % ip response = util.web.http_get(url=url, json=True) if response['json'] is not None: try: city = response['json']['city'] country = response['json']['country'] isp = response['json']['isp'] org = response['json']['org'] region = response['json']['regionName'] zipcode = response['json']['zip'] info = country + ', ' + city + ', ' + region + ', Zipcode: ' + zipcode + ' Isp: ' + isp + '/' + org return info except KeyError: return None else: return None def chuck_norris(): """ Finds a random Chuck Norris joke/quote. :return: joke str or None on failure. """ url = 'http://api.icndb.com/jokes/random/?escape=javascript' response = util.web.http_get(url=url, json=True) if response['json'] is not None: if response['json']['type'] == 'success': joke = response['json']['value']['joke'] return joke return None
4227dcb300d4fa307993f81eb8decf6586738d99
penroselearning/pystart
/ATM Machine.py
1,224
4.0625
4
PASSWORD='12345@' account_balance=60000 attempts=3 pin=input("Enter your Account Pin:\n") attempts -= 1 while pin!=PASSWORD: if attempts > 0: pin = input(f'''Sorry, the password is incorrect.You have {attempts} more attempt/s. Please enter your Account Pin again:\n''') attempts -= 1 else: print('Sorry, you have entered an incorrect password 3 times. Your account has been blocked :-(') exit() print('-'*30) print("Welcome to your Account.") action= int(input('''Would you like to: 1. Deposit Money 2. Withdraw Money 3. View Balance ------------------------ Please choose the number corresponding to the action of your choice:\n''')) if action == 1: amount = int(input('How much money would you like to deposit in your account (USD). Please type the number:\n')) account_balance += amount print(f'Your new account balance is USD {account_balance}') elif action == 2: amount = int(input('How much money would you like to withdraw from your account (USD). Please type the number:\n')) account_balance -= amount print(f'Your new account balance is USD {account_balance}') elif action == 3: print(f'Your current account balance is USD {account_balance}') print('Thank you!')
70bccb7a493552961294f62cbd1d8a8bd9c7ae8b
penroselearning/pystart
/Arrival Time.py
262
3.84375
4
from datetime import datetime,timedelta departure = datetime.now() distance=5 speed=10 time = distance/speed arrival = departure + timedelta(hours=time) print(f"The boat Departure time: {departure.time()}") print(f"The boat will Arrive at {arrival.time()}")
2ff8a92f137f31da8bce56cb5444c86087d9f393
Raviprakash-B/Python-basics
/list_comp.py
253
3.796875
4
#list comprehension #LAMBDA a = lambda x,y : x if x>y else y print(a(2,5)) #MAP n = [1,2,3,4,5] print(list(map(lambda x: x**2,n))) #FILTER n = [1,2,3,4,5] print(list(filter(lambda x: x>3,n))) #REDUCE n = [1,2,3,4,5] print(reduce(lambda x,y: x+y,n))
588ea48e739e6762860446353ef2a693712f0083
Raviprakash-B/Python-basics
/else.py
79
3.609375
4
x = 1 if x == 2: print("not found") else: print("found",x) #python3 else.py
918f441facb7f0e339d36bb9d2f599310e44d6f6
saadkhan321/Project3_ND
/Python_Code/audit.py
4,452
3.921875
4
""" Your task in this exercise has two steps: - audit the OSMFILE and change the variable 'mapping' to reflect the changes needed to fix the unexpected street types to the appropriate ones in the expected list. You have to add mappings only for the actual problems you find in this OSMFILE, not a generalized solution, since that may and will depend on the particular area you are auditing. - write the update_name function, to actually fix the street name. The function takes a string with street name as an argument and should return the fixed name We have provided a simple test so that you see what exactly is expected """ # Source : http://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list-in-python # Source : http://www.decalage.info/en/python/print_list # Source : http://stackoverflow.com/questions/914715/python-looping-through-all-but-the-last-item-of-a-list # Source : http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-for-loops-in-python import xml.etree.cElementTree as ET from collections import defaultdict import re import pprint import string OSMFILE = "example.osm" street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE) expected = ["Street", "Avenue", "Boulevard", "Drive", "Court", "Place", "Square", "Lane", "Road", "Trail", "Parkway", "Commons"] # UPDATE THIS VARIABLE mapping = { "St": "Street","St.": "Street", "Ave": "Avenue", "Rd.": "Road", "N." : "North"} def audit_street_type(street_types, street_name): m = street_type_re.search(street_name) if m: street_type = m.group() if street_type not in expected: street_types[street_type].add(street_name) def is_street_name(elem): return (elem.attrib['k'] == "addr:street") def audit(osmfile): osm_file = open(osmfile, "r") street_types = defaultdict(set) for event, elem in ET.iterparse(osm_file, events=("start",)): if elem.tag == "node" or elem.tag == "way": for tag in elem.iter("tag"): if is_street_name(tag): audit_street_type(street_types, tag.attrib['v']) return street_types def update_name(name, mapping): # YOUR CODE HERE name_value = name.split(' ') # Splitting the street address by space and storing in a list # storing the first word of the street name name_first = name_value[0] # storing the first part of the street name, except the last word name_first_part = name_value[:-1] # storing the last word of the street name name_last = name_value[-1] # storing the last part of the street name, except the first word name_last_part = name_value[1:] # storing the middle part of the street name name_middle_part = name_value[1:-1] for k,m in mapping.items(): # iterating over the mapping dictionary # correcting last part of street names (St, St., Ave, Rd.) if name_last == k: # checking in last word of address is present in dictionary key name_last = m.split() # replacing last word with a better name name_list = name_first_part + name_last # combining first part and last word name = " ".join(name_list) # converting list to a string # correcting first part of street names (N.) elif name_first == k: name_first = m.split() # replacing first word with a better name name_list = name_first + name_middle_part + name_last # combining first word and last part name = " ".join(name_list) # converting list to a string else: continue return name def test(): st_types = audit(OSMFILE) assert len(st_types) == 3 pprint.pprint(dict(st_types)) for st_type, ways in st_types.iteritems(): for name in ways: better_name = update_name(name, mapping) print name, "=>", better_name if name == "West Lexington St.": assert better_name == "West Lexington Street" if name == "Baldwin Rd.": assert better_name == "Baldwin Road" # additional assertion added to check "N." if name == "N. Lincoln Ave": assert better_name == "North Lincoln Avenue" if __name__ == '__main__': test()
9775d082ef3043fb020ffd1ac9137534069c6444
adi-spec/nauka_pythona
/haslo.py
342
3.5625
4
#! /usr/bin/python #haslo='woj' haslo=input() pwd=len(haslo) #gwiazdki= #secret='' if pwd<3: print("haslo za krotkie") else: for i in range(1, pwd -1): print(haslo[0] + (pwd-2)*'*' + haslo[-1]) # break #haslo = 'wojtek' #gwiazdki = (len(haslo) - 2) * "*" #secret = haslo[0] + gwiazdki + haslo[-1] #print(secret)
d3b38512fdc71b9953968731d12be52a176adb12
idrisr/npr_puzzles
/10_31_parrot/creature.py
1,665
3.984375
4
""" From Michael Arkelian, of Sacramento, Calif.: Name a creature in six letters. Move the first three letters to the end and read the result backward to name another creature. Clue: If you break either six-letter word in half, each pair of three letters will themselves spell a word. http://www.npr.org/templates/story/story.php?storyId=130943907 """ f_wordlist = '/home/idris/word_lists/CROSSWD.TXT' def load_dict(): """load word_list into dictionary I should make a dictionary saved on disk instead of always re-loading """ fin = open (f_wordlist) d = dict() for line in fin: word = line.strip().lower() if len(word) in (3, 6): d[ word ] = None return d def move_letters(word): """move first 3 letters of word to end""" new_word = word[3:] + word [:3] #reverse word new_word = new_word[::-1] return new_word def half_words(word): """tests to see if each split word is a real word""" def check_word(word): """returns boolean of whether word is in dictionary""" return (word in d_dict) def test_condition(word): """test if all conditions for puzzle are true""" l = list() word2 = move_letters(word) l.append( word2 ) l.append( word[:3] ) l.append( word[3:]) l.append( word2[:3]) l.append( word2[3:]) for word in l: if not check_word(word): return False return True #check if word after moving letter #if check_worddd def main(): for word in d_dict: if test_condition(word): print word if __name__ == '__main__': #load only 3 or 6 letter words d_dict = load_dict() main()
91e717e2422ba6a54dcfef0de4292846b9fd1832
Laavanya-Agarwal/Python-C2
/Making functions/countWords.py
271
4.3125
4
def countWords(): fileName = input('Enter the File Name') file = open(fileName, 'r') noOfWords = 0 for line in file: words = line.split() noOfWords = noOfWords + len(words) print('The number of words is ' + str(noOfWords)) countWords()
3c54aa7bc9815de81888d9b40085067fa1cf218a
keryl/2017-03-24
/even_number.py
467
4.25
4
def even_num(l): # first, we will ensure l is of type "list" if type(l) != list: return "argument passed is not a list of numbers" # secondly, check l is a list of numbers only for n in l: if not (type(n) == int or type(n) == float): return "some elements in your list are not numbers" # else find even numbers in it enum = [] for n in l: if n % 2 == 0: enum.append(n) return enum
1c4d7118670c3d9a705ba5d14ad1a9aea618330f
Shahil98/Reccommender_Movie_System
/EDA.py
1,593
3.734375
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df_main = pd.read_csv("training_ratings_for_kaggle_comp.csv") df_movies = pd.read_csv('movies.dat',sep='::',names=["movie","movie_name","genre"]) df_main = pd.merge(df_main,df_movies,on="movie") print() print("=========================================") print("Main dataframe head : ") print() print(df_main.head(5)) print("=========================================") print() average_ratings = df_main.groupby("movie_name")['rating'].mean().sort_values(ascending=False) print() print("=========================================") print("Average rating of movies head in descending order : ") print() print(average_ratings.head(5)) print("=========================================") print() count_of_ratings = df_main.groupby("movie_name")['rating'].count().sort_values(ascending=False) print() print("=========================================") print("Count of ratings head in descending order : ") print() print(count_of_ratings.head(5)) print("=========================================") print() ratings = pd.DataFrame(average_ratings) ratings["count_of_ratings"] = pd.DataFrame(count_of_ratings) plt.hist(ratings['count_of_ratings'].tolist(),bins=70) plt.title("Histogram of count of ratings given to movies") plt.show() plt.hist(ratings['rating'].tolist(),bins=70) plt.title("Histogram of average ratings given to movies") plt.show() plt.scatter(y=ratings['count_of_ratings'].tolist(),x=ratings['rating'].tolist()) plt.xlabel("Average ratings") plt.ylabel("Count of ratings") plt.show()
872ee49d185da0fec48939b43665c541099ff79e
anttesoriero/kg_anttesoriero_2021
/main.py
389
3.6875
4
# Anthony Tesoriero - Kargo Summer 2020 Software Engineering Internship Assessment import sys # Input from command line s1 = sys.argv[1] s2 = sys.argv[2] if len(s1) != len(s2): # Check to see if strings are the same length. If not, print False print(False) elif len(set(s1)) != len(s1): # Check to see if s1 has repeated characters. If so, print False print(False) else: print(True)
e698c9685c8fbf6d57ac79dfcc4d71f0ed1bf80e
Ayushree30/Python
/Encryption_software.py
1,204
3.859375
4
from tkinter import * from tkinter import messagebox import tkinter import tkinter as tk from Crypto.Cipher import AES import os,base64 import rsa window=tk.Tk() msg=tk.Label(text="Encryption Software",width=20,height=2) label=tk.Label(text="Enter Plaintext") entry=tk.Entry(width=40) def encryption(): #public and private Key generation RSA_key_length=512 public_key, private_key=rsa.newkeys(RSA_key_length) #RSA encryption name=entry.get() ciphertext=rsa.encrypt(name.encode(),public_key) tkinter.messagebox.showinfo(title='Ciphertext',message=ciphertext) def decryption(): #RSA decryption RSA_key_length=512 public_key, private_key=rsa.newkeys(RSA_key_length) name=entry.get() message_length=len(name) ciphertext=rsa.encrypt(name.encode(),public_key) decrypted_message=rsa.decrypt(ciphertext,private_key) decrypt=decrypted_message[0:message_length].decode("utf-8") tkinter.messagebox.showinfo(title='Plaintext',message=decrypt) button_1=tk.Button(text="Encrypt",command=encryption) button_2=tk.Button(text="Decrypt",command=decryption) #text_box=tk.Text() msg.pack() label.pack() entry.pack() button_1.pack() button_2.pack() #text_box.pack() window.mainloop()
6aaa8b738d85fb7fa6a8ecf013f62dc565cb49f3
kartavyabhatts30/Competitive-Coding-1
/Problem1.py
432
3.59375
4
# your code goes here def linMissingElem(nums): for i in range(len(nums)): if i == len(nums) - 1: return i + 2 if nums[i] != i+1: return i + 1 def binMissingElem(nums): if nums[-1] == len(nums): return len(nums)+1 l = 0 r = len(nums) - 1 while l < r: m = l + (r-l)//2 if nums[m] > m+1: r = m-1 else: l = m+1 return l + 1 print(linMissingElem([1,3,4,5,6,7])) print(binMissingElem([2,3]))
67e4f11eaa8ecc6402c5f85137f055875a5f3112
co-devs/codeword-generator
/project/codewordgenerator.py
5,209
4.40625
4
#!/usr/bin/env python3 """Code Word Generator This script will provide the user with a randomly generated code word. It requires the existence of several wordlists within the same folder in order to make those code words. This file can also be imported as a module and contains the following functions: * random_line - returns a random line from a file * get_noun - returns a random noun from a file * get_adj -returns a random adjective from a file * get_verb - returns a random verb from a file * gen_code - combines two words and returns as a codeword * main - the main function of the script """ import random import argparse def random_line(xfile): """Gets and returns a random line from a file Kudos to Alex Martelli and Martijn Pieters for the Waterman's Reservoir Algorithm code. Not sure that it's implemented correctly, but it works. https://stackoverflow.com/questions/3540288/how-do-i-read-a-random-line-from-one-file-in-python Parameters ---------- xfile : str The file location of the file to read Returns ------- str The random string from the file """ line = next(xfile) for num, xline in enumerate(xfile, 2): if random.randrange(num): continue line = xline return line def get_noun(nfile): """Gets and returns a random noun from a file Noun list source http://www.desiquintans.com/downloads/nounlist/nounlist.txt Parameters ---------- nfile : str The file location of the noun wordlist Returns ------- str The random noun from the file """ with open(nfile) as file: return random_line(file).strip() def get_adj(afile): """Gets and returns a random adjective from a file Adjectives source list https://www.talkenglish.com/vocabulary/top-500-adjectives.aspx Parameters ---------- afile : str The file location of the adjective wordlist Returns ------- str The random adjective from the file """ with open(afile) as file: return random_line(file).strip() def get_verb(vfile): """Gets and returns a random verb from a file Verbs source list https://www.linguasorb.com/english/verbs/most-common-verbs/1 Parameters ---------- nfile : str The file location of the verb wordlist Returns ------- str The random verb from the file """ with open(vfile) as file: return random_line(file).strip() def gen_code(nfile, afile, vfile, delim="", style=""): """Gets two random words and returns them as a code word kudos to Asim Ihsan (https://github.com/asimihsan) for the structure of either two nouns or an adjective and a noun https://gist.github.com/asimihsan/8239189 (n,n) (a,n) Parameters ---------- nfile : str The file location of the noun wordlist afile : str The file location of the adjective wordlist vfile : str The file location of the verb wordlist delim : str The delimiter to be used between words style : str The style of code word Returns ------- str The random code word """ if style == 'nn': num = 9 elif style == 'an': num = 6 elif style == 'vn': num = 5 else: num = random.randint(0, 99) if num % 5 > 1: # (n,n) word1 = get_noun(nfile).upper() word2 = get_noun(nfile).upper() if delim: code = word1 + delim + word2 else: code = word1 + word2 return code elif num % 5 == 1: # (a,n) word1 = get_adj(afile).upper() word2 = get_noun(nfile).upper() if delim: code = word1 + delim + word2 else: code = word1 + word2 return code else: # (v,n) word1 = get_verb(vfile).upper() word2 = get_noun(nfile).upper() if delim: code = word1 + delim + word2 else: code = word1 + word2 return code def main(): parser = argparse.ArgumentParser() parser.add_argument("-n", "--number", nargs='?', default=1, type=int, help="the number of codewords to print") parser.add_argument("-d", "--delimiter", type=str, help="the delimiter to use between words") parser.add_argument("-s", "--style", default='', choices=['nn', 'an', 'vn', ''], help="generate a noun-noun style code word") parser.add_argument("--nounlist", default='nouns.txt', type=str, help="noun wordlist file") parser.add_argument("--adjlist", default='adjs.txt', type=str, help="adjective wordlist file") parser.add_argument("--verblist", default='verbs.txt', type=str, help="verb wordlist file") args = parser.parse_args() for i in range(args.number): print(gen_code(args.nounlist, args.adjlist, args.verblist, args.delimiter, args.style)) if __name__ == "__main__": main()
5db5b7d81bb4c0700add06486d81e592d8101dfd
EtMR/Data-Structures-and-Algorithms-Certificate-Course-Coursera-
/counting_inversion.py
2,567
3.6875
4
# -*- coding: utf-8 -*- """ Created: Fri May 19 13:36:00 2020 @author: Etermeteor Topic: counting_inversion This script implements the counting inversion algorithm. (week 2 - divide and conquer - algorithm 1) """ import random import time def count_inv(arr): """ Pesudocode: count(arr): length arr = n if n = 1: return 0 else: x_sorted, x_count = on left arr y_sorted, y_count = on right arr arr_sorted, count = intermixed arr return (1)+(2)+(3) Note: If we can implement the count intermixed arr with O(n), the function will be able to run at time O(n log (n)) Complexity: O(n log (n)) """ l = len(arr) if l == 1: return arr, 0 else: half_l = l // 2 x_sorted, x = count_inv(arr[:half_l]) y_sorted, y = count_inv(arr[half_l:]) # implement O(n) for arr_sorted, z = CountSplitInv(arr, n) i = j = k = z = 0 while (i < len(x_sorted)) and (j < len(y_sorted)): if x_sorted[i] < y_sorted[j]: arr[k] = x_sorted[i] i += 1 else: arr[k] = y_sorted[j] j += 1 z += len(x_sorted) - i k += 1 while (i < len(x_sorted)): arr[k] = x_sorted[i] i += 1 k += 1 while (j < len(y_sorted)): arr[k] = y_sorted[j] j += 1 k += 1 return arr, x+y+z if __name__ == '__main__': random.seed(123) def evl(funct, x): start_time = time.time() _, result = funct(x) end_time = time.time() return result, (end_time - start_time) with open('IntegerArray.txt', 'r') as IA: testset = IA.readlines() san_chk = random.sample(range(0, 10), 10) testset = [int(element) for element in testset] print('----- Sanity Check -----') print('san_chk arr: ', san_chk) print('function output (arr, count): ', count_inv(san_chk)) print('') print('----- Assignment #2 -----') print('Count of inversions: {}, time used: {}.'.format(*evl(count_inv, testset))) """ ----- Sanity Check ----- san_chk arr: [0, 4, 1, 6, 3, 2, 9, 5, 7, 8] function output (arr, count): ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 10) ----- Assignment #2 ----- Count of inversions: 2407905288, time used: 2.1146366596221924. """
699e07824aea9ed37903c8a4e7daee1ed2ff4de3
JLyndon/PLD-Assignment-02
/UserDetails.py
206
3.84375
4
usr_name = input("Enter your name: ") usr_age = input("Enter age: ") usr_address = input("Enter your address: ") print(f"\nHi, my name is {usr_name}. I am {usr_age} years old and I live in {usr_address}.")
5826d676d257bfaa2bf72b13a1cf7105a2b1f79e
danny237/Python-Assignment3
/binary_search.py
1,087
3.671875
4
"""Implementation of Binary Search""" def binary_search(list1, n): """ Functio for binary Search Parameter: list1(list): list of emement n(int): number to be search Return: index(int): index of searched element """ L = 0 R = len(list1) - 1 while L <= R: mid = (L+R) // 2 if list1[mid] == n: return mid else: if list1[mid] < n: L = mid + 1 else: R = mid -1 # user input print('Enter the element in the list. Seperated by comma') while True: try: user_list = [int(e) for e in input().strip().split(',')] break except ValueError: print("Can't evaulate number.") print('Please. Enter the element in the list. Seperated by comma') print('Enter the number to search in the list.') value = int(input()) returned_index = binary_search(user_list, value) if returned_index is not None: print(f'{value} is present in {returned_index + 1} index of list.') else: print('Not found')
8bd5806dd9b01c9eb90592e7239e8662ae9f1af5
danny237/Python-Assignment3
/insertion_sort.py
541
4.1875
4
"""Insertion Sort""" def insertion_sort(list1): """function for insertion sort""" for i in range(1, len(list1)): key = list1[i] j = i-1 while j >=0 and key < list1[j] : list1[j+1] = list1[j] j -= 1 list1[j+1] = key return list1 # user input print('Enter list of number seperated by comma.') print('Example: 1,2,3') list_arr = [int(i) for i in input().strip().split(',')] sorted_arr = insertion_sort(list_arr) print(f'Sorted list: {sorted_arr}')
db847c81696583b5f7497358984a09b7667e6617
male524/Algorithms
/Week 4/toLowerCase.py
579
3.90625
4
# 709. To Lower Case """ Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. Example 1: Input: "Hello" Output: "hello" Example 2: Input: "here" Output: "here" Example 3: Input: "LOVELY" Output: "lovely" """ class Solution: def toLowerCase(self, str: str) -> str: return ''.join([chr(ord(char) + 32) if 65 <= ord(char) <= 90 else char for char in str]) # I learned how to use list comprehension a bit better from w3schools. # This took me 30 minutes since I challenged my self to solve this in one line.
3fb94ff4bbb8804f5798884318f9b5174a820477
male524/Algorithms
/Week 4/minTimeToVisitAllPoints.py
2,182
3.9375
4
# 1266. Minimum Time Visiting All Points """ On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. You can move according to these rules: In 1 second, you can either: move vertically by one unit, move horizontally by one unit, or move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). You have to visit the points in the same order as they appear in the array. You are allowed to pass through points that appear later in the order, but these do not count as visits. Example 1: Input: points = [[1,1],[3,4],[-1,0]] Output: 7 Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] Time from [1,1] to [3,4] = 3 seconds Time from [3,4] to [-1,0] = 4 seconds Total time = 7 seconds Example 2: Input: points = [[3,2],[-2,2]] Output: 5 Constraints: points.length == n 1 <= n <= 100 points[i].length == 2 -1000 <= points[i][0], points[i][1] <= 1000 """ from typing import List class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: sec = 0 for i in range(0, len(points) - 1): x1, y1, x2, y2 = points[i][0], points[i][1], points[i + 1][0], points[i + 1][1] xDif, yDif = abs(x1 - x2), abs(y1 - y2) while True: if xDif >= 1 and yDif >= 1: xDif -= 1 yDif -= 1 sec += 1 elif xDif == 1 and yDif != 1: xDif -= 1 sec += 1 elif yDif == 1 and xDif != 1: yDif -= 1 sec += 1 elif xDif >= 1 and yDif == 0: xDif -= 1 sec += 1 elif yDif >= 1 and xDif == 0: yDif -= 1 sec += 1 else: break return sec print(Solution.minTimeToVisitAllPoints(0, [[1,1],[3,4],[-1,0]])) # I used stuff I already knew to solve this. # This took me 15 minutes
0227fd18303630931bddcb968fcf59461f0f6e09
male524/Algorithms
/Week 13/Learn/getIntersectionNode.py
1,129
3.5625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from platform import node class Solution: def getIntersectionNode(self, headA: node, headB: node) -> node: A = headA B = headB lenA = lenB = 1 if A == B: return A while A.next != None: A = A.next lenA += 1 while B.next != None: B = B.next lenB += 1 diff = abs(lenA - lenB) A = headA B = headB if lenA > lenB: for i in range(lenA): if A == B: return A A = A.next if i >= diff: B = B.next elif lenB > lenA: for i in range(lenB): if A == B: return A B = B.next if i >= diff: A = A.next else: for i in range(lenA): if A == B: return A A = A.next B = B.next
3f9c496c229700a9f0acf9bd80e21cc1618467f8
male524/Algorithms
/Week 2/isValid.py
2,367
4.03125
4
# 20. Valid Parentheses """ Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false Example 4: Input: s = "([)]" Output: false Example 5: Input: s = "{[]}" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'. """ class Solution1: def isValid(self, s: str) -> bool: holder = [] for i in range(len(s)): holder.append(s[i]) if holder[-1] == ')' or holder[-1] == ']' or holder[-1] == '}': curChr = holder[-1] if curChr == ')': revCurChr = str(chr(ord(curChr) - 1)) else: revCurChr = str(chr(ord(curChr) - 2)) if revCurChr in holder: first = len(holder) - 1 - holder[::-1].index(revCurChr) second = len(holder) - 1 - holder[::-1].index(curChr) dif = second - first if dif > 1: return False holder.pop(second) holder.pop(first) else: return False if len(holder) > 0: return False else: return True class Solution2: # @return a boolean def isValid(self, s): stack = [] dict = {"]":"[", "}":"{", ")":"("} for char in s: if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else: return False return stack == [] print(Solution1.isValid(1, "(([{()}])())()[]{}")) print(Solution2.isValid(1, "(([{()}])())()[]{}")) # I learned how to get the index of the last item with a specific value in a list by doing len(list) - 1 - list[::-1].index(value) # I looked at another person's solution and I learned what a stack is from it, so I included the code # This one was really hard for me, it took me 3 hours
ceca83f8d1a6d0dbc027ad04a7632bb8853bc17f
harshablast/numpy_NN
/nn.py
2,183
3.734375
4
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def d_sigmoid(x): return x * (1 - x) def relu(x): return x * (x > 0) def d_relu(x): return 1 * (x > 0) class neural_network: def __init__(self, nodes): self.input_dim = nodes[0] self.HL01_dim = nodes[1] self.HL02_dim = nodes[2] self.output_dim = nodes[3] self.W1 = 2 * (np.random.rand(self.input_dim, self.HL01_dim) -1) self.W2 = 2 * (np.random.rand(self.HL01_dim, self.HL02_dim) -1) self.W3 = 2 * (np.random.rand(self.HL02_dim, self.output_dim) -1) self.B1 = 2 * (np.random.rand(1, self.HL01_dim)) self.B2 = 2 * (np.random.rand(1, self.HL02_dim)) self.B3 = 2 * (np.random.rand(1, self.output_dim)) def forward_pass(self, input): self.HL01_out = sigmoid(np.add(np.matmul(input, self.W1), self.B1)) self.HL02_out = sigmoid(np.add(np.matmul(self.HL01_out, self.W2), self.B2)) self.output = sigmoid(np.add(np.matmul(self.HL02_out, self.W3), self.B3)) return self.output def backward_pass(self, train_data_X, train_data_Y, iterations, learning_rate): for j in range(iterations): self.forward_pass(train_data_X) error = np.sum(np.square(self.output - train_data_Y)) print(error) output_error = self.output - train_data_Y output_deltas = output_error * d_sigmoid(self.output) self.W3 -= np.dot(self.HL02_out.T, output_deltas) * learning_rate self.B3 -= np.sum(output_deltas, axis=0, keepdims=True) * learning_rate HL02_error = np.dot(output_deltas, self.W3.T) HL02_deltas = HL02_error * d_sigmoid(self.HL02_out) self.W2 -= np.dot(self.HL01_out.T, HL02_deltas) * learning_rate self.B2 -= np.sum(HL02_deltas, axis=0, keepdims=True) * learning_rate HL01_error = np.dot(HL02_deltas, self.W2.T) HL01_deltas = HL01_error * d_sigmoid(self.HL01_out) self.W1 -= np.dot(train_data_X.T, HL01_deltas) * learning_rate self.B1 -= np.sum(HL01_deltas, axis=0, keepdims=True) * learning_rate
3d2c83671779aae0c1226838d0b8dc6f73a90016
milominderbinder22/cit129
/wk5/cp_searchIt.py
3,233
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 1 22:37:21 2018 """ import json def getCriteria(filename): with open(filename,'r') as infile: criteria=json.load(infile) return criteria def printProject(n): keys=n.keys() for i in keys: print(i + ": ",n[i]) print("--------------------------") ##def checkCriteria(item,criteria): ##deprecated, too many calls def extractCriteria(criteria): asset_type=[] fiscal_year=[] status=[] area=[] start_date=[] ## TO ADD ADDITIONAL CRITERIA: create a list for each criteria HERE for i in criteria: if i=="asset_type": for j in range(len(criteria[i])): asset_type.append(criteria[i][j]) if i=="fiscal_year": for j in range(len(criteria[i])): fiscal_year.append(criteria[i][j]) if i=="status": for j in range(len(criteria[i])): status.append(criteria[i][j]) if i=="area": for j in range(len(criteria[i])): area.append(criteria[i][j]) if i=="start_date": for j in range(len(criteria[i])): start_date.append(criteria[i][j]) ## TO ADD ADDITIONAL CRITERIA: add a list populator of the form above HERE return(asset_type,fiscal_year,status,area,start_date) #TO ADD ADDITIONAL CRITERIA: add the new criterion's list name ##to the return statement above def searchCP(criteriaFileName,CPfilename): #should also take CPfilename asset_typisch=[] fiscal_year=[] status=[] area=[] start_date=[] criteria=getCriteria(criteriaFileName) counter=0 with open(CPfilename,'r') as datafile: data=json.load(datafile) asset_typisch,fiscal_year,status,area,start_date = extractCriteria(criteria) for p in data['features']: if len(asset_typisch)>0 and p['properties']['asset_type'] not in asset_typisch: continue elif len(fiscal_year)>0 and p['properties']['fiscal_year'] not in fiscal_year: continue elif len(status)>0 and p['properties']['status'] not in status: continue elif len(area)>0 and p['properties']['area'] not in area: continue elif len(start_date)>0 and p['properties']['start_date'] not in start_date: continue ##TO ADD ADDITIONAL CRITERIA: add the new criterion's list name ## in a statement with the form immediately above else: counter +=1 printProject(p['properties']) ## COULD ALSO WRITE THESE TO A FILE. USING A METHOD. print("Asset type list is: ",asset_typisch) print("And fiscal yr is: ",fiscal_year) print(str(counter)+" such projects") ##gives count of projects found meeting criteria #execution control below: searchCP('cp_search_criteria.json','cgcapitalprojects_img.geojson') """ SNIPPETS AND NOTES AND SUCH: if contains "fiscal\w" "asset\w" etc then do that thing (regex) """
a92ddcd48a363dc8b7533fc30bc9ced4c0f901e7
MoisesCatonio/Heap_Binary_Tree
/Heap.py
2,131
3.53125
4
class element: def __init__(self, data=None, own_pos=None, father=None, left_son=None, right_son=None): self.data = data self.father = father self.own_pos = own_pos self.left_son = left_son self.right_son = right_son class heap: def __init__(self): self.tree = [] def determine_positions(self): for i in range(0, len(self.tree)): self.tree[i].own_pos = i self.tree[i].left_son = int(2*i+1) self.tree[i].right_son = int(2*i+2) if(i != 0): self.tree[i].father = int((i-1)/2) else: self.tree[i].father = None def add_element(self, new_element): self.tree.append(new_element) self.determine_positions() def swap(self, elem1, elem2): aux = self.tree[elem1.own_pos] self.tree[elem1.own_pos] = self.tree[elem2.own_pos] self.tree[elem2.own_pos] = aux self.determine_positions() def heapify(self): last_elem = len(self.tree)-1 for last_1 in range(last_elem, 0, -1): for last in range(last_elem, 0, -1): if(last > 1): iter2 = last - 1 if(self.tree[last].father == self.tree[iter2].father): min_value = min(self.tree[last].data, self.tree[iter2].data) if(self.tree[last].data == min_value): elem_change = self.tree[last] else: elem_change = self.tree[last-1] if(min_value<self.tree[elem_change.father].data): self.swap(elem_change, self.tree[elem_change.father]) else: elem_change = self.tree[last] if(elem_change.data < self.tree[elem_change.father].data): self.swap(elem_change, self.tree[elem_change.father]) def printer_list(self): for i in range(0,len(self.tree)): print(str(self.tree[i].data) + ", ")
adfba4e45bc9ec9707eeda09767bfde152600426
reachtoakhtar/data-structure
/tree/problems/binary_tree/diameter.py
776
4.125
4
__author__ = "akhtar" def height(root, ans): if root is None: return 0 left_height = height(root.left, ans) right_height = height(root.right, ans) # update the answer, because diameter of a tree is nothing but maximum # value of (left_height + right_height + 1) for each node ans[0] = max(ans[0], 1 + left_height + right_height) return 1 + max(left_height, right_height) def find_diameter(root): """ Find the diameter of a binary tree with given root. :param BTreeNode root: The root of the tree. :return: the diameter of the tree. :rtype: int """ if root is None: return 0 # This will store the final answer ans = [-99999999999] height(root, ans) return ans[0]
c217c1c3b1af03e659f0a418b94684dd9e2cb372
reachtoakhtar/data-structure
/tree/problems/binary_tree/maximum_sum_level.py
2,082
4.09375
4
__author__ = "akhtar" def level_with_maximum_sum(root): """ Find the level with maximum sum in a binary tree. :param BTreeNode root: The root of the tree. :return: the level with maximum sum and the sum. :rtype: tuple """ if root is None: return stack = [root] level = 1 max_sum = root.data max_sum_level = 1 while len(stack): current_level_sum = 0 next_level_nodes = [] for _ in range(len(stack)): node = stack.pop() current_level_sum += node.data if node.left: next_level_nodes.append(node.left) if node.right: next_level_nodes.append(node.right) if current_level_sum > max_sum: max_sum = current_level_sum max_sum_level = level level += 1 stack = next_level_nodes return max_sum_level, max_sum # # # def level_with_maximum_sum(root): # """ # Find the level with maximum sum in a binary tree. # # :param BTreeNode root: The root of the tree. # :return: the level with maximum sum. # :rtype: int # """ # # # used for storing each level sum # d = {} # # stack = [root] # # # determining current level of tree # level = 1 # # while stack: # next_lvl_nodes = [] # current_lvl_sum = 0 # # for i in range(len(stack)): # node = stack.pop() # # # sum each nodes value # current_lvl_sum += node.val # # # check for children # if node.left: # next_lvl_nodes.append(node.left) # if node.right: # next_lvl_nodes.append(node.right) # # d[level] = current_lvl_sum # level += 1 # stack = next_lvl_nodes # # # Get key(level) of maximum value in dictionary # return max(d, key=d.get)
f137cb5b73c874f6d7efbf38e7245f3a7603126a
reachtoakhtar/data-structure
/tests/test_tree/problems/binary_tree/test_inorder_traversal.py
3,414
3.5625
4
__author__ = "akhtar" import unittest from tests.test_tree.utils import SampleBTree from tree.problems.binary_tree.traversal_inorder import inorder_iterative class TestInorderTraversal(unittest.TestCase): def setUp(self): return super().setUp() def test_inorder_recursive(self): print("TEST INORDER TRAVERSAL OF A BINARY TREE - RECURSIVE") print("===========================================================") root = SampleBTree.create_1() SampleBTree.print_1() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_3() SampleBTree.print_3() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_4() SampleBTree.print_4() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_6() SampleBTree.print_6() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_9() SampleBTree.print_9() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_left_weighted() SampleBTree.print_left_weighted() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_right_weighted() SampleBTree.print_right_weighted() print("Inorder traversal:", end=" ") inorder_iterative(root) print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") def test_inorder_iterative(self): print("TEST INORDER TRAVERSAL OF A BINARY TREE - ITERATIVE") print("===========================================================") root = SampleBTree.create_1() SampleBTree.print_1() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_3() SampleBTree.print_3() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_4() SampleBTree.print_4() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_6() SampleBTree.print_6() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_9() SampleBTree.print_9() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_left_weighted() SampleBTree.print_left_weighted() print("Inorder traversal:", end=" ") inorder_iterative(root) print("\n\n") root = SampleBTree.create_right_weighted() SampleBTree.print_right_weighted() print("Inorder traversal:", end=" ") inorder_iterative(root) print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") if __name__ == "__main__": unittest.main()
623580ac962f92c1ce58be445c296c731b16a2fd
reachtoakhtar/data-structure
/tests/test_tree/problems/binary_tree/test_max_sum_level.py
2,519
3.671875
4
__author__ = "akhtar" import unittest from tests.test_tree.utils import SampleBTree from tree.problems.binary_tree.maximum_sum_level import level_with_maximum_sum class TestMaxSumLevel(unittest.TestCase): def setUp(self): return super().setUp() def test_diameter(self): print("TEST LEVEL OF MAXIMUM SUM IN A BINARY TREE") print("===========================================================") root = SampleBTree.create_1() SampleBTree.print_1() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level), end=" ") print("\n\n") root = SampleBTree.create_3() SampleBTree.print_3() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level), end=" ") print("\n\n") root = SampleBTree.create_4() SampleBTree.print_4() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level), end=" ") print("\n\n") root = SampleBTree.create_6() SampleBTree.print_6() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level), end=" ") print("\n\n") root = SampleBTree.create_9() SampleBTree.print_9() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level)) print("\n\n") root = SampleBTree.create_left_weighted() SampleBTree.print_left_weighted() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level)) print("\n\n") root = SampleBTree.create_right_weighted() SampleBTree.print_right_weighted() max_sum_level, sum = level_with_maximum_sum(root) print("Maximum sum = {0}".format(sum)) print("Maximum sum level = {0}".format(max_sum_level)) print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") if __name__ == "__main__": unittest.main()
38c2c7c2a0ace1c174050b835855fc93d6709a1a
reachtoakhtar/data-structure
/tests/test_linked_list/problems/test_reverse_single_linked_list.py
2,226
3.765625
4
import unittest from linked_list.exception import EmptyListError from linked_list.lists import SingleLinkedList __author__ = "akhtar" from linked_list.problems.reverse_single_linked_list import \ reverse_single_linked_list class TestReverseSingleLinkedList(unittest.TestCase): def setUp(self): self.linked_list = SingleLinkedList() def create_list(self): self.linked_list = SingleLinkedList() self.linked_list.insert_at_end(5) self.linked_list.insert_at_end(81) self.linked_list.insert_at_end(23) self.linked_list.insert_at_end(8) self.linked_list.insert_at_end(99) self.linked_list.insert_at_end(33) self.linked_list.insert_at_end(67) # 5 --> 81 --> 23 --> 8 --> 99 --> 33 --> 67 def test_reverse_single_linked_list(self): print("TEST REVERSE SINGLE LINKED LIST") print("===========================================================") print("List: <Empty list>") try: print("<", end="") reverse_single_linked_list(self.linked_list) except EmptyListError as e: print(str(e), end=">\n\n") self.linked_list.insert_at_beginning(22) print("List: " + self.linked_list.get_list()) reverse_single_linked_list(self.linked_list) self.assertEqual(self.linked_list.get_list(), "22") print("Reversed list: " + self.linked_list.get_list(), end="\n\n") self.linked_list.insert_at_end(53) print("List: " + self.linked_list.get_list()) reverse_single_linked_list(self.linked_list) self.assertEqual(self.linked_list.get_list(), "53 \u27F6 22") print("Reversed list: " + self.linked_list.get_list(), end="\n\n") self.create_list() print("List: " + self.linked_list.get_list()) reverse_single_linked_list(self.linked_list) self.assertEqual( self.linked_list.get_list(), "67 \u27F6 33 \u27F6 99 \u27F6 8 \u27F6 23 \u27F6 81 \u27F6 5") print("Reversed list: " + self.linked_list.get_list()) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") if __name__ == "__main__": unittest.main()
30982b383b30bc7c329196debc528bb91484155c
reachtoakhtar/data-structure
/tests/test_tree/problems/binary_tree/test_find_height.py
1,929
3.890625
4
__author__ = "akhtar" import unittest from tests.test_tree.utils import SampleBTree from tree.nodes import BTreeNode from tree.problems.binary_tree.find_height import find_height_iterative, \ find_height_recursive class TestFindHeight(unittest.TestCase): def setUp(self): self.create_tree() def create_tree(self): self.root = SampleBTree.create_9() def test_find_height_recursive(self): print("TEST FIND HEIGHT OF A BINARY TREE - RECURSIVE") print("===========================================================") SampleBTree.print_9() height = find_height_recursive(self.root) self.assertEqual(5, height) print("Height of given tree = {0}".format(height), end="\n\n") self.root = BTreeNode(10) print("Tree to operate: ") print(" " * 20 + "10\n") height = find_height_recursive(self.root) self.assertEqual(1, height) print("Height of given tree = {0}".format(height), end=" ") print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") def test_find_height_iterative(self): print("TEST FIND HEIGHT OF A BINARY TREE - ITERATIVE") print("===========================================================") SampleBTree.print_9() size = find_height_iterative(self.root) self.assertEqual(5, size) print("Height of given tree = {0}".format(size), end="\n\n") self.root = BTreeNode(10) print("Tree to operate: ") print(" " * 20 + "10\n") size = find_height_iterative(self.root) self.assertEqual(1, size) print("Height of given tree = {0}".format(size), end=" ") print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") if __name__ == "__main__": unittest.main()
fcaa579f2c5da9947e593f06227b1645e960d084
reachtoakhtar/data-structure
/tests/test_tree/problems/binary_tree/test_find_size.py
1,885
3.703125
4
__author__ = "akhtar" import unittest from tests.test_tree.utils import SampleBTree from tree.nodes import BTreeNode from tree.problems.binary_tree.find_size import find_size_iterative, \ find_size_recursive class TestFindSize(unittest.TestCase): def setUp(self): self.create_tree() def create_tree(self): self.root = SampleBTree.create_9() def test_find_size_recursive(self): print("TEST FIND SIZE OF A BINARY TREE - RECURSIVE") print("===========================================================") SampleBTree.print_9() size = find_size_recursive(self.root) self.assertEqual(9, size) print("Size of given tree = {0}".format(size), end="\n\n") self.root = BTreeNode(10) print("Tree to operate: ") print(" " * 20 + "10\n") size = find_size_recursive(self.root) self.assertEqual(1, size) print("Size of given tree = {0}".format(size), end=" ") print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") def test_find_size_iterative(self): print("TEST FIND SIZE OF A BINARY TREE - ITERATIVE") print("===========================================================") SampleBTree.print_9() size = find_size_iterative(self.root) self.assertEqual(9, size) print("Size of given tree = {0}".format(size), end="\n\n") self.root = BTreeNode(10) print("Tree to operate: ") print(" " * 20 + "10\n") size = find_size_iterative(self.root) self.assertEqual(1, size) print("Size of given tree = {0}".format(size), end=" ") print( "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n") if __name__ == "__main__": unittest.main()
9c8fe55f7c3910b7dc73ee068c81c8276f350998
rbirkaur23/Armstrong_Number
/armstrong_num.py
219
3.953125
4
n=int(input("Enter a number: ")) store=n total=0 while n!=0: last_digit=n%10 total=total+(last_digit**3) n=n//10 if (total ==store): print("Armstrong Number") else: print("Not an Armstrong Number")
a3690f36f56028ac4288ee264fb5d441d0f789e1
demmmmmmi/psychopy2018
/day.py
300
4
4
from datetime import datetime print"what is the date you want to know the day, input yyyymmdd:)" odate=raw_input() print"The output 0 represent Monday :P and 1 mean Tuesday... you can +1 then that is the day you want to know:))" odate = datetime.strptime(odate,'%Y%m%d' ).weekday() print odate
4ae028682e42184125c883e9bef12a4f80d74611
hector81/Aprendiendo_Python
/CursoPython/Unidad10/Ejemplos/raise_levantar_excepciones.py
440
3.890625
4
def probable_execp(numero): """Función que sintácticamente está perfecta pero no lógicamente """ numero = float(numero) raiz = numero ** 0.5 if numero <0: raise Exception("El dato introducido debe ser un número positivo") else: print(f"La raíz cuadrada del número {numero} es {raiz}") print("Buen día.") numero = input("Introduce número: ") probable_execp(numero)
93c12f6ced3ca1b9d99a490e6e3e7d6551dbd58f
hector81/Aprendiendo_Python
/Bucles/Hexagono.py
625
4.125
4
numero = 0 cuadrado = '' # bucle para poner numero correto while numero < 1 : # ponemos el numero numero = int(input('Escribe el número ')) print() if numero < 1: print('El número debe ser positivo') else: numeroArriba = numero while numeroArriba < ((numero*2) + 3): for i in range(0, ((numero*2)-1)): if i < numero: cuadrado = cuadrado + ' ' else: cuadrado = cuadrado + 'x' print(cuadrado) cuadrado = '' numeroArriba = numeroArriba + 2
a3d7e3651dfa1a7c87a4a08c2482479a1e060b69
hector81/Aprendiendo_Python
/CursoPython/Unidad8/Ejemplos/funcion_datetime_datetime.py
1,090
4
4
''' Con datetime puedes construir una fecha con su hora con el método constructor con el siguiente formato: datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0). Especificando la fecha y hora, sólo son obligatorios el año, el mes y el día. ''' ''' una fecha 19 de junio de 2006 a las 18:37:24, recuerda que sólo son obligatorios el año, el mes y el día, el formato que debemos usar es: AAAA M DD HH MM SS. ''' from datetime import datetime fecha1 = datetime(2006, 6, 19, 18, 37, 24) print(fecha1) ''' now() crea una fecha con los datos actuales. ''' #datetime.datetime(2006, 6, 19, 18, 37, 24) fecha2 = datetime.now() print(fecha2) #datetime.datetime(2019, 8, 14, 17, 33, 46, 261156) ''' Una vez creada la fecha, no puedes modificar los valores, por lo que tendrías que volver a crear una nueva fecha, esto es importante si quieres utilizar los tiempos de ejecución. ''' fecha1 = datetime(2019, 8, 14, 17, 33, 46, 261156) print(fecha1) fecha3 = datetime(2019, 8, 14, 17, 33, 46, 261156) print(fecha3)
21cea9ddd51db449c503ea7e5b097d6e0b89930e
hector81/Aprendiendo_Python
/Bucles/Desglose_Cantidad_Monedas_Euros.py
2,281
4.03125
4
# Realiza un programa que proporcione el desglose en billetes y monedas de una # cantidad entera de euros. Recuerda # que hay billetes de 500, 200, 100, 50, 20, 10 y 5 ¤ y monedas de 2 y 1 ¤. # Debes ✭✭recorrer✮✮ los valores de billete y moneda # disponibles con uno o m´as bucles for-in. def introducirCantidad(): while True: try: cantidad = float(input("Por favor ingrese una cantidad: ")) if cantidad < 0: print('La cantidad debe ser positiva') else: return cantidad break except ValueError: print("Oops! No era válido. Intente nuevamente...") # fin funcion def desglosarCantidad(cantidad): arrayCantidadMonedasBilletes = [500,200,100,50,20,10,5,2,1,0.5,0.2,0.1,0.05,0.02,0.01] monBil = '' restoCantidad = 0 cantidadUnidad = 0 for i in range(len(arrayCantidadMonedasBilletes)): if cantidad == arrayCantidadMonedasBilletes[i]: print('HAY ' + '1' + ' ' + monBil + ' DE ' + str(arrayCantidadMonedasBilletes[i]) + ' EUROS') break else: # sacamos el resto restoCantidad = cantidad%arrayCantidadMonedasBilletes[i] # restamos el resto a la cantidad cantidad = cantidad - restoCantidad # y la dividimos por la posicion para sacar la cantidad exacta de billetes o monedas cantidadUnidad = int(cantidad/arrayCantidadMonedasBilletes[i]) # estos es para billetes o monedas if arrayCantidadMonedasBilletes[i] < 3: if cantidadUnidad > 1: monBil = 'MONEDAS' else: monBil = 'MONEDA' else: if cantidadUnidad > 1: monBil = 'BILLETES' else: monBil = 'BILLETE' print('HAY ' + str(cantidadUnidad) + ' ' + monBil + ' DE ' + str(arrayCantidadMonedasBilletes[i]) + ' EUROS') # ponemos los valores para siguiente vuelta cantidad = restoCantidad cantidadUnidad = 0 # fin funcion cantidad = introducirCantidad() desglosarCantidad(cantidad)
ba1a94f3a0febbebcb813bd462e63179eaf1cc73
hector81/Aprendiendo_Python
/CursoPython/Unidad8/Ejemplos/funcion_random_choice.py
425
3.765625
4
''' La función choice(secuencia) elige un valor al azar en un conjunto de elementos. Cualquier tipo de datos enumerables (tupla, lista, cadena, range) puede utilizarse como conjunto de elementos. ''' import random #lista print(random.choice(['win', 'lose', 'draw'])) #cadena print(random.choice("estocadena")) #tupla print(random.choice(("Python", True, "Zope", 5))) #range print(random.choice(range(1, 150)))
e76f3aaaeeea8f6372ee87a8263a350b51625bc8
hector81/Aprendiendo_Python
/Excepciones/Ejercicio1_division_error_cero.py
912
4.09375
4
''' EJERCICIOS EXCEPCIONES 1. Función que recibe dos enteros, a y b, y divide el mayor por el menor mostrando un mensaje de error si es una división entre cero (ZeroDivisionError). ''' def introducirNumero(): while True: try: x = int(input("Por favor ingrese un número: ")) return x break except ValueError: print("Oops! No era válido. Intente nuevamente...") def dividir(a, b): lista = [a, b] maximo = max(lista) minimo = min(lista) try: resultado = maximo / minimo return f"El resultado de la division ({maximo}/{minimo}) es = {resultado}" except ZeroDivisionError: return f"El denominador o divisor no puede ser cero" print(f"Introduce el parametro a") a = introducirNumero() print(f"Introduce el parametro b") b = introducirNumero() print(dividir(a, b))
a341738e4c229e642ecb091b3c3ef8e471c484e9
hector81/Aprendiendo_Python
/CursoPython/Unidad10/Ejemplos/excepcion_basica_general.py
467
3.65625
4
def excepcion_basica(numero): try: numero = float(numero) calculo = numero ** 0.5 print(f"La raíz cuadrada del número {numero} es {calculo}") except: pass print("Buen día.") ''' Prueba en tu espacio de trabajo, excepcion_basica("6j"), excepcion_basica(-90), excepcion_basica(87), excepcion_basica(hola) ''' #excepcion_basica("6j") #excepcion_basica(-90) #excepcion_basica(87) #excepcion_basica(hola)
b9d59b5bd22207e7d7188fdfffa92f5acbccd82f
hector81/Aprendiendo_Python
/CursoPython/Unidad7/Ejercicios/ejercicio_II_u7.py
1,171
4.53125
5
''' Lambda y map() map() es una función incorporada de orden superior que toma una función e iterable como entradas, y devuelve un iterador que aplica la función a cada elemento de la iterable. El código de abajo usa map() para encontrar la media de cada lista en números para crear los promedios de la lista. Haz una prueba para ver qué pasa. Reescribe este código para ser más conciso reemplazando la función media por una expresión lambda definida dentro de la llamada a map() ''' ''' SOLUCION SIN FUNCION LAMBDA ''' numeros = [ [56, 13, 93, 45, 18], [59, 83, 16, 75, 43], [49, 59, 93, 83, 62], [41, 72, 56, 10, 87] ] def promedio(num_list): return sum(num_list) / len(num_list) medias = list(map(promedio, numeros)) print(medias) ''' SOLUCION CON FUNCION LAMBDA ''' #Expresión lambda para realizar la solución al mismo problema. promedio1 = lambda numeros : sum(numeros) / len(numeros) # lambda parametro return formula medias1 = list(map(promedio1, numeros)) # a la funcion map le pasamos como parametros la funcion y la lista print(medias1)
7cb9b691fd986e01fca2d107ef040fa2661acf8c
hector81/Aprendiendo_Python
/Listas/IntroducirNotasAlumnos.py
3,628
3.984375
4
def introducirNumeroAlumnos(): while True: try: numeroAlumnos = int(input("Por favor ingrese el número de alumnos: ")) return numeroAlumnos break except ValueError: print("Oops! No era válido. Intente nuevamente...") # FIN FUNCION def introducirNombreAlumnos(): while True: try: nombreALumno = input("Por favor ingrese el nombre de alumno: ") if nombreALumno != '': return nombreALumno break except ValueError: print("Oops! No era válido. Intente nuevamente...") # FIN FUNCION def introducirNotas(): while True: try: nota = int(input("Por favor ingrese la nota de alumno: ")) return nota break except ValueError: print("Oops! No era válido. Intente nuevamente...") # FIN FUNCION def calificarNota(nota): nota = introducirNotas() if nota < 5: return 'SUSPPENSO' elif nota < 7: return 'APROBADO' elif nota < 9: return 'NOTABLE' elif nota < 10: return 'SOBRESALIENTE' else: return 'SIN CALIFICACION' # FIN FUNCION def introducirDatos(): arrayAlumnosNotas = [] alumnoNota = [] numeroAlumnos = introducirNumeroAlumnos() for i in range(numeroAlumnos): nombre = introducirNombreAlumnos() nota = introducirNotas() calificacion = calificarNota(nota) alumnoNota = [nombre,nota,calificacion] arrayAlumnosNotas.append(alumnoNota) # vacio array para siguiente vuelta alumnoNota = [] return arrayAlumnosNotas # FIN FUNCION def recorrerDatosYEstadisiticas(): arrayAlumnosNotas = introducirDatos() numeroSuspensos = 0 numeroAprobados = 0 numeroNotables = 0 numeroSobresalientes = 0 numerosINcALIFICACION = 0 totalNumero = 0 for i in range(len(arrayAlumnosNotas)): print('El alumno ' + str(arrayAlumnosNotas[i][0]) + ' ha sacado la nota ' + str(arrayAlumnosNotas[i][1]) + ' y se le califica con un ' + str(arrayAlumnosNotas[i][2])) if arrayAlumnosNotas[i][2] == 'SUSPENSO': numeroSuspensos = numeroSuspensos + 1 elif arrayAlumnosNotas[i][2] == 'APROBADO': numeroAprobados = numeroAprobados + 1 elif arrayAlumnosNotas[i][2] == 'NOTABLE': numeroNotables = numeroNotables + 1 elif arrayAlumnosNotas[i][2] == 'SOBRESALIENTE': numeroSobresalientes = numeroSobresalientes + 1 else: numerosINcALIFICACION = numerosINcALIFICACION + 1 totalNumero = numeroSuspensos + numeroAprobados + numeroNotables + numeroSobresalientes + numerosINcALIFICACION print('EL NUMERO DE SUSPENSOS ES ' + str(numeroSuspensos) + " Y EL TANTO POR CIENTO ES " + str((numeroSuspensos*100)/totalNumero) + '%') print('EL NUMERO DE APROBADOS ES ' + str(numeroAprobados) + " Y EL TANTO POR CIENTO ES " + str((numeroAprobados*100)/totalNumero) + '%') print('EL NUMERO DE NOTABLES ES ' + str(numeroNotables) + " Y EL TANTO POR CIENTO ES " + str((numeroNotables*100)/totalNumero) + '%') print('EL NUMERO DE SUSPENSOS ES ' + str(numeroSobresalientes) + " Y EL TANTO POR CIENTO ES " + str((numeroSobresalientes*100)/totalNumero) + '%') print('EL NUMERO DE SUSPENSOS ES ' + str(numerosINcALIFICACION) + " Y EL TANTO POR CIENTO ES " + str((numerosINcALIFICACION*100)/totalNumero) + '%') # FIN FUNCION recorrerDatosYEstadisiticas()
b786cc73b8183d18f853c669c1edeedc93a8688e
hector81/Aprendiendo_Python
/Unidad9/Ejemplos/herencia/mascota.py
363
3.734375
4
# creamos la clase class Mascota: # declaramos el metodo __init__ def __init__(self): self.nombre=input("Ingrese el nombre: ") self.edad=int(input("Ingrese la edad: ")) def mostrar(self): print("Nombre: ",self.nombre) print("Edad: ",self.edad) #----------hasta aquí ya lo teníamos definido-------------
08be952345411637b829e6af9f3ff91c745225cd
hector81/Aprendiendo_Python
/CursoPython/Unidad5/Ejemplos/ejemplo3_if_else_anidados.py
1,063
4.125
4
''' Durante el trimestre, un estudiante debe realizar tres exámenes. Cada examen tiene una calificación y la nota total que recibe el estudiante es la suma de las dos mejores calificaciones. Escribe un programa que lea las tres notas y determine cuál es la calificación total que recibirá el estudiante. Solamente hay tres casos posibles y son excluyentes, por lo que se usarán dos decisiones anidadas para verificar dos casos, y el tercero será la cláusula else. ''' # Cálculo de calificación final nota1 = int(input('Cual es la nota de tu primer examen: ')) nota2 = int(input('Cual es la nota de tu segundo examen: ')) nota3 = int(input('Cual es la nota de tu tercer examen: ')) # aquí añadimos 2 comparaciones que concatenadas con and obliga a que las dos sean verdaderas para que if # sea verdad t = 0 if nota1 >= nota3 and nota2 >= nota3: t = nota1 + nota2 else: if nota1 >= nota2 and nota3 >= nota2: t = nota1 + nota3 else: t = nota2 + nota3 print(f'Su calificación total es: {t}')
0c9b52ac97b2fbdf3f5a0321f7cf36646986f4ab
hector81/Aprendiendo_Python
/Integer/DevolverDigitos.py
391
4.09375
4
def introducirNumero(): while True: try: x = int(input("Por favor ingrese un número par: ")) return x break except ValueError: print("Oops! No era válido. Intente nuevamente...") numero = introducirNumero() numeroDigitos = len(str(numero)) print("El número tiene " + str(numeroDigitos) + " digitos")
0c8d83c250fa1300cde1e30bade521711b00199c
hector81/Aprendiendo_Python
/Integer/Introducir_Pares.py
396
4.125
4
def introducirNumero(): while True: try: x = int(input("Por favor ingrese un número par: ")) return x break except ValueError: print("Oops! No era válido. Intente nuevamente...") numero = 0 while numero%2 == 0: numero = introducirNumero() if numero%2 != 0: print("El numero era impar")
a5084140a8d49079bcbac4d8d6cc2cb27721ebab
hector81/Aprendiendo_Python
/Excepciones/Ejercicio2_texto_ruta_OSError.py
1,117
4.125
4
''' EJERCICIOS EXCEPCIONES 2. Programa que itere sobre una lista de cadenas de texto que contienen nombres de fichero hasta encontrar el primero que existe (OSError) [Pista: crear nuestra propia función, existe_fichero(ruta), que devuelve True o False] ''' # buscar fichero = Ejercicio2_texto_ruta_OSError.py def introducirNombreFichero(): while True: try: fichero = input(f"Por favor ingrese un nombre de fichero: ") if fichero != '': print(f"El fichero buscado es " + fichero) return fichero break except ValueError: print(f"Oops! No era válido. Intente nuevamente...") def existe_fichero(fichero): while True: try: with open(fichero,"r") as ficheroBuscar: print(f"Fichero encontrado") break except OSError: print(f"Fichero ' {fichero} ' no existe") finally: print(f"Operación terminada") break fichero = introducirNombreFichero() existe_fichero(fichero)
9570e6bbbe210122e6a2611d19622fabafac0777
hector81/Aprendiendo_Python
/CursoPython/Unidad6/Soluciones/ejercicio_I_u6 (2).py
637
4.3125
4
"""Diseña un programa que genere un entero al azar y te permita introducir números para saber si aciertas dicho número. El programa debe incluir un mensaje de ayuda y un conteo de intentos. """ import random num = int(input("Introduce un número del uno a l diez: ")) aleatorio = random.randint(1,10) while num != aleatorio: if num < aleatorio: print(f"El numero {num} es demasiado pequeño") num = int(input("Introduce otro")) elif num > aleatorio: print(f"El numero {num} es demasiado grande") num = int(input("Introduce otro")) print(f"Enhorabuena has acertado el num es {aleatorio}")
8c72ee9e300534e48b4f7ff9adad76e665e758b5
hector81/Aprendiendo_Python
/CursoPython/Unidad7/Ejemplos/funcion_nonlocal.py
558
4.15625
4
''' Si el programa contiene solamente funciones que no contienen a su vez funciones, todas las variables libres son variables globales. Pero si el programa contiene una función que a su vez contiene una función, las variables libres de esas "subfunciones" pueden ser globales (si pertenecen al programa principal) o no locales (si pertenecen a la función). ''' def myfunc1(): x = "John" def myfunc2(): nonlocal x x = "hello" myfunc2() return x print(myfunc1()) # devuelva la variable que está dentro de la subfuncion