blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0fa5eb00e017567a4be83ed88ffbc2b2bbdd2123
reyllama/leetcode
/Python/#7.py
847
4.15625
4
''' 7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' class Solution: def reverse(self, x: int) -> int: if x >= 0: r = int(str(x)[::-1]) else: r = -int(str(x)[1:][::-1]) return r if r in range(-2**31, 2**31) else 0 ''' Runtime: 20 ms, faster than 98.69% of Python3 online submissions for Reverse Integer. Memory Usage: 13 MB, less than 99.34% of Python3 online submissions for Reverse Integer. '''
true
d7240926fd437fd21e86fe98c928e1946d38cce3
reyllama/leetcode
/Python/#344.py
1,855
4.21875
4
""" 344. Reverse String Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ i = 0 while i < len(s)-1: if i==0: s.append(s[0]) s.pop(0) else: s.insert(len(s)-i, s[0]) s.pop(0) i += 1 """ Runtime: 1156 ms, faster than 5.15% of Python3 online submissions for Reverse String. Memory Usage: 18.1 MB, less than 95.68% of Python3 online submissions for Reverse String. """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ s.reverse() """ Runtime: 284 ms, faster than 12.82% of Python3 online submissions for Reverse String. Memory Usage: 18.4 MB, less than 23.22% of Python3 online submissions for Reverse String. """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ for i in range(len(s)//2): t = s[i] s[i] = s[len(s)-1-i] s[len(s)-1-i] = t """ Runtime: 264 ms, faster than 15.35% of Python3 online submissions for Reverse String. Memory Usage: 18 MB, less than 98.30% of Python3 online submissions for Reverse String. """
true
6996584587d1da1bea89feeac00a77acf8064f01
reyllama/leetcode
/Python/C739.py
1,665
4.1875
4
""" 739. Daily Temperatures Given a list of daily temperatures temperatures, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. For example, given the list of temperatures temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]. """ import collections class Solution(object): def dailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ ans = [0] * len(temperatures) memo = dict() for i, v in enumerate(temperatures): for key in memo.keys(): if memo[key] < v: del memo[key] ans[key] = i-key memo[i] = v return ans """ Time Limit Exceeded """ class Solution(object): def dailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ stack, ans = [], [0]*len(temperatures) for i, v in enumerate(temperatures): while stack and temperatures[stack[-1]] < v: cur = stack.pop() ans[cur] = i-cur stack.append(i) return ans """ Runtime: 452 ms, faster than 85.92% of Python online submissions for Daily Temperatures. Memory Usage: 17.2 MB, less than 82.60% of Python online submissions for Daily Temperatures. """
true
431b13b9f4000a3db036ff19a64714652560a1c6
HaiyuLYU/UNSW
/COMP9021-Principles-of-Programming/Quizzes/Q6/quiz_6.py
2,948
4.3125
4
# Defines two classes, Point() and Triangle(). # An object for the second class is created by passing named arguments, # point_1, point_2 and point_3, to its constructor. # Such an object can be modified by changing one point, two or three points # thanks to the method change_point_or_points(). # At any stage, the object maintains correct values # for perimeter and area. # # Written by *** and Eric Martin for COMP9021 from math import sqrt class PointError(Exception): def __init__(self, message): self.message = message class Point(): def __init__(self, x = None, y = None): if x is None and y is None: self.x = 0 self.y = 0 elif x is None or y is None: raise PointError('Need two coordinates, point not created.') else: self.x = x self.y = y # Possibly define other methods class TriangleError(Exception): def __init__(self, message): self.message = message class Triangle: def __init__(self, *, point_1, point_2, point_3): self.p1 = Point(point_1.x,point_1.y) self.p2 = Point(point_2.x,point_2.y) self.p3 = Point(point_3.x,point_3.y) if self.p1.y!=0 and self.p2.y!=0 and self.p3.y!=0: if(self.p1.x/self.p1.y)==(self.p2.x/self.p2.y)==(self.p3.x/self.p3.y): raise TriangleError('Incorrect input, triangle not created.') elif self.p1.y==0 and self.p2.y==0 and self.p3.y==0: raise TriangleError('Incorrect input, triangle not created.') a = sqrt((self.p1.x-self.p2.x)**2+(self.p1.y-self.p2.y)**2) b = sqrt((self.p2.x-self.p3.x)**2+(self.p2.y-self.p3.y)**2) c = sqrt((self.p1.x-self.p3.x)**2+(self.p1.y-self.p3.y)**2) p = (a+b+c)/2 self.area =sqrt(p*(p-a)*(p-b)*(p-c)) self.perimeter = a+b+c def change_point_or_points(self, *, point_1 = None,point_2 = None, point_3 = None): if point_1 is not None: self.p1 = point_1 if point_2 is not None: self.p2 = point_2 if point_3 is not None: self.p3 = point_3 flag = 0 if self.p1.y!=0 and self.p2.y!=0 and self.p3.y!=0: if(self.p1.x/self.p1.y)==(self.p2.x/self.p2.y)==(self.p3.x/self.p3.y): print('Incorrect input, triangle not modified.') flag = 1 elif self.p1.y==0 and self.p2.y==0 and self.p3.y==0: print('Incorrect input, triangle not modified.') flag = 1 if flag ==0: a = sqrt((self.p1.x-self.p2.x)**2+(self.p1.y-self.p2.y)**2) b = sqrt((self.p2.x-self.p3.x)**2+(self.p2.y-self.p3.y)**2) c = sqrt((self.p1.x-self.p3.x)**2+(self.p1.y-self.p3.y)**2) p = (a+b+c)/2 self.area =sqrt(p*(p-a)*(p-b)*(p-c)) self.perimeter = a+b+c # Possibly define other methods
true
a252aaed19f3ab44a5366ab8022fbfe2787a6987
MattB70/499-Individual-Git-Exercise
/DumbSort.py
1,771
4.15625
4
# Sorting Integers or Strings. # Matthew Borle # September 14, 2021 # Python 2.7.15 while True: input_type = raw_input("Integers or Strings? (Ii/Ss): ") if input_type == "I" or input_type == "i": print "Integers selected" array = raw_input("Input integers seperated by spaces:\n") print "Input:\t" + array array = array.split(" ") array = [x for x in array if x.isdigit()] # remove any non numeric values array.sort(key=int) print "Output:\t" + " ".join(array) break; if input_type == "S" or input_type == "s": print "Strings selected" array = raw_input("Input strings seperated by spaces:\n") print "Input:\t" + array array = array.split(" ") array = [x for x in array if not x.isdigit()] # remove any non string values array.sort(key=str) print "Output:\t" + " ".join(array) break; if input_type == "T" or input_type == "t": # Test print "Tests selected" print "String Input:\torange apple grape strawberry blackberry" strings = "orange apple grape strawberry blackberry" strings = strings.split(" ") strings = [x for x in strings if not x.isdigit()] # remove any non string values strings.sort(key=str) print "String Output:\t" + " ".join(strings) print "Integer Input:\t2 9 5 0 1 10 4 21 9 1" integers = "2 9 5 0 1 10 4 21 9 1" integers = integers.split(" ") integers = [x for x in integers if x.isdigit()] # remove any non numeric values integers.sort(key=int) print "Integer Output:\t" + " ".join(integers) break; else: # User input invalid argument. print "Invalid input type. Try again.\n"
true
7057b8a23fbfddadfae7d4e86db3428fae4c405d
yangsg/linux_training_notes
/python3/basic02_syntax/classes/02_a-first-look-at-classes.py
2,324
4.625
5
#// https://docs.python.org/3.6/tutorial/classes.html#a-first-look-at-classes #// 类定义需要先执行才能生效(可以将class 定义放在if 语句块或函数的内部) if True: class ClassInIfBlock(): pass def function(): class ClassInFunction: pass #// 当进入 class definition 时,被当做 local scope的一个新的名字空间(namespace) 就被创建了 #// When a class definition is entered, a new namespace is created, and used as the local scope — thus, #// all assignments to local variables go into this new namespace. In particular, #// function definitions bind the name of the new function here. #// When a class definition is left normally (via the end), a class object is created. #// This is basically a wrapper around the contents of the namespace created by the class definition; #// we’ll learn more about class objects in the next section. The original local scope #// (the one in effect just before the class definition was entered) is reinstated, #// and the class object is bound here to the class name given in the class definition header (ClassName in the example). #// Class objects 支持两种类型的操作:成员引用 和 实例化 #// Class objects support two kinds of operations: attribute references and instantiation. class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' print(MyClass.i) #// 12345 print(MyClass.f) #// <function MyClass.f at 0x7efe4bb270d0> MyClass.i = 7777 print(MyClass.i) #// 7777 print(MyClass.__doc__) #// A simple example class #// 类的实例化,即创建一个属于该类的对象 x = MyClass() #// 有点类似于java 中的 'new MyClass()', 但是python中没有new关键字 #// python中的 __init__ 函数作用类似于 java中的构造器函数的作用 class ClassWithInitFunction(): def __init__(self): #// 带有 __init__ 初始函数的类, 每次实例化时会被自动调用 self.data = ['a', 'b'] x = ClassWithInitFunction() print(x.data) #// ['a', 'b'] #// __init__ 函数接收参数的类 class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print('x.r = {}, x.i = {}'.format(x.r, x.i)) #// x.r = 3.0, x.i = -4.5
true
31e193aaaeba31bf82941aa2da1dc1c1c17e58b8
pxue/euler
/problem20.py
2,910
4.1875
4
# Problem20: Factorial digit sum # find sum of factorial of 100! # Python has builtin Math.Factorial function # let's see how that's implemented # From python src code # Divide-and-conquer factorial algorithm # # Based on the formula and psuedo-code provided at: # http://www.luschny.de/math/factorial/binarysplitfact.html # # Faster algorithms exist, but they're more complicated and depend on # a fast prime factorization algorithm. # # Notes on the algorithm # ---------------------- # # factorial(n) is written in the form 2**k * m, with m odd. k and m are # computed separately, and then combined using a left shift. # # The function factorial_odd_part computes the odd part m (i.e., the greatest # odd divisor) of factorial(n), using the formula: # # factorial_odd_part(n) = # # product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j # # Example: factorial_odd_part(20) = # # (1) * # (1) * # (1 * 3 * 5) * # (1 * 3 * 5 * 7 * 9) # (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) # # Here i goes from large to small: the first term corresponds to i=4 (any # larger i gives an empty product), and the last term corresponds to i=0. # Each term can be computed from the last by multiplying by the extra odd # numbers required: e.g., to get from the penultimate term to the last one, # we multiply by (11 * 13 * 15 * 17 * 19). # # To see a hint of why this formula works, here are the same numbers as above # but with the even parts (i.e., the appropriate powers of 2) included. For # each subterm in the product for i, we multiply that subterm by 2**i: # # factorial(20) = # # (16) * # (8) * # (4 * 12 * 20) * # (2 * 6 * 10 * 14 * 18) * # (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19) # # The factorial_partial_product function computes the product of all odd j in # range(start, stop) for given start and stop. It's used to compute the # partial products like (11 * 13 * 15 * 17 * 19) in the example above. It # operates recursively, repeatedly splitting the range into two roughly equal # pieces until the subranges are small enough to be computed using only C # integer arithmetic. # # The two-valuation k (i.e., the exponent of the largest power of 2 dividing # the factorial) is computed independently in the main math_factorial # function. By standard results, its value is: # # two_valuation = n//2 + n//4 + n//8 + .... # # It can be shown (e.g., by complete induction on n) that two_valuation is # equal to n - count_set_bits(n), where count_set_bits(n) gives the number of # '1'-bits in the binary expansion of n. #/ # factorial_partial_product: Compute product(range(start, stop, 2)) using # divide and conquer. Assumes start and stop are odd and stop > start. # max_bits must be >= bit_length(stop - 2). from math import factorial print reduce(lambda x, y: x + y, [int(i) for i in str(factorial(100))])
true
f74dde0261038d46e3ada75c994c31d62ee9dba1
rugbyprof/2143-ObjectOrientedProgramming
/ClassLectures/day01.py
2,090
4.59375
5
import random # simple print! print("hello world") # create a list a = [] # prints the entire list print(a) # adds to the end of the list a.append(3) print(a) # adds to the end of the list a.append(5) print(a) # adds to the end of the list, and python doesn't care # what a list holds. It can a mixture of all types. a.append("mcdonalds") print(a) # I can also append alist to a list. # Lists of lists is how we represent multi-dimensional data (like 2D arrays) a.append([1,2,3,'a','b']) print(a) s = "hello " t = "world" st = s + t # python 'overloads' the `+` sign to perform a concetenation # when adding strings. print(st) # simple loop that loops 10 times # the 'range' function returns a 'list' in this case # the list = [0,1,2,3,4,5,6,7,8,9] for i in range(10): # appand a random integer between 0 and 100 a.append(random.randint(0,100)) # This loop 'iterates' over the 'container' 'a' placing # subsequent values in x for x in a: print(x) # Another way of looping over a container (list). # This has a more traditional c++ 'feel' to it. for j in range(len(a)): print(a[j]) print() # print the last element in a list print(a[len(a)-1]) # print the last element in a list (cooler way) print(a[-1]) # Prints a "slice" of the list. In this case 2,3,4 (not 5). print(a[2:5]) # Loop and jump by two's. Remember the range function takes different param numbers. # 1. param = size of list to return # 2. params = starting value, ending value that list will contain # 3. params = same as 2. but adds an 'increment by' value as the third param for i in range(0,len(a),2): print(a[i]) print(a) #Insert a value into a position in the list, without overwriting another value a.insert(7,'dont jack my list') # This would overwrite value at a[7] # Or error if index did not exist a[7] = 'dont jack my list' print(a) # Just like appending to the list a.insert(len(a),'please work') print(a) # Should error, but defaults to appending to end of list a.insert(len(a)+3,'hmmmm') # prints second to last item print(a[-2]) # errors a[len(a)+2] = '999999'
true
165acb2cc72d57f0d8943f97abb0c7ce17f33b42
yangreal1991/my_leetcode_solutions
/0035.search-insert-position/search-insert-position.py
847
4.28125
4
import numpy as np class Solution: def __init__(self): pass def searchInsert(self, nums, target): """Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. Args: nums: List[int] -- a sorted array target: int -- target value Returns: result: int -- the the index where it would be if it were inserted in order """ if len(nums) == 0: return "Length of nums must be greater than 0." for i, num in enumerate(nums): if num >= target: return i return len(nums) if __name__ == '__main__': s = Solution() nums = [1,3,5,6] target = 5 print(s.searchInsert(nums, target))
true
d026133e160d8f0b83b5167fb1898c5334147cf4
MattMackreth/BasicsDay1
/02datatypes_strings.py
1,689
4.59375
5
# # Data types # # Computers are stupid # # they don't understand context so we need to be specific with data types # # # We can use type() to check datatypes # # # Strings # # lists of characters bundled together in a specific order # # using index # print('hello') # print(type('hello')) # # # Concatentation of strings # string_a = 'hello there' # name_person = 'Juan Pier' # print(string_a + ' ' + name_person) # # # Useful methods # # Length # # Returns the length of a string # print(len(string_a)) # print(len(name_person)) # # # Strip # # Removes trailing or prevailing white spaces # string_num = ' 90383 ' # print(string_num) # print(string_num.strip()) # # # .Split this is a method for strings # # it splits in a specific location and outputs a list (data type) # string_text = 'Hello I need to test this' # split_string = string_text.split(' ') # print(split_string) # # # Capturing user input # # get user input of first name # # save user input to variable # # get user last name and save it to variable # # join the 2 # # print # # user_fname = input('What is your first name? ') # user_lname = input('What is your last name? ') # # Concatenation # user_name = user_fname + ' ' + user_lname # print('Hello ' + user_name) # # Interpolation - use f in front of string to add python into the string # welcome_message = f"Hi {user_name}, you are very welcome!" # print(welcome_message) # ctrl + / for mass comment out # Count/Lower/Upper/Capitalize text_example = "here is sOMe text wItH a whole bunch of lots of text, so much text wow" # Count print(text_example.count('e')) print(text_example.upper()) print(text_example.capitalize()) print(text_example.lower()) # Casting
true
701af849fc555f9c802f3d3f60c16569455d8bd6
Vantom16/security_system
/security.py
1,058
4.21875
4
#Creating our Security System # Code output is displayed in command line #First we create a list of known users known_users = ["Alice", "Jane", "David", "Paul", "Eli", "Isme"] while True: print("Hi! My name is Joe") name =input("What is your name?: ").strip().capitalize() #Computer will compare name given and ones in our database. if name in known_users: print("Hello {}".format(name)) # If our users wants to be removed from the system remove = input("Would you like to be removed from the system (y/n)?").strip().lower() if remove == "y": known_users.remove(name) elif remove == "n": print("No problem. I didn't want you to leave anyway! ") else: print("Hmmm I don't think I have met you yet {}".format(name)) add_me =input("Would you like to be added to our system (y/n)?: ").strip().lower() if add_me == "y": known_users.append(name) elif add_me == "n": print("No worries. See you around!")
true
031291a9602fdc584e02649768b0ef0d9fa3d1c4
valievav/Python_programs
/Practice_exercises/training/mini_tasks.py
2,730
4.1875
4
# Related read # https://realpython.com/python-coding-interview-tips/#select-the-right-built-in-function-for-the-job # https://docs.python.org/3/library/functions.html#built-in-functions section_sep = '' # EVEN numbers x = [11,1,3,4,5,6,8,9,10,1,3] even_only = [i for i in x if i %2==0] print(even_only) print(section_sep) ################################## # get COUNT of particular element in list one_cnt = x.count(1) print(one_cnt) # get COUNT of ALL elements in a list list_elem_cnt = {i: x.count(i) for i in x} print(list_elem_cnt, type(list_elem_cnt)) # COUNT number of each letter in a word from collections import Counter word = "tomatoes, potatoes, brokkoli" print({i: word.count(i) for i in word}) print(Counter(word)) # COUNT words in sentence sentence = "It was a really great trip" print(len(sentence.split())) print(section_sep) ################################### # FIND DUPES in array from collections import Counter dupes = [k for k, v in Counter(x).items() if v > 1] print(dupes) dupes = [k for k, v in list_elem_cnt.items() if v > 1] print(dupes) # REMOVE DUPES deduped = list(set(x)) print(deduped) # REMOVE DUPES option for ordered list print(list(dict.fromkeys(x))) print(section_sep) ##################################### # SORT list char = ['d', 'K', 'd', 'c', 'a'] char.sort(key=str.lower) # in-place print(char) print(sorted(char, key=str.lower)) # copy and sort print(section_sep) ##################################### # REVERSE list order with slicing l = [1,2,3,4,5,6,7] print(l[::-1]) # REVERSE list order with reverse iter print(list(reversed(l))) # REVERSE list order with reverse method l.reverse() print(l, ) print(section_sep) ###################################### # get LENGTH for each element in a list words = ['asd', 'zxcvb', 'a', 'qwerty'] print(list(map(len, words))) print(section_sep) ####################################### # UPDATE each element of a list to upper print(list(map(lambda x: x.upper(), words))) # ADD 2 lists x1 = [1,2,3,4,5] x2 = [6,7,8,9,10] print(list(map(lambda x,y: x+y, x1, x2))) print(section_sep) ####################################### # get EVERY 2nd element in a list x = [1,2,3,4,5,6] print(x[::2]) print(section_sep) print(section_sep) #################################### # Generate every possible COMBINATION between elements of a list (order doesn't matter) import itertools people = ['Mary', 'Jake', 'Sandy', 'Becca', 'Robin'] print(list(itertools.combinations(people, r=4))) print(section_sep) ################################## # Generate every possible PERMUTATIONS between elements of a list (order does matter) print(list(itertools.permutations(people, r=2))) print(section_sep) ##################################
true
9717caa2c2fccc161cd400a18bad6574237374be
valievav/Python_programs
/Practice_exercises/reverse_word_order.py
917
4.375
4
# https://www.practicepython.org/exercise/2014/05/21/15-reverse-word-order.html # Write a program that asks the user for a long string containing multiple words. # Print back to the user the same string, except with the words in backwards order. # For example 'My name is Michele' -> 'Michele is name My' def reverse_with_reverse_method(sentence: str) -> str: words = sentence.split() words.reverse() return ' '.join(words) def reverse_with_slicing(sentence: str) -> str: words = sentence.split() return ' '.join(words[::-1]) # [start: end: step] def reverse_with_reversed_iterator(sentence: str) -> str: words = sentence.split() return ' '.join(list(reversed(words))) # yields elements user_input = input('Please enter a sentence.\n') solutions = [ reverse_with_reverse_method, reverse_with_slicing, reverse_with_reversed_iterator, ] print(solutions[0](user_input))
true
70808716d0d3ae632945a34ffc58c57326666ce6
tmetz/ITP195
/notes/ch4.py
2,233
4.1875
4
import math import string #my_utf = ord("h") # Returns integer (ordinal) UTF-8 value of char #my_utf_ch = chr(121) # Returns UTF-8 char #print(my_utf, my_utf_ch) my_str = "This is a test of a string" #print(my_str[:8]) # Print from beginning to 7th char. Does not print the 8th character!!! # Extended slicing: # [start:finish:countBy] #print(my_str[0:11:2]) # prints every other letter (count by 2) # reversing a string: reverse_my_str = my_str[::-1] #print(reverse_my_str) #print(my_str*5) #print(my_str.upper().find('S')) # chaining #my_str = my_str.upper() #print(my_str) # print("TEST" in my_str) # print(len(my_str)) # print(my_str.find('T')) # Assume start looking from 0 # print(my_str.find('T',11)) # Start looking from character 11 # # # Nested methods: # print(my_str.find('T', my_str.find('T')+1)) # Find the second 'T' #print("This is a {:_>15} test of {}".format("not", "something cool.")) # for i in range(5): # print("{:10d} --> {:4d}".format(i,i**2)) # # print("Pi is {:.10f}".format(math.pi)) # pi to 10 decimal places # river = "Mississippi" # target = input("Input a character to find: ") # for index in range(len(river)): # if river[index].lower() == target.lower(): # print("Letter \"{}\" found at index: {}".format(target, index)) # break # else: # print("Letter \"{}\" not found in \"{}\"".format(target, river)) # river = "Mississippi" # target = input("Input a character to find: ") # for index,letter in enumerate(river): # if letter.lower() == target.lower(): # print("Letter \"{}\" found at index: {}".format(target, index)) # break # else: # print("Letter \"{}\" not found in \"{}\"".format(target, river)) new_str = "This is a test string to split" new_list = new_str.split(" ") print(new_list) name_str = "Tamara Leah Metz" first_name, middle_name, last_name = name_str.split(" ") print(middle_name) pal_str = "Madam, I'm Adam" modified_str = pal_str.lower() bad_chars = string.whitespace + string.punctuation for char in modified_str: if char in bad_chars: modified_str = modified_str.replace(char,"") if modified_str == modified_str[::-1]: print(\ "The original string is {}\n") # Need to finish copying this!!!!!
true
28b8a10bc86eb1393dfb88d0d0192c4c4a2a2e18
tmetz/ITP195
/Homework/stack.py
1,332
4.25
4
""" Tammy Metz ITP 195 - Topics In Python HW 4 - due April 9, 2018 Create a python module called "stack" that has methods for popping, pushing, and returning the top of the stack """ class Stack(object): def __init__(self, stack_as_list): self.stack = stack_as_list def is_empty(self): if len(self.stack) == 0: return True else: return False def top(self): return self.stack[-1] def push(self, item_to_add): self.stack.append(item_to_add) def pop(self): popped_item = self.stack.pop() return (popped_item) def __str__(self): return_string = "" self.stack.reverse() # Reversing order so we can print FILO order for item in self.stack: return_string = return_string + str(item) + "\n" self.stack.reverse() # Put it back in order return(return_string) def main(): list1 = [9, "Bob", 5.8] stack1 = Stack(list1) for i in range(10): stack1.push("Extra item "+str(i)) print("") print("The top of the stack is {} \n".format(stack1.top())) print("Printing the stack object: ") print(stack1) print("Popping items....") while not stack1.is_empty(): print("Popping {}".format(stack1.pop())) if __name__ == "__main__": main()
true
ed02008cb439f9c84cbbc1aa022fa87f9465e1e4
Spookyturbo/PythonCourse
/Week2/Lab3/guessNumber-ariedlinger.py
855
4.28125
4
#Guess My Number #Andrew Riedlinger #January 24th, 2019 # #The computer picks a random number between 1 and 100 #The player tries to guess it and the computer lets #the player know if the guess is too high, too low #or right on the money import random print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") #set the initial values theNumber = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 #guessing loop while(guess != theNumber): if(guess > theNumber): print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 #Congratulations print("You guessd it! The number was", theNumber) print("And it only took you", tries, "tries!\n") input("\n\nPress the enter key to exit.")
true
94d88ae01f38050fa8f03842be24da5a3f860ab1
tgoel5884/twoc-python
/Day4/program2.py
542
4.3125
4
a = int(input("Enter the no of tuples you want to add in the list: ")) b = int(input("Enter the no of elements you want to add in each tuple: ")) List = [] for i in range(a): print("Enter the elements in Tuple", i + 1) Tuple = [] for j in range(b): Tuple.append(int(input("Enter the element: "))) List.append(tuple(Tuple)) N = int(input("Enter index about which you want to sort the list: ")) List.sort(key = lambda x : x[N]) print("After sorting tuple List by Nth index sort:",List) # Code by Tanmay Goel
true
9cfc335ffe0c53f298a637da72223abb916829c6
Fin-Syn/Python-Beginings
/first_list.py
1,249
4.59375
5
days_of_week = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'] print (days_of_week [2]) #Changes element in the list days_of_week [0] = 'Sunday' print (days_of_week) #Slices the list, but formats is as stated in the list print (days_of_week [2:5]) #Example nested list, when printing needs to call list, then item within list child1 = ['Pat', 5, 6.5] family = [child1] print (family [0] [1]) kevin_list = [] #Adding single values to a list kevin_list.append ('kevin') kevin_list.append ('wolf') print (kevin_list) #Adding multiple values to a list in one line of code kevin_list.extend (['july 26', 29]) print (kevin_list) #Second way of adding multiple lines to a list kevin_list = kevin_list + [1991, 'learning python'] #Insert a value in the selected spot kevin_list.insert (3, 'age') print (kevin_list) #Removes only the first instance of selected vaule kevin_list.remove ('age') print (kevin_list) #(max () ) prints highest value in list number = [16, 8, 15, 42, 23, 4] print (max(number)) #Automatically sorts list based on pythons defualt, sort can be configured number.sort() print (number) #Reverses the order of the list kevin_list.reverse() print (kevin_list)
true
edc76b2b6c2a2926e3a4f9529829661fe5eb2669
Stashare/Bc13_Day2
/missingnumber.py
558
4.21875
4
"""MissingNumber""" def find_missing(a,b): temparr=[] #an array that stores missing numbers temporarily during the loop #and it is assigned to outputarr. outputarr=[0] #output the final result #loop to check whether there is missing numbers for i in b: if i not in a: temparr.append(i) outputarr=temparr print outputarr find_missing([], [])#A call to the find_missing function,passing arrays as parameters #the output should be [0]
true
c8b0db36c366681ec0245f0441a2ab8e25d59e82
chelseacx/CP1404
/Practicals/workshop 4/calculating_bmi.py
587
4.15625
4
def get_float_value(variable_name, measurement_unit): while True: try: float_value = float(input("Please enter your {} in {}: ".format(variable_name, measurement_unit))) break except ValueError: print("Invalid value!") return float_value print("Body-mass-index calculator, for CP1404") weight = get_float_value("weight", "kgs") """ function that gets the float value""" height = get_float_value("height", "m") bmi = weight / (height * height) print("Therefore, your BMI value is: {:.2f}".format(bmi)) print("Thank you!")
true
e8bf766cb61490a70fbc298c790b0aadcaf2b1de
Mrklata/Junior
/tuples.py
766
4.15625
4
def tuple_checker(a, b): unique_a = set(a) - set(b) unique_b = set(b) - set(a) if a == b: return 'tuples are equal' if unique_b != unique_a: return f'tuples are not equal and the unique values are a: {unique_a}, b: {unique_b}' else: return 'tuples are not equal but have the same values' def test_tuple(): same_tuples = tuple_checker((1, 2, 3), (1, 2, 3)) same_values_tuple = tuple_checker((1, 2, 3), (3, 2, 1)) different_tuples = tuple_checker((1, 2, 3), (2, 3, 5, 7, 5, 4)) assert same_tuples == "tuples are equal" assert same_values_tuple == "tuples are not equal but have the same values" assert different_tuples == "tuples are not equal and the unique values are a: {1}, b: {4, 5, 7}"
true
63ee2a4321f54f09e2c06cccb689b017ad090a6a
MythiliPriyaVL/PySelenium
/venv/ProgramCode/34-ModuleItertools.py
573
4.46875
4
""" Define a function even_or_odd, which takes an integer as input and returns the string even and odd, if the given number is even and odd respectively. Categorise the numbers of list n = [10, 14, 16, 22, 9, 3 , 37] into two groups namely even and odd based on above defined function. Hint : Use groupby method of itertools module. Iterate over the obtained groupby object and print it's group name and list of elements associated with a group. """ def even_or_odd(inputI): if(inputI%2==0): return "Even" else: return "Odd" n=[10,14,16,22,9,3,37]
true
a81870d539a8fd5de0f7c7514a04bcfd87532f6f
MythiliPriyaVL/PySelenium
/venv/ProgramCode/31.2-TimeDelta.py
1,244
4.28125
4
#Example file for timedelta from datetime import datetime from datetime import date from datetime import time from datetime import timedelta def main(): # basic timedelta print(timedelta(days=365, hours=5, minutes=1)) #Today's date now = datetime.now() print("Today is: ", str(now)) #Today's date one year from now print("One year from now, it will be: ", str(now+timedelta(365))) # timedelta with more argument print("In 2 days and 3 weeks, it will be: ", str(now + timedelta(days=2, weeks=3))) #Calculate Date 1 week ago, formatted as a String t= datetime.now() - timedelta(weeks=1) s = t.strftime("%A %B %d, %Y") print("One week ago it was: ", s) #How many days until April fool's day today = date.today() afd = date(today.year, 4, 1) #2020-04-01 #Check if the April Fool's day already went by if afd < today: print("April fool's day already went by %d days ago" %((today-afd).days)) afd = afd.replace(year = today.year+1) time_to_afd = afd-today print("It's just ", time_to_afd.days," days until April Fool's day") print(timedelta.max) print(timedelta.min) print(timedelta.resolution) if __name__ =="__main__": main();
true
6505d7aa96966839827ac72822be80332f018413
MythiliPriyaVL/PySelenium
/venv/ProgramCode/11-PrimeNumbers.py
668
4.25
4
#5. Print prime numbers below a given number. #Get input from the User and print whether the value is Prime or Not numberInput = int(input("Enter any number, I can print the Prime Numbers below that :")) #Validating the Input value if (numberInput == 1 or numberInput == 2 ): print("There is no Prime Number below " + str(numberInput)) else: print("Prime numbers below " + str(numberInput) + " are: ") print("2") x = 1 for num in range(3, numberInput,2): for i in range(2, num): if (num % i) == 0: break else: x = x + 1 print(num) print("Total number of prime numbers are: ", x)
true
a6c3a5848f1f16bddcf0f65e0927b6cc7d396eb3
MythiliPriyaVL/PySelenium
/venv/ProgramCode/05-LoginCheck.py
740
4.15625
4
""" Login Testing: 1. User Name and Password are hardcoded in the program 2. User should enter right combination of values to login 3. User can try upto 3 times and the program stops after that. """ #Hardcoded User Name and Password values uN1 = "newUser" uP1 = "09876" #Looping for 3 maximum attempts for x in range(3): #User Input for User Name and Password uName = input("Enter the User Name: ") uPassword = input("Enter the Password: ") if(uN1 == uName and uP1 == uPassword): print("User login Successful.") print("Access granted") break else: print("User login Unsuccessful.") print("Access Denied") else: print("Maximum attempts reached. Try after sometime.")
true
1deb4d6cf623e49cff90450de4087c1c5433b18a
demetredevidze/edge-final-project
/final.py
1,377
4.28125
4
# day_1_game.py # [Demetre Devidze] import random rules = "Rules are simple! You get 5 chances to guess a random integer between 0 and 30. " hint1 = "PS, 5 tries is definitely enough! If you play smart you will be able to win the game every single time!" hint2 = "Think about the powers of 2. Two to the power of five is 32, so you have enough number of tries." user_name = input("Hey, what's your name? \n") print("Hi " + user_name + ", would you like to play a game on guessing random numbers?") play_game = input() if play_game == "yes" or "Yes" or "YES" or "yeah" or "YEAH" or "Yeah" or "Sure" or "sure" or "SURE" or "lets do it": print("Great decision " + user_name + "! " + rules + " Good luck!") print(hint1) answer = random.randint(0, 30) for guess_number in range(5): guess = input("what is your guess:") if int(guess) == answer: print("Well done " + user_name + "! You got it right!") break elif int(guess) > answer: print("Too big " + user_name + "! Try again!") elif int(guess) < answer: print("Too small " + user_name + "! Try again!") else: print("Sorry " + user_name + "! You are out of guesses!") print("But I will give you a hint! " + hint2 + " Play smarter next time!") else: print("Okay " + user_name + "! No hard feelings, have a nice day!")
true
26c9f7e383cce71cde211cd35562d951f7c64c54
RAJARANJITH1999/Python-Programs
/even.py
214
4.1875
4
value=int(input("enter the value to check whether even or odd")) if(value%2==0): print(value,"is a even number") else: print(value,"is odd number") print("vaule have been checked successfully")
true
2d2147a5e19328d03bb6105bc77f569881ccfced
RAJARANJITH1999/Python-Programs
/shirt.py
880
4.125
4
white=['M','L'] blue=['M','S'] available=False print("*****search for your color shirt and size it*****") color=input("enter your shirt color") if(color.lower()=='white'): size=input("enter your size") if((size.upper() in white)): print("available") available=True else: print("unavailable") elif( color.lower()=='blue'): size=input("enter your size") if(size.upper() in blue): print("available") available=True else: print("unavailable") else: print("unvailable") if(available==True): name=input("enter your name ") address=input("enter the addres to place order") mobile=int(input("enter your mobile number")) print("********order confirmation*******") print("name:",name) print("address:",address) print("mobile:",mobile) print("***ordered shirt***\n","color:",color,"\nsize:",size.upper())
true
7346df8393977718803fbe9c33ab377afb56a2c9
wengellen/cs36
/searchRotatedSortedArray.py
554
4.1875
4
# Given an integer array nums sorted in ascending order, and an integer target. # # Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # # You should search for target in nums and if found return its index, otherwise return -1. # # Example 1: # Input: nums = [6,7,0,1,2,3,4,5], target = 0 # Output: 2 # # Example 2: # Input: nums = [6,7,0,1,2,3,4,5], target = 3 # Output: 5 # # Example 3: # Input: nums = [1], target = 0 # Output: -1 def csSearchRotatedSortedArray(nums, target):
true
0d7662fc3a197bb8d5fb992726c99597bd2a410c
wengellen/cs36
/linkedListPatterns.py
859
4.125
4
class LinkedListNode: def __init__(self, value): self.value = value self.next = None self.prev = None x = LinkedListNode('X') y = LinkedListNode('Y') z = LinkedListNode('Z') x.next = y y.next = z y.prev = x z.prev = y def print_ll_reverse(tail): current = tail while current is not None: # print(current.value) current = current.prev # traverse a linked list and print value of each node def print_ll(head): # init a new variable to refer to the node we have # access to current = head # use while loop to keep traversing until our # `current` variable falls off the tail of the ll while current is not None: print(current.value) # update our `current` variable to refer to the # next node in the ll current = current.next print_ll_reverse(z)
true
b743ffa0b4a76bceb5b53afb58b2e3b2106652e9
tsoutonglang/gwc-summer-2017
/your-grave.py
2,059
4.1875
4
start = ''' You wake up strapped to a chair at the bottom of a grave. Your arms are tied behind your back, and your feet are tied to the chair. You look up and see the Riddler standing over you with a shovel in his hand. "You have to play my games to live. It's game over once you get a riddle wrong. Get all three right then everyone lives! If you get the first two right, you and one other person dies. If you only get the first one wrong then you and three people die. It's game over for you and five innocents if you get them all wrong! He stabbed the shovel into the ground and rubbed his hands together. 'Let's begin" ''' print(start) print("People endangered: 5") print("'What is the beginning of eternity, the end of time and space, the beginning of every end, and every race?''") user_input = input() if user_input == "e": print("'Congrats, you just saved yourself and two others...''") print("People endangered: 3") print("'What starts with the letter 'e,' ends with 'e,' but only has one letter?''") user_input = input() if user_input == "eye": print("'Congrats, you saved two more people. Ready for the final round?''") print("People endangered: 1") print("'What belongs to you, but is used by others?'") user_input = input() if user_input == "your name": print("'Congradulations young Gothamite, you saved your butt and 5 people'") print("The Riddler walks away from the grave leaving you tied to the chair six feet below the ground.") else: print("'You little idiot.' He takes the shovel and buries you in dirt. 'I hope your guilty conscience can deal with killing someone... Oh wait, you're gonna be dead too!'") print("People killed: 1") else: print("'WHY DO YOU DO THIS?!' He angrily grabs the shovel and knocks you out with it. He begins to bury you alive.") print("People killed: 3") else: print("The Riddler shakes his head and grabs his shovel to bury you alive.") print("People killed: 5")
true
1c30b6fff4469000460b9518314899e67004f706
manas-mukherjee/MLTools
/src/tutorials/fluentpython/function_as_objects/TestFunction.py
2,833
4.15625
4
############################################## # Treating a Function Like an Object # ############################################## # Example 5-1 print('\nExample 5-1\n------------\n') def factorial(n): '''Returns n factorial''' return 1 if n<2 else n * factorial(n-1) print(factorial(42)) print(factorial.__doc__) print(type(factorial)) print(help(factorial)) # Example 5-2 print('\nExample 5-2\n------------\n') fact = factorial print(fact(6)) print(list(map(fact, range(10)))) # Example 5-3 print('\nExample 5-3\n------------\n') # Higher order functions # Imp: map, filter, and reduce fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=len, reverse=True)) # Example 5-4 print('\nExample 5-4\n------------\n') def reverse(word): return word[::-1] print(sorted(map(reverse, fruits), key=len)) # Example 5-5 print('\nExample 5-5\n------------\n') # A listcomp or a genexp does the job of map and filter combined, but is more readable. #Old way using list - Build a list of factorials from 0! to 5!. print(list(map(fact, range(6)))) #New way using list comprehension. print([fact(num) for num in range(6)]) #Old way using list - List of factorials of odd numbers up to 5!, using both map and filter.. print(list(map(fact, filter(lambda n : n%2, range(6))))) #New way using list comprehension. print([fact(num) for num in range(6) if num % 2]) # Example 5-6 print('\nExample 5-6\n------------\n') #Starting with Python 3.0, reduce is not a built-in. from functools import reduce from operator import add print(reduce(add, range(100))) print(sum(range(100))) l = [n for n in range(25) if n % 2 == 0] print(l) print(all(l[1:])) print(any([1,0,0,0])) ############################################## # Anonymous Functions # ############################################## # Example 5-7 print('\nExample 5-6\n------------\n') fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits, key=reverse)) print(sorted(fruits, key = lambda x : x[::-1])) ############################################## # User-Defined Callable Types # ############################################## # Example 5-8 print('\nExample 5-8\n------------\n') import random class BingoCage: def __init__(self, items): self._items = list(items) random.shuffle(self._items) def pick(self): try: return self._items.pop() except IndexError: raise LookupError('pick from empty BignoCase') def __call__(self, *args, **kwargs): return self.pick() bingo = BingoCage(range(3)) print("direct - " , bingo()) for i in range(2): p = bingo.pick() print(p) # for l in dir(factorial): # print(l) print(factorial.__dict__) import bobo
true
19f26e9acaab20e6ca4c43ab04797cafa9fb6f0f
Sciencethebird/Python
/Numpy/arrange and linspace.py
686
4.125
4
import matplotlib.pyplot as plt import numpy as np import math # arange and linespace both output np array # arange: x1 form [0, 10) increase by 1 x1 = np.arange(0,10,0.1) print(x1) # linespace: x2 belongs to [10, 2] with twenty dots x2 = np.linspace(10,2,50) print('numpy array is converted to a python list \n', list(x2)) y1 = np.sin(x1) y2 = np.cos(x2) #1. math functions do not take np array #2. math functions do not take list (one in one out) #y3 = math.tan(list(x1)) #Visualization using matplotlib plt.plot(x1, y1, label = 'arrange') plt.plot(x2, y2, label = 'linspace') plt.xlabel = 'x' plt.ylabel = 'y' plt.title = 'arrange vs linespace' plt.legend() plt.show()
true
3ec05fbcb0a83872f6dc2454482e07aca2e52229
zanda8893/Student-Robotics
/.unused/code.py
2,586
4.1875
4
import time import random """ this is a rough first attempt which shouldn't work """ class move(): """ the general movement methods for the robot they are programmed here for easy access and to make it easier when implementing new ideas # TODO: add proper moter commands for starting and stoping to robit code branch """ """ this class is working on the assumption that we dont have any sensors updating the position once we have sensors, we can update this to get more accurete movement """ def forward(self, distance): #move forward code print("Forward class") print("moving",distance) sleep = distance / 2.2 #convert the distance into time s = d / t if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep moters = True #power the moters time.sleep(sleep) moters = False #stop the moters print("moved",distance) def backward(self, distance): #might not need this. we could use a negative number in the move.forward() function print("Backwards class") print("moving",distance) sleep = distance / 2.2 #convert the distance into time s = d / t (number=filler) if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep moters = True #power the moters in reverse time.sleep(sleep) moters = False #stop the moters print("moved",distance) def right(self, angle): print("right class") print("turning", angle, "clockwise") sleep = angle / 2.2 #convert the angle into time using, s = d / t (filler number) if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep left_moters = True #rurns right right_moters = False time.sleep(sleep) left_moters = False #stop the moters right_moters = False print("turned",angle , "clockwise") def left(self, angle): print("left class") print("turning", angle, "counterclockwise") sleep = angle / 2.2 #convert the angle into time using, s = d / t(numberr=filler) if sleep < 0: #time.sleep doent work with negative numbers so this make the numbers positive sleep = 0 - sleep left_moters = False #turns left right_moters = True time.sleep(sleep) left_moters = False #stop the moters right_moters = False print("turned",angle , "counterclockwise") class sensor(): """ docstring for Sensors. """ def camara(self, arg): pass move = move() test = 6 move.forward(test) move.right(test) #move.forward(input())
true
3b05334d87578f06dbdae53128873bf77f512ef4
ccbrantley/Python_3.30
/Decision Structures and Boolean Logic/Brantley_U3_14.py
645
4.21875
4
weight = 0 height = 0 print('This progam will calculatey your BMI(Body Mass Index).') weight = int(input('Please enter in your weight using a measurement of pounds.')) height = int(input('Please enter in your height using a measurement of inches.')) BMI = weight * 703/height**2 if 18.5 <= BMI <= 25: print('Your BMI is ', format(BMI, ',.2f'), ' and is classified as optimal.', sep='') elif BMI > 25: print('Your BMI is ', format(BMI, ',.2f'), ' and is classified as overweight.', sep='') elif BMI < 18.5: print('Your BMI is ', format(BMI, ',.2f'), ' and is classified as underweight.', sep='') else: print('NULL')
true
5f5b691d7740a9bb38c7a28cbda880cc6ed2aed6
ccbrantley/Python_3.30
/Repetition Structure/Brantley_U4_8.py
285
4.375
4
number = 0 number_sum = 0 print('Enter positive numbers to sum them together and enter a negative number to stop.') while number >= 0: number = float(input('Enter number: ')) if number >= 0: number_sum += number print('The sum is:', format(number_sum, ',.2f'))
true
449f7ce26696cd4804d5e7796a5d724d9b9c34b8
ashishaaron346/MONTHLY_TASKS_PROJECT
/March_2019_Task2/Beginner_Python_Projects_2/proj13DiceRoll.py
1,520
4.125
4
#!/usr/bin/env python3 # proj13DiceRoll.py - r/BeginnerProjects #13 # https://www.reddit.com/r/beginnerprojects/comments/1j50e7/project_dice_rolling_simulator/ import random, time # Loop until keyboard interrupt while True: try: # Prompt until a positive integer is input for num of sides while True: try: sides = int(input("How many sides does the die have?")) except ValueError: print("I need an integer!") continue if not sides > 0: print("I need a positive integer!") else: break # Prompt until a positive integer is input for num of rolls while True: try: rolls = int(input("How many times should it be rolled?")) except ValueError: print("I need an integer!") continue if not rolls > 0: print("I need a positive integer!") else: break # Initialize variables results = [] resultsDict = {} # Random rolls for i in range(rolls): results.append(random.randint(1, sides)) # Count appearance of each side of the die for i in results: if i in resultsDict: resultsDict[i] += 1 else: resultsDict.setdefault(i, 1) # Print results and their percentages for k in resultsDict: print(str(k) + " appeared " + str(resultsDict[k]) + " times, or " + str(round(resultsDict[k]/rolls*100, 2)) + "% of the time.") # Pause, allowing time for keyboard interrupt, then begin again time.sleep(3) print("\nLet's go again!\n") # Break out of program except KeyboardInterrupt: print("This was fun.") break
true
72a2dea947e7c91504ad5fa81a035c5c34454128
ashishaaron346/MONTHLY_TASKS_PROJECT
/March_2019_Task1/Beginner_Python_Projects_1/proj02Magic8Ball.py
1,135
4.15625
4
#!/usr/bin/env python3 # proj02Magic8Ball.py - r/BeginnerProjects #2 # https://www.reddit.com/r/beginnerprojects/comments/29aqox/project_magic_8_ball/ import time, random responses = ["Nah.", "Get out of here.", "Could be, who knows man.", "Yes", "Technically your odds aren't zero, but realistically...", "Maybe.", "You're wasting everyone's time, ask me a real question.", "Totally", "I'm optimistic", "The future is cloudy"] # Takes a question from user and, after a pause, returns a random response def mainevent(): # "Takes" a question from user but doesn't do anything with it input("Ask me a question") # Tells user it is thinking, waits for 3 seconds print("Let me think about that...") time.sleep(3) # Prints a random response from list above result = responses[random.randint(0,len(responses)-1)] print(result) # Loop until user opts to quit program while True: # Run 8 ball function mainevent() # Pause while user reads the 8 ball response time.sleep(3) # Give user the option to continue or quit prompt = input("Press anything to go again or enter QUIT\n") if prompt == "QUIT": break
true
04bb9b3d91d0f91b5c9f8b66a9ff301af2983553
daorejuela1/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
2,165
4.15625
4
#!/usr/bin/python3 """linked list docstrings. This module demonstrates how to use a linked list with classes. """ class Node(): """This class defines a memory space""" def __init__(self, data, next_node=None): """ corroboares data is int and next node is valid""" if type(data) is not int: raise TypeError("data must be an integer") self.__data = data if type(next_node) is not Node and next_node is not None: raise TypeError("next_node must be a Node object") self.__next_node = next_node @property def data(self): """get data value""" return self.__data @property def next_node(self): """get next node value""" return self.__next_node @next_node.setter def next_node(self, value): """set next node value""" if type(value) is not Node and value is not None: raise TypeError("next_node must be a Node object") self.__next_node = value class SinglyLinkedList(Node): """defines a single linked list structure""" def __init__(self): """head initialization""" self.__head = None def __str__(self): """in case of printing""" final_str = "" while(self.__head is not None): final_str += str(self.__head.data) if (self.__head.next_node is not None): final_str += "\n" self.__head = self.__head.next_node return(final_str) def sorted_insert(self, value): """insert the node in order""" if (self.__head is None): self.__head = Node(value) return if (value <= self.__head.data): self.__head = Node(value, self.__head) return origin = self.__head while (self.__head.next_node is not None): if (self.__head.next_node.data > value): self.__head.next_node = Node(value, self.__head.next_node) self.__head = origin return self.__head = self.__head.next_node self.__head.next_node = Node(value) self.__head = origin
true
99b2b7fa1180a5ed800908c4e3e925d19c1f502e
xx-m-h-u-xx/Scientific-Computing-with-AI-TensorFlow-Keras
/GuessNumber.py
562
4.125
4
# Guess the number game. # GuessNumber.py import random num_guesses = 0 user_name = input("Hi: What is your name? ") number = random.randint(1,20) print("Welcome, {}! Guess number between 1 and 20.".format(user_name)) while num_guesses < 6: guess = int(input("Take a guess?")) num_guesses += 1 if guess < number: print("Number too low") if guess > number: print("Number too high") if guess == number: break if guess == number: print("Woopee!") else: print("Loser!!!")
true
e666d86c38fda89d2434f80db29c44a386020118
fanzou2020/Parsing
/driver.py
1,106
4.25
4
import parser import truth_table inputStr = input('Please enter the proposition:\n') result = parser.parse(inputStr) variables = result["variables"] case = input('1. Given the truth value of variables.\n2. Generate truth table\n') if case == '1': print("The variables are: ", end='') print(variables) s = input('please input the truth value of variables, using "true", "false", "T", or "F"\n') variableTokens = s.split(" ") # print(variableTokens) assignment = [] for x in variableTokens: if x == 'true' or x == 'T': assignment.append(True) elif x == 'false' or x == 'F': assignment.append(False) print(assignment) ast = result["ast"].evaluate(assignment) print("The Value of this proposition is: ", end='') print(ast) elif case == '2': print("The truth table of " + '"' + inputStr + '"') truth_table.generateTruthTable(result) # variables = result["variables"] # # print(ast) # print(variables) # # print() # # print("The truth table of " + '"' + inputStr + '"') # truth_table.generateTruthTable(result)
true
ab534206a4e2293ccf0d1d774aa6d698ddabc870
andersonLoyola/python-repo
/book/exerciseOne.py
634
4.25
4
# Write a program that asks the user to enter a integer and prints two integers, root and pwr, such that 0 < pwr < 6 amd root**pwr is equals to the integer entered by the user number = int(input("Write some number: ")) auxNumber = 1 found = False while auxNumber < number and found == False: auxPower=0 while auxNumber**auxPower <= number and auxPower < number and found == False: if auxNumber**auxPower == number: found = True else: auxPower+=1 print(auxNumber, "-", auxPower) if(not found): auxNumber+=1 if found == True: print("number", auxNumber, "power", auxPower) else: print("not found")
true
6f1f06ca37ee63633a8b568afd7c15571a019222
marjorienorm/learning_python
/words.py
1,414
4.21875
4
"""Retrieve and print words for a url. usage: python words.py <URL> """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words form a url. Args: url: The URL of a UTF-8 text document. Returns: A list of strings containing the words from the document. """ story = urlopen(url) story_words = [] for line in story: #line_words = line.split() line_words = line.decode('utf8').split() for word in line_words: story_words.append( word ) story.close() return story_words def print_items( items ): """Print items oer line from a list of items. Args: items: An iterable series of printable items. Returns: Nothing is returned from this function. """ for item in items: print( item ) def main(url = None): """Print each word from a text document from a URL. Args: url: The URL of a UTF-8 text document. Returns: Nothing is returned from this function. """ if url is None: url = "http://sixty-north.com/c/t.txt" words = fetch_words(url) print_items( words ) #def main(): # words = fetch_words( "http://sixty-north.com/c/t.txt" ) # print_items( words ) if __name__ == '__main__': if len(sys.argv) > 1: main( sys.argv[1] ) else: main()
true
01a55d99f9fbf4b98ec18322393f396480d59f34
Saberg118/CS100
/Tuition_calculator.py
397
4.125
4
# This program will display the projected semester tuition for the next 5 # years if tuition increases by 3% # Initialize tuition = 8000 # Make a table print('Years \t\t Tuition') print('___________________________') #for loop for year in range(1,6): # Calculate tuition tuition *= 1.03 # Display table print(format(year, '.2f'),'\t\t',format(tuition,'.2f'))
true
404845e4a4a0225a1c712014a3a2730f378e287e
Saberg118/CS100
/budget_calculator_using for loop.py
1,082
4.28125
4
# This program keeps the running total of the expenses of the user # and it will give the feedback wither or not the user stayed on # their proposed budget or if they were over or under it. total = 0.0 # initialize the accumulator # Get the budget amount from the user budget = float(input('Enter your budget for the month. ')) number = int(input('How may expenses do you have?')) # Get the total amount of expenses from the user for expense in range(number): expense = float(input("""Enter how much you have spent""")) # Added to the total total += expense # determine wither he is under or over or at their budget # and display the result print('Budget: $', format(budget,".2f")) print('Expense: $', format(total,".2f")) if budget > total: difference = budget - total print('You are $', format(difference, ".2f"),\ 'under your budget') elif budget < total: difference = total - budget print('You are $', format(difference, ".2f"),\ 'over your budget') else: print('You have stayed on budget')
true
71b3cd139efaa07ca2bd48ed3e81ffbafb2af00b
Saberg118/CS100
/classroom_percentage.py
858
4.1875
4
# This program calculate the percentage of males and females # in a given class. # Get the number of girl in the class. girls = int(input('How many females are in the class? ')) # Get the number of boys in the class. boys = int(input('How many males are in the class? ')) # Calculate the number of students in the class students = boys + girls # Calculate the percentage of girls in the class. percentage_of_girls = (girls / students) * 100 # Calculate the percentage of boys in the class. percentage_of_boys = (boys / students) * 100 # Display the percentage of females in the class print('The percentage or females in the class is', \ format(percentage_of_girls, '.2f'),'%') # Display the percentage of males in the class print('The percentage or males in the class is', \ format(percentage_of_boys, '.2f'),'%')
true
6e11cba06075706d9d8eae9678aaafe941fdb039
cifpfbmoll/practica-3-python-AlfonsLorente
/src/Ex7.py
1,336
4.46875
4
#!/usr/bin/env python3 #encoding: windows-1252 #Pida al usuario tres nmero que sern el da, mes y ao. Comprueba que la fecha introducida es vlida. Por ejemplo: #32/01/2017->Fecha incorrecta #29/02/2017->Fecha incorrecta #30/09/2017->Fecha correcta. import sys if __name__ == "__main__": #declare the variables day = int(input("Insert the day: ")) month = int(input("Insert the month: ")) year = int(input("Insert the year: ")) #if days are greater than 31 in the 31-days month, show incorrect if day > 31 and (month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12): print(day, '/', month, '/', year, "-> incorrect date") #if days are greater than 30 in the 30-days month, show incorrect elif day > 30 and (month == 4 or month == 6 or month == 9 or month == 11): print(day, '/', month, '/', year, "-> incorrect date") #if the days are greater than 28 in february elif day > 28 and month == 2: print(day, '/', month, '/', year, "-> incorrect date") #Other errors that could happen elif(day < 0 or month < 1 or month > 12): print(day, '/', month, '/', year, "-> incorrect date") #the date is correct, print is correct else: print(day, '/', month, '/', year, "-> correct date")
true
68436256894092a0eae4cb852624edd04e53baa5
avholloway/100DaysOfCode
/day9.py
2,573
4.28125
4
programming_dictionary = { "Bug": "An error in a program that prevents the program from running as expected.", "Function": "A piece of code that you can easily call over and over again." } # 9.1 - grading # ----------------------------------------------------------- def one(): student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 #TODO-1: Create an empty dictionary called student_grades. student_grades = {} #TODO-2: Write your code below to add the grades to student_grades.👇 for student in student_scores: score = student_scores[student] if score <= 70: grade = "Fail" elif score <= 80: grade = "Acceptable" elif score <= 90: grade = "Exceeds Expectations" else: grade = "Outstanding" student_grades[student] = grade # 🚨 Don't change the code below 👇 print(student_grades) # 9.2 - travel log # ----------------------------------------------------------- def two(): travel_log = [ { "country": "France", "visits": 12, "cities": ["Paris", "Lille", "Dijon"] }, { "country": "Germany", "visits": 5, "cities": ["Berlin", "Hamburg", "Stuttgart"] }, ] #🚨 Do NOT change the code above #TODO: Write the function that will allow new countries #to be added to the travel_log. 👇 def add_new_country(country, visits, cities): travel_log.append({ "country": country, "visits": visits, "cities": cities }) #🚨 Do not change the code below add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"]) print(travel_log) # final - auction # ----------------------------------------------------------- from replit import clear from auctionart import logo #HINT: You can call clear() to clear the output in the console. print(logo) print("Welcome to the secret auction program!") print() bids = {} def collect_bidder_info(): name = input("Name: ") bid = int(input("Bid: $")) bids[name] = bid collect_bidder_info() while input("Another (yes/no): ") == "yes": clear() collect_bidder_info() winning = { "name": "no one", "bid": 0 } for name in bids: this_bid = bids[name] if this_bid > winning["bid"]: winning["name"] = name winning["bid"] = this_bid clear() print(f"The winner is {winning['name']} with a bid of {winning['bid']}")
true
794fb4af68bf0683eab6ce717a4de1cf955f007b
russunazar/-.-1-
/number 3.py
459
4.21875
4
x = float(input("перша цифра: ")) y = float(input("друга цифра: ")) operation = input("Operation: ") result = None if operation == "+": result = x + y if operation == "-": result = x - y if operation == "*": result = x * y if operation == "/": result = x / y else: print("unsupported operation") if result is not None: print("Result: ", result)
true
8e4f94063b10e42d4877fcf11afaaccc00217437
itsmehaanh/nguyenhaanh-c4e34
/Session4/homework/bai4.py
987
4.25
4
print ('''If x = 8, then what is 4(x+3)? 1. 35 2.36 3.40 4.44''') question = { "If x = 8, then what is 4(x+3)?" : { "1" : 35, "2" : 36, "3" : 40, "4" : 44,} } answer = input("Your code:") if answer == "3": print("Bingo!") else: print(":(") print('''Estimate this answer (exact calculation not needed): Jack scored these marks in 5 math tests: 49, 81, 72, 66 and 52. What is the mean? 1. About 55 2. About 65 3. About 75 4. About 85''' ) question2 = { "Estimate this answer (exact calculation not needed)": { "1":"About 55", "2": "About 65", "3": "About 75", "4": "About 85",} } answer_2 = input("Your code:") if answer_2 == "2": print("Bingo!") else: print(":(") if answer == "3" and answer_2 == "2": print("You correctly answer both questions") elif answer != "3" and answer_2 != "2": print("You got both answers incorrect") else: print("You correctly answer 1 out of 2 questions")
true
5df4cabafe46b6606f8712dcd94f62a9bd08c680
hakim-DJZ/HF-Python
/Chapter2/nester/hakim_nester.py
688
4.5
4
"""Example module from chapter 2, Head First Python. The module allows you to print nested lists, by use of recursion. It's named the nester.py module, which provides the print_lol() frunction to print nested lists.""" def print_lol(the_list, indent = False, level=0): """For each item, check if it's a list; if so, keeping calling myself until not a list, then print to standard output""" for each_item in the_list: if isinstance(each_item,list): print_lol(each_item, indent, level+1) else: if indent != False: for tab_stop in range(level): print("\t", end ='') print(each_item)
true
b68dbecaada6712ac96438e48a88e462196ceee8
in-tandem/matplotlib_leaning
/simple_graph.py
484
4.125
4
## i am going to plot using simple lists of data ## i am going to label x and y axis ## i am going to add color ## i am adding title to the graph import matplotlib.pyplot as plot print('i am going to draw a simple graph') x_axis = [10, 20, 30, 40, 66, 89] y_axis = [2.2, 1.1, 0, 3, -9, 99] plot.plot(x_axis,y_axis, color="blue") plot.xlabel("Number of Routers") plot.ylabel("Distances from Master Router( -ve means inner circle) ") plot.title("some graph silly silly") plot.show()
true
b59d922c989315e331dc682a37a9d48f8bd41ef0
odeyale2016/Pirple_assignment
/card2.py
1,038
4.1875
4
from random import randint, choice def jack_chooses_a_card(suits: dict): """ Program for Card Game """ print(str(randint(1,13)) + " of " + str(choice(suits))) def check_help(): # Instructions for the help multiline_str = """Welcome to Pick a Card Game. To play the game, follow the instruction below. 1. Enter your name at the begining of the program. 2. press Enter to continue... 3. Pick a Card.""" print("Game Instruction: \n" + multiline_str) if __name__ == "__main__": suits = ["Spades", "Hearts", "Diamonds", "Clubs"] player_name= input(str("Enter your name: " )) print("It's "+player_name+"'s turn") print("Just press [ENTER] to get started") user_input = input("") if(user_input == '--help'): check_help() print("Just type [--resume] to Resume the Game") while user_input == "": jack_chooses_a_card(suits) user_input = input("\nTo run again press [ENTER] key, entering anything else would terminate the program\n")
true
801d9ab6b31011ff1783ec489e3d150c5c79f44a
rlowrance/re-local-linear
/x.py
2,216
4.15625
4
'''examples for numpy and pandas''' import numpy as np import pandas as pd # 1D numpy arrays v = np.array([1, 2, 3], dtype=np.float64) # also: np.int64 v.shape # tuple of array dimensions v.ndim # number of dimensions v.size # number of elements for elem in np.nditer(v): # read-only iteration pass for elem in np.nditer(v, op_flags='readwrite'): # mutation iteration elem[...] = abs(elem) # elipses is required for elems in np.nditer(v, flags=['external_loop']): # iterate i chunks print elems # elems is a 1D vector # basic indexing (using a slice or integer) ALWAYS generates a view v[0:v.size:1] # start:stop:step v[10] v[...] # advanced indexing (using an ndarray) ALWAYS generates a copy # advanced indexes are always broadcast v[np.array([1, 2])] # return new 1D with 2 elements v[~np.isnan(v)] # return new 1D with v.size elements # pd.Index # data: aray-like 1D of hashable items # dtype: np.dtype # copy: bool default ? # name: obj, documentation # tupleize_cols: bool, default True; if True, attempt to create MultiIndex i = pd.Index(data, dtype, copy, name, tupleize_cols) i.shape i.ndim i.size i.values # underlying data as ndarray # generally don't apply methods directly to Index objects # pd.Series # data: array-like, dict, scalar # index: array-like, index # dtype: numpy.dtype # copy: default False (True forces a copy of data) s = pd.Series(data, index, dtype, name, copy) s.values # return ndarray s.shape s.ndim s.size # indexing and iteration s.get(key[,default]) # key: label s.loc[key] # key: single label, list or array of labels, slice with labels, bool array s.iloc[key] # key: int, list or array of int, slice with ints, boolean array s.iteritems() # iterate over (index, value) pairs # pd.DataFrame: # data: numpy ndarray, dict, DataFrame # index: index or array-like # columns: index or array-like # dtype: nparray dtype # copy: boolean default False df = pd.DataFrame(data, index, columns, dtype, copy) df.shape df.ndim df.size df.as_matrix([columns]) # convert to numpy array df.loc[key] # key: single lable, list or array of labels, slice of labels, bool array df.iloc[key] # key: int, list or array of int, slice of int, bool array
true
758aea129a19502aeacd16c4a89319a1da897513
jemg2030/Retos-Python-CheckIO
/HOME/EvenTheLast.py
2,110
4.125
4
''' You are given an array of integers. You should find the sum of the integers with even indexes (0th, 2nd, 4th...). Then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be 0 (zero). Input: A list of integers. Output: The number as an integer. Example: assert checkio([0, 1, 2, 3, 4, 5]) == 30 assert checkio([1, 3, 5]) == 30 assert checkio([6]) == 36 assert checkio([]) == 0 How it is used: Indexes and slices are important elements of coding. This will come in handy down the road! Precondition: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) --------- --------- Se te da un arreglo de enteros. Deberías encontrar la suma de los elementos con índices pares (0, 2do, 4to... ) luego multiplicar ese resultado con el elmento final del arreglo. No olvides que el primer elemento tiene el índice 0. Para un arreglo vacio, el resultado siempre será 0 (cero). Entrada: Una lista de enteros. Salida: El número como un entero. Ejemplo: assert checkio([0, 1, 2, 3, 4, 5]) == 30 assert checkio([1, 3, 5]) == 30 assert checkio([6]) == 36 assert checkio([]) == 0 Cómo se usa: Índices y fragmentos son elementos importantes de la programación en python y otros lenguajes. Esto se volverá útil en el camino más adelante! Precondición: 0 ≤ len(array) ≤ 20 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ''' def checkio(array: list[int]) -> int: # your code here if not array: return 0 even_index_sum = sum(array[i] for i in range(0, len(array), 2)) return even_index_sum * array[-1] # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': print("Example:") print(checkio([0, 1, 2, 3, 4, 5])) assert checkio([0, 1, 2, 3, 4, 5]) == 30 assert checkio([1, 3, 5]) == 30 assert checkio([6]) == 36 assert checkio([]) == 0 print("The mission is done! Click 'Check Solution' to earn rewards!")
true
2614ae144faef13ad3271bf311531cbd671b395e
jemg2030/Retos-Python-CheckIO
/SCIENTIFIC_EXPEDITION/AbsoluteSorting.py
2,639
4.78125
5
''' Let's try some sorting. Here is an array with the specific rules. The array (a list) has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list or tuple. Precondition: The numbers in the array are unique by their absolute values. Input: An array of numbers , a tuple.. Output: The list or tuple (but not a generator) sorted by absolute values in ascending order. Addition: The results of your function will be shown as a list in the tests explanation panel. Example: assert checkio([-20, -5, 10, 15]) == [-5, 10, 15, -20] assert checkio([1, 2, 3, 0]) == [0, 1, 2, 3] assert checkio([-1, -2, -3, 0]) == [0, -1, -2, -3] How it is used: Sorting is a part of many tasks, so it will be useful to know how to use it. Precondition: len(set(abs(x) for x in array)) == len(array) 0 < len(array) < 100 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ---------- ---------- Vamos a experimentar con ordenamiento (clasificación). Aquí hay una matriz con normas específicas. El vector (una list) tiene varios números. Debes ordenarla por valor absoluto en orden ascendente. Por ejemplo, la secuencia (-20, -5, 10, 15), queda ordenada de la siguiente forma: (-5, 10, 15, -20). Tu función debe devolver la lista (o tupla) ordenada. Condiciones: Los números de la matriz son únicos por sus valores absolutos. Datos de Entrada: Un conjunto de números, una tupla. Salida: La lista o tupla (pero no un generador) ordenados por valores absolutos en orden ascendente. Adicional: Los resultados de tu función serán presentados como una lista en panel de explicación de pruebas. Ejemplo: assert checkio([-20, -5, 10, 15]) == [-5, 10, 15, -20] assert checkio([1, 2, 3, 0]) == [0, 1, 2, 3] assert checkio([-1, -2, -3, 0]) == [0, -1, -2, -3] ¿Cómo se usa?: La clasificación /ordenamiento es una parte de muchas tareas, por lo que es bastante útil saber cómo se usa. Condiciones: len(set(abs(x) for x in array)) == len(array) 0 < len(array) < 100 all(isinstance(x, int) for x in array) all(-100 < x < 100 for x in array) ''' def checkio(values: list) -> list: # your code here return sorted(values, key=abs) print("Example:") print(checkio([-20, -5, 10, 15])) # These "asserts" are used for self-checking assert checkio([-20, -5, 10, 15]) == [-5, 10, 15, -20] assert checkio([1, 2, 3, 0]) == [0, 1, 2, 3] assert checkio([-1, -2, -3, 0]) == [0, -1, -2, -3] print("The mission is done! Click 'Check Solution' to earn rewards!")
true
5f47280efff7921b548de8f213f7e6a07b4138b1
jemg2030/Retos-Python-CheckIO
/HOME/BiggerPrice.py
2,824
4.40625
4
''' You have a list with all available products in a store. The data is represented as a list of dicts Your mission here is to find the most expensive products in the list. The number of products we are looking for will be given as the first argument and the list of all products as the second argument. Input: int and list of dicts. Each dict has the two keys "name" and "price" Output: The same format as the second input argument. Example: assert bigger_price( 2, [ {"name": "bread", "price": 100}, {"name": "wine", "price": 138}, {"name": "meat", "price": 15}, {"name": "water", "price": 1}, ], ) == [{"name": "wine", "price": 138}, {"name": "bread", "price": 100}] assert bigger_price( 1, [{"name": "pen", "price": 5}, {"name": "whiteboard", "price": 170}] ) == [{"name": "whiteboard", "price": 170}] ---------- ---------- Se tiene una lista con todos los productos disponibles en una tienda. Los datos se representan como una lista de dicts Tu misión aquí es encontrar los productos más caros de la lista. El número de productos que buscamos se dará como primer argumento y la lista de todos los productos como segundo argumento. Entrada: int y lista de dicts. Cada dict tiene las dos claves "nombre" y "precio" Salida: El mismo formato que el segundo argumento de entrada. Ejemplo: assert mayor_precio( 2, [ {"nombre": "pan", "precio": 100}, {"nombre": "vino", "precio": 138}, {"nombre": "carne", "precio": 15}, {"nombre": "agua", "precio": 1}, ], ) == [{"nombre": "vino", "precio": 138}, {"nombre": "pan", "precio": 100}] assert mayor_precio( 1, [{"nombre": "bolígrafo", "precio": 5}, {"nombre": "pizarra", "precio": 170}] ) == [{"nombre": "pizarra", "precio": 170}] Traducción realizada con la versión gratuita del traductor www.DeepL.com/Translator ''' def bigger_price(limit: int, data: list[dict]) -> list[dict]: """ TOP most expensive goods """ # your code here return sorted(data, key=lambda x: x['price'], reverse=True)[:limit] print("Example:") print( bigger_price( 2, [ {"name": "bread", "price": 100}, {"name": "wine", "price": 138}, {"name": "meat", "price": 15}, {"name": "water", "price": 1}, ], ) ) assert bigger_price( 2, [ {"name": "bread", "price": 100}, {"name": "wine", "price": 138}, {"name": "meat", "price": 15}, {"name": "water", "price": 1}, ], ) == [{"name": "wine", "price": 138}, {"name": "bread", "price": 100}] assert bigger_price( 1, [{"name": "pen", "price": 5}, {"name": "whiteboard", "price": 170}] ) == [{"name": "whiteboard", "price": 170}] print("The mission is done! Click 'Check Solution' to earn rewards!")
true
483f162dabdd2310a400cadb2abc8ad26faeac62
Chi10ya/UDEMY_SeleniumWithPython
/Sec8_ClassesObjectOrientedPrg.py
2,934
4.8125
5
""" 8: Classes - Object Oriented Programming 45: Understanding objects / classes 46: Create your own object 47: Create your own methods 48: Inheritance 49: Method Overriding 50: Practice exercise with solution """ # 45: Understanding objects / classes # 46: Create your own object class myClass(object): # Inherting the inbuilt object class def __init__(self, make): # __init__ method is used to initialize all the objects which are created to the specific class self.make = make print(self.make) def myName(self, name): print(name) def myCountry(self, countryName): print(countryName) mc = myClass("Puegot") mc.myName("Chaitanya Ambica Yashvir Dhiyanshi") mc.myCountry("IRELAND") # 47: Create your own methods class Car(object): wheels = 4 def __init__(self, make, model): self.make = make self.model = model def info(self): print("Make of the car : "+self.make) print("Model of the car : "+self.model) c1 = Car('Puegot', '880') print(c1.make) print(c1.model) print(Car.wheels) print(c1.wheels) # 48: Inheritance class Cars(object): def __init__(self): print("You just created the car instance") def drive(self): print("Car started") def stop(self): print("Car stopped") class BMW(Cars): def __init__(self): Cars.__init__(self) print("You just create the BMW instance") def headsUpFeature(self): print("Having an headsp feature") c2 = Cars() c2.drive() c2.stop() b1 = BMW() b1.drive() b1.stop() b1.headsUpFeature() # 49: Method Overriding class MyCars(object): print('$'*50) def __init__(self): print("You just created the car instance. It is MyCars class and in __init__") def start(self): print("Car started.... in MyCars class") def stop(self): print("Car stopped.... in MyCars class") class BMW(MyCars): def __init__(self): print("You just create the BMW instance. It is BMW class and in __init__") MyCars.__init__(self) def headsUpFeature(self): print("Having an headsup feature.. in BMW class") def start(self): super().start() print("Hi..Chaitanya, Welcome.. Today you are driving BMW car. It is in BMW class") super().stop() c2 = MyCars() c2.start() c2.stop() b1 = BMW() b1.start() b1.stop() b1.headsUpFeature() b1.start() # 50: Practice exercise with solution #************************************************* # My Practice of Classes & Objects class empInfo(object): def set_emp_details(self, empno, ename): self.empNo = empno self.empName = ename def get_emp_details(self): return self.empNo, self.empName objEmp = empInfo() objEmp.set_emp_details(7224, "Chaitanya") empNo, empName = objEmp.get_emp_details() print("Employee Number : "+str(empNo)) print("Employee Name : "+empName)
true
4bf52edd8b443fde14901d5522921ac8f599679f
stanisbilly/misc_coding_challenges
/decompress.py
1,981
4.1875
4
''' Decompress a compressed string, formatted as <number>[<string>]. The decompressed string should be <string> written <number> times. Example input: 3[abc]4[ab]c Example output: abcabcabcababababc Number can have more than one digit. For example, 10[a] is allowed, and just means aaaaaaaaaa One repetition can occur inside another. For example, 2[3[a]b] decompresses into aaabaaab Characters allowed as input include digits, small English letters and brackets [ ]. Digits are only to represent amount of repetitions. Letters are just letters. Brackets are only part of syntax of writing repeated substring. Input is always valid, so no need to check its validity. source: https://techdevguide.withgoogle.com/resources/compress-decompression/ ''' import re pattern = r'\d+\[[a-zA-Z]*\]' pattern_with_group = r'(\d+)\[([a-zA-Z]*)\]' # same as above, but grouped def repeatstr(strin): m = re.match(pattern_with_group, strin) return int(m.groups()[0]) * m.groups()[1] def decompress(strin): matches = re.findall(pattern, strin) while len(matches) > 0: for m in matches: strin = re.sub(m.replace('[','\\[').replace(']','\\]'), repeatstr(m), strin, 1) matches = re.findall(pattern, strin) return strin def run_tests(): tests = [ ('abc', 'abc'), ('3[a]', 'aaa'), ('a3[b]', 'abbb'), ('xyz3[]2[b]', 'xyzbb'), ('3[a]2[b]1[c]0[d]', 'aaabbc'), ('xyz3[a]2[b]1[c]', 'xyzaaabbc'), ('xyz3[a]2[b]zzz', 'xyzaaabbzzz'), ('3[2[a]c]', 'aacaacaac'), ('3[2[a]2[b]c]', 'aabbcaabbcaabbc'), ('z3[2[a]c]z', 'zaacaacaacz'), ('1[1[1[1[1[a]]]]]', 'a'), ('x1[1[1[1[1[a]]]]2[b]]x', 'xabbx'), ('a100[50[]]2[bxyz]10000[]c', 'abxyzbxyzc'), ('10[a]0[b]100[c]', 10*'a'+ 0*'b' + 100*'c') ] for t in tests: td = decompress(t[0]) print(td == t[1], ',', t[0],'-->', td) if __name__ == '__main__': run_tests()
true
b26f56ad13ac9c603fe51fe969c4ee54b81b4687
bermec/challenges
/challenges_complete/challenge182_easydev10.py
2,146
4.4375
4
''' (Easy): The Column Conundrum Text formatting is big business. Every day we read information in one of several formats. Scientific publications often have their text split into two columns, like this. Websites are often bearing one major column and a sidebar column, such as Reddit itself. Newspapers very often have three to five columns. You've been commisioned by some bloke you met in Asda to write a program which, given some input text and some numbers, will split the data into the appropriate number of columns. Formal Inputs and Outputs Input Description To start, you will be given 3 numbers on one line: <number of columns> <column width> <space width> number of columns: The number of columns to collect the text into. column width: The width, in characters, of each column. space width: The width, in spaces, of the space between each column. After that first line, the rest of the input will be the text to format. Output Description You will print the text formatted into the appropriate style. You do not need to account for words and spaces. If you wish, cut a word into two, so as to keep the column width constant. Sample Inputs and Outputs Sample Input Input file is available here. (NB: I promise this input actually works this time, haha.) Sample Output Outout, according to my solution, is available here. I completed the Extension challenge too - you do not have to account for longer words if you don't want to, or don't know how. ''' if __name__ == "__main__": import re format_style = [4, 25, 1] lst = [] with open('loren_ipsum.txt', 'r') as f: for line in f: line = line.rstrip() lst.append(line) lsts = re.findall('.{25}', lst[0]) #print(lsts) x = 0 y = x while y < 10: temp = lsts[x] print('{0}{1:<26}'.format(x, lsts[x]), end='') x += 10 print('{0}{1:<26}'.format(x, lsts[x]), end='') x += 10 print('{0}{1:<26}'.format(x, lsts[x]), end='') x += 10 print('{0}{1:<26}'.format(x, lsts[x]), end='') print('\n') y += 1 x = y
true
bbc20d6705ef01287e574deca25e2e6c1497b87e
bermec/challenges
/challenge75_easy.py
2,182
4.125
4
''' Everyone on this subreddit is probably somewhat familiar with the C programming language. Today, all of our challenges are C themed! Don't worry, that doesn't mean that you have to solve the challenge in C, you can use whatever language you want. You are going to write a home-work helper tool for high-school students who are learning C for the first time. These students are in the advanced placement math course, but do not know anything about programming or formal languages of any kind. However, they do know about functions and variables! They have been given an 'input guide' that tells them to write simple pure mathematical functions like they are used to from their homework with a simple subset grammar, like this: f(x)=x*x big(x,y)=sqrt(x+y)*10 They are allowed to use sqrt,abs,sin,cos,tan,exp,log, and the mathematical arithmetic operators +*/-, they can name their functions and variables any lower-case alphanumeric name and functions can have between 0 and 15 arguments. In the this challenge, your job is to write a program that can take in their "simple format" mathematical function and output the correct C syntax for that function. All arguments should be single precision, and all functions will only return one float. As an example, the input L0(x,y)=abs(x)+abs(y) should output float L0(float x,float y) { return fabsf(x)+fabsf(y); } Bonus points if you support exponentiation with "^", as in "f(x)=x^2" ''' import re def math_to_c(inpstr): (f, body) = inpstr.split('=') for op in ['exp', 'log','sqrt','abs','sin','cos','tan']: body = body.replace(op, op+"f") body = body.replace("absf", "fabsf") for m in re.compile(".*(([\w+])\^([\d+])).*").finditer(body): body = body.replace(m.group(1), "expf(" + m.group(2) + "," + m.group(3) + ")") (name, args) = f.split('(') sig = name + "(" argsplit = args.strip().split(',') for i in range(len(argsplit)): sig += "float " + argsplit[i] if i != len(argsplit) - 1: sig += ", " return "float " + sig + " {\n return " + body + ";\n}" if __name__ == "__main__": print(math_to_c("L0(x,y)=abs(x)+abs(y)+x^2"))
true
f11d708155799e063007143742985ddc376c4d01
AvneetHD/little_projects
/Time Converter.py
524
4.28125
4
def minutes_to_seconds(x): x = int(x) x = x * 60 print('{} seconds.'.format(x)) def hours_to_seconds(x): x = int(x) x = (x * 60) * 60 print('{} seconds'.format(x)) direction = input('Do you want to convert hours to seconds. Y/N.') direction2 = input('Do you want to convert minutes to seconds. Y/N.') if direction == 'Y' or direction == 'yes': hours = input('') hours_to_seconds(hours) if direction2 == 'Y' or direction == 'yes': minutes = input('') minutes_to_seconds(minutes)
true
7c7c402f239d4aa58c9f0359fc9e0150d6dd49cd
melbinmathew425/Core_Python
/advpython/oop/quantifiers/rule5.py
213
4.15625
4
import re x="a{1,3}"#its print the group or individualy, when its no of 'a' is in between {1,3} r="aaa abc aaaa cga" matcher=re.finditer(x,r) for match in matcher: print(match.start()) print(match.group())
true
89f0c05070f4b6f6fe4485376461e8b309289a4c
Turjo7/Python-Revision
/car_game.py
688
4.15625
4
command = "" started = False # while command != "quit": while True: command = input("> ").lower() if command == "start": if started: print("The Car Already Started: ") else: started = True print("The Car Started") elif command == "stop": if not started: print("The Car Already Stoped: ") else: started= False print("The Car Stopped") elif command == "help": print(f''' start- to start the car stop- to stop the car help- to see help ''') elif command == "quit": break else: print("Can not understand: ")
true
30cd1ebf47edc12c42c6383e4d84c35326dee8fd
sdmgill/python
/Learning/range_into_list.py
312
4.21875
4
#putting a range into a list print("Here is my range placed into a list:") numbers = list(range(1,6)) print(numbers) #putting a range into a list and grab only even numbers print("\nHere is my even list / range:") even_numbers=list(range(2,11,2)) #start with 2, go to 11(10), increment by 2 print(even_numbers)
true
6afa0ebf1d665a64a0a4a7277b18f1ce442c92cf
sdmgill/python
/Learning/7.1-Input.py
894
4.375
4
message = input("Tell me something and I will repeat it back to you: ") print(message) name = input("Please enter your name: ") print("Hello " + name.title()) # building a prompt over several lines prompt = "This is going to be a very long way of asking " prompt += "you what you name is. So..................." prompt += "waht's your name?" name = input(prompt) print("Hello " +name.title()) # input returns everything as a string so we need to convert when evaluating numbers height = input("How tall are you in inches?") height = int(height) if height > 36: print("\nYou are tall enough to ride!") else: print("You are a small fucker!") # Modulo number = input("Enter a number and I will tell you if it is even or odd:") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.")
true
def46f78814c9ca4e28e153774d8a9d668f78463
fander2468/week2_day2_HW
/lesser_then.py
443
4.34375
4
# Given a list as a parameter,write a function that returns a list of numbers that are less than ten # For example: Say your input parameter to the function is [1,11,14,5,8,9]...Your output should [1,5,8,9] my_list = [1,2,12,14,5,6,77,8,22,3,10,13] def lesser_than_ten(numbers): new_list = [] for number in numbers: if number < 10: new_list.append(number) return new_list print(lesser_than_ten(my_list))
true
ed8f4819a364d77fdda527f9f6ad69bc45e7b8dd
tyler7771/learning_python
/recursion.py
2,625
4.21875
4
# Write a recursive method, range, that takes a start and an end # and returns an list of all numbers between. If end < start, # you can return the empty list. def range(start, end): if end < start: return [] result = range(start, end - 1) result.insert(len(result), end) return result # print range(1,100) # Write both a recursive and iterative version of sum of an list. def sum_iter(list): sum = 0 for num in list: sum += num return sum # print sum_iter([1,2,3,4,5]) def sum_rec(list): if len(list) == 0: return 0 num = list.pop() result = sum_rec(list) + num return result # print sum_rec([1,2,3,4,5]) # Write a recursive and an iterative Fibonacci method. The method should # take in an integer n and return the first n Fibonacci numbers in an list. # You shouldn't have to pass any lists between methods; you should be # able to do this just passing a single argument for the number of Fibonacci # numbers requested. def fib_iter(n): if n == 0: return [] elif n == 1: return [1] else: result = [1, 1] while len(result) < n: result.append(result[-2] + result[-1]) return result # print fib_iter(1) # print fib_iter(2) # print fib_iter(3) # print fib_iter(4) # print fib_iter(5) def fib_rec(n): if n == 0: return [] elif n == 1: return [1] elif n == 2: return [1, 1] result = fib_rec(n - 1) result.insert(len(result), (result[-2] + result[-1])) return result # print fib_rec(1) # print fib_rec(2) # print fib_rec(3) # print fib_rec(4) # print fib_rec(5) # Write a recursive binary search: bsearch(array, target). Note that binary # search only works on sorted arrays. Make sure to return the location of the # found object (or nil if not found!). Hint: you will probably want to use # subarrays. def bsearch(list, target): if len(list) == 0: return None mid = len(list) / 2 if list[mid] == target: return mid elif list[mid] > target: return bsearch(list[0:mid], target) elif list[mid] < target: result = bsearch(list[(mid + 1):(len(list))], target) if result == None: result = None else: result += (mid + 1) return result # print bsearch([1, 2, 3], 1) # => 0 # print bsearch([2, 3, 4, 5], 3) # => 1 # print bsearch([2, 4, 6, 8, 10], 6) # => 2 # print bsearch([1, 3, 4, 5, 9], 5) # => 3 # print bsearch([1, 2, 3, 4, 5, 6], 6) # => 5 # print bsearch([1, 2, 3, 4, 5, 6], 0) # => nil # print bsearch([1, 2, 3, 4, 5, 7], 6) # => nil
true
1df55414bfbee7b20e79850c101f4a18bbdc91b5
abhinavnarra/python
/Python program to remove to every third element until list becomes empty.py
646
4.375
4
# Python program to remove to every third element until list becomes empty def removeThirdNumber(int_list): # list starts with 0 index pos = 3 - 1 index = 0 len_list = (len(int_list)) # breaks out once the list becomes empty while len_list > 0: index = (pos + index) % len_list#for first iteration 2%3 remainder 2 so element in 2nd index will be deleted and it will be continued untill the list become empty. # removes and prints the required element print(int_list.pop(index)) len_list -= 1 nums = [1, 2, 3, 4] removeThirdNumber(nums)
true
018618289d9e3c9d984aef740fa362be4af586c7
abhinavnarra/python
/Demonstrate python program to input ‘n’ employee number and name and to display all employee’s information in ascending order based upon their number - dictionary method.py
716
4.5625
5
#Demonstrate python program to input ‘n’ employee number and name and to display all employee’s information in ascending order based upon their number - dictionary method. dict1={} dict2={} No_of_employees=int(input("Enter No of Employees:"))#enter number of employees to be sorted for i in range(1,No_of_employees+1): emp_id=input("Enter id:") name=input("Enter name:") dict1[emp_id]=name#storing the elements in a dictionary print(dict1)#unsorted dictionary for i in sorted(dict1.keys()):#printing the employee number and name and to display all employee’s information in ascending order based upon their number . dict2[i]=dict1[str(i)] print(dict2)#sorted dictionary
true
2f9607ab1c2e61d71cc16ec72e5caaf03fb25de3
szeitlin/interviewprep
/make_anagrams.py
824
4.3125
4
#!/bin/python3 import os # Complete the makeAnagram function below. def make_anagram(a:str, b:str) -> int: """ Count number of characters to delete to make the strings anagrams :param a: a string :param b: another string :return: integer number of characters to delete """ b_list = [y for y in b] overlap, extra = [], [] for i,char in enumerate(a): if char in b_list: overlap.append(char) b_list.remove(char) else: extra.append(char) print("overlap:{}".format(overlap)) print("extra:{}".format(extra)) return len(extra + b_list) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') a = input() b = input() res = make_anagram(a, b) fptr.write(str(res) + '\n') fptr.close()
true
81c57b9e4c681f24c467d8657548fc002739c647
nikointhehood/unix-101
/lesson-1/subject/exercises/exercise-0/biggest.py
820
4.3125
4
#! /usr/bin/python3 import sys # This import allows us to interact with the command line arguments # First, we declare a function which will do the comparison job def biggest(int1, int2): if int1 > int2: print(int1) elif int2 > int1: print(int2) else: print("The integers are equal") # Let's try get the command line arguments try: if len(sys.argv) != 3: # Actually, the target value is 3 because the first element of argv is always the name of the script print("Usage: ./biggest.py integer1 integer2") else: first_int = int(sys.argv[1]) second_int = int(sys.argv[2]) # Now, call the function with the arguments previously retrieved biggest(first_int, second_int) except ValueError: print("Usage: ./biggest.py integer1 integer2")
true
38a378e9ccfc27479b43a229088ff02031a9bad3
bsk17/PYTHONTRAINING1
/databasepack/dbClientdemo.py
2,901
4.4375
4
import sqlite3 # create connection to the db conn = sqlite3.connect("mydb") # for server side programming we have change the connection # line and we have to mention the varchar(size) mycursor = conn.cursor() # function to create the table def createTable(): print("*" * 40) sql = '''create table if not exists student(name varchar, email varchar primary key, mobile varchar , password varchar )''' try: mycursor.execute(sql) print("Table Created") except: print("Something went wrong") # function to insert data def insertData(): print("*" * 40) name = input("Enter name - ") email = input("Enter email - ") mobile = input("Enter mobile - ") password = input("Enter password - ") sql = "insert into student values('" + name + "', '" + email + "', '" + mobile + "', '" + password + "')" try: mycursor.execute(sql) print("Data inserted") except: print("something went wrong") # function to update data def updateData(): print("*" * 40) email = input("Enter email - ") newmobile = input("Enter New mobile - ") sql = "update student set mobile ='" + newmobile + "' where email='" + email + "'" try: mycursor.execute(sql) print("Mobile updated succesfully") except: print("Something went wrong") # function to show the data def showData(): sql = "select * from student" mycursor.execute(sql) for row in mycursor.fetchall(): print(row[0], row[1], row[2], row[3]) # function to delete the data def deleteData(): print("*" * 40) email = input("Enter email - ") sql = "delete from student where email='" + email + "'" try: mycursor.execute(sql) print("Data deleted") except: print("Data deleted succesfully") # function to login def login(): print("*" * 40) email = input("Enter email - ") password = input("Enter password - ") sql = "select * from student where email='" + email + "' and password='" + password + "'" mycursor.execute(sql) if len(mycursor.fetchall()) == 0: print("Could not login") else: print("Login Succesful") sql = "select * from student where email='" + email + "'" mycursor.execute(sql) for row in mycursor.fetchall(): print(row[0], row[1], row[2], row[3]) while True: print("1. Create Table\n2. Insert Data\n3. Update Data\n4. Delete Data\n5. Show Data\n6. Login\n7. Exit") ch = eval(input("Enter Your Choice")) if ch == 1: createTable() elif ch == 2: insertData() elif ch == 3: updateData() elif ch == 4: deleteData() elif ch == 5: showData() elif ch == 6: login() elif ch == 7: conn.close() exit() else: print("Wrong choice") conn.commit()
true
a361f51e6cda567cf1bf3705c2f831bc099e5c50
CCedricYoung/bitesofpy
/263/islands.py
1,293
4.28125
4
def count_islands(grid): """ Input: 2D matrix, each item is [x, y] -> row, col. Output: number of islands, or 0 if found none. Notes: island is denoted by 1, ocean by 0 islands is counted by continuously connected vertically or horizontally by '1's. It's also preferred to check/mark the visited islands: - eg. using the helper function - mark_islands(). """ islands = 0 # var. for the counts queue = {(i,j) for i in range(len(grid)) for j in range(len(grid[0]))} while len(queue) > 0: i, j = queue.pop() if grid[i][j] != 1: continue mark_islands(i, j, grid, queue) islands += 1 return islands def mark_islands(i, j, grid, queue): """ Input: the row, column, grid and queue Output: None. Side-effects: Grid marked with visited islands. Visited paths removed from queue. """ grid[i][j] = '#' DIRECTIONS = [(1, 0), (-1, 0), (0,1), (0,-1)] paths = [(i + d[0], j + d[1]) for d in DIRECTIONS] for path in paths: if path not in queue or grid[path[0]][path[1]] == 0: continue queue.remove(path) grid[path[0]][path[1]] = '#' mark_islands(*path, grid, queue)
true
be7a281f69933d5a719d3ea23cfa64e2c07786ed
sumitbatwani/python-basics
/lists.py
879
4.25
4
# - List - # names = ["John", "Sarah", "Aman"] # print(names[1:2]) # names[start: exclusion_end] # - Largest number in a list - # numbers = [5, 1, 2, 4, 3] # largest_number = numbers[0] # for item in numbers: # if item > largest_number: # largest_number = item # print(f"largest number = {largest_number}") # 2D List # ''' # matrix = [ # [1, 2, 3], # [4, 5, 6], # [7, 8, 9] # ] # ''' # matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # for row in matrix: # for item in row: # print(item) # Remove duplicate from a list # list_of_numbers = [1, 2, 3, 4, 5, 5, 1] # for number in list_of_numbers: # if list_of_numbers.count(number) > 1: # list_of_numbers.remove(number) # print(list_of_numbers) # or # uniques = [] # for number in list_of_numbers: # if number not in uniques: # uniques.append(number) # print(uniques)
true
bc016336933f66d8ec6af96eb078859b7640ac85
lindaspellman/CSE111
/W10 Handling Exceptions/class_notes.py
821
4.125
4
import math def main(): ## program driver - GOAL: Keep lean ## prompt user for how many circles they have numberOfCircles = int(input("How many circles are we working with? ")) areasList = loopForCircles(numberOfCircles) displayAreas(areasList) ## display each area: separate print statements or a list? def displayAreas(areasList): areasList = [round(i, 2) for i in areasList] print(areasList) def loopForCircles(numberOfCircles): circleAreas = [] ## loop x times: compute area for each circle for _ in range(numberOfCircles): ## get radius for each circle r = float(input("Please enter the radius: ")) circleAreas.append(computeCircleArea(r)) return circleAreas def computeCircleArea(radius): ## compute and return circle area return math.pi * radius**2 if __name__ == '__main__': main()
true
186d3639f0c8109d68ad43f442bc6bc49338550a
Techbanerg/TB-learn-Python
/10_MachineLearning/example_numpy.py
2,359
4.34375
4
# NumPy is the fundamental Python package for scientific computing. It adds the capabilities of N-dimensional arrays, element-by-element operations (broadcasting), core # mathematical operations like linear algebra, and the ability to wrap C/C++/Fortran code.We will cover most of these aspects in this chapter by first covering # The NumPy package enables users to overcome the shortcomings of the Python lists by providing a data storage object called ndarray. The ndarray is similar to lists, # but rather than being highly flexible by storing different types of objects in one list, only the same type of element can be stored in each column. For example, # with a Python list, you could make the first element a list and the second another list or dictionary. With NumPy arrays, you can only store the same type of # element, e.g., all elements must be floats, integers, or strings. Despite this limitation, ndarray wins hands down when it comes to operation times, as the # operations are sped up significantly. Using the time's magic command in IPython, we compare the power of NumPy ndarray versus Python lists in terms of speed. #!/usr/bin/Python3 import numpy as np #array1 = np.arange(1e7) #array2 = array1.tolist() #print(array1, array2) arr1 = np.arange(15).reshape(3, 5) arr2 = [[0,1,2],[4,5,6]] # The ndarray operation is ∼ 25 faster than the Python loop in this example. Are you convinced that the NumPy ndarray is the way to go? From this point on, we will be # working with the array objects instead of lists when possible. Should we need linear algebra operations, we can use the matrix object, which does not # use the default broadcast operation from ndarray. For example, when youmultiply two equally sized ndarrays, which we will denote as A and B, the ni, j element of A is only # multiplied by the ni, j element of B. When multiplying arr4 = np.zeros((2,2)) matrix_arr = np.matrix(arr4) arr3 = np.arange(1000) # Matrix Multiplication arr5 = np.arange(100).reshape(10, 10) arr6 = np.arange(200).reshape(10, 20) result = arr5.dot(arr6) # creating 5x5x5 cube of 1's cube_array = np.ones((5,5,5)).astype(np.float16) print("{} \n {} \n {} \n {} \n {}".format(arr1, arr2, cube_array, matrix_arr, result)) print(" shape : {0} dimension: {1} type: {2} itemsize: {3}".format(arr1.shape, arr1.ndim, arr1.dtype, arr1.itemsize ))
true
f944c425973b7e81855743e7804ab96189e84a3a
Techbanerg/TB-learn-Python
/00_Printing/printing.py
1,708
4.34375
4
# This exercise we are going to print single line and multi line comments # The following examples will help you understand the different ways of # printing import pprint from tabulate import tabulate from prettytable import PrettyTable print ("Mary had a little lamb") print ("Its Fleece was white as %s ." % 'snow') print('Mercury', 'Venus', 'Earth', sep=', ', end=', ') print('Mars', 'Jupiter', 'Saturn', sep=', ', end=', ') print('Uranus', 'Neptune', 'Pluto', sep=', ') # Using Newline Character with extra padding print('Printing in a Nutshell', end='\n * ') print('Calling Print', end='\n * ') print('Separating Multiple Arguments', end='\n * ') print('Preventing Line Breaks') pp =pprint.PrettyPrinter(indent=4, depth=2, width=80) grocery = ['eggs', 'bread', 'milk'] pp.pprint(grocery) print(pprint.isreadable(grocery)) print(tabulate([['Arindam', 50000], ['Shaun', 30000]], headers=['Name', 'Salary'], tablefmt='orgtbl')) table = PrettyTable(['Name', 'PhNo']) table.add_row(['Sourav', 979136789]) table.add_row(['Sachin', 8792798890]) print(table) # String formatting is attractively designing your string using formatting techniques # provided by the particular programming language. We have different string formatting # techniques in Python. We are now going to explore the new f-string formatting technique. # f-string evaluates at runtime of the program. It's swift compared to the previous methods. # f-string having an easy syntax compared to previous string formatting techniques of Python. # We will explore every bit of this formatting using different examples Company = "Wipro" Incentive = "Nothing" print(F"Company {Company} is giving {Incentive} as incentive for year 2020")
true
b77d9ad34b7ca42a441be75c4ba747a1e68f905a
Techbanerg/TB-learn-Python
/02_DataTypes/List/list_comprehension.py
700
4.34375
4
# This short course breaks down Python list comprehensions for yuo step by step # see how python's comprehensions can be transformed from and to equivalent for loops # so you wil know exactly what's going on behind the scenes # one of the favorite features in Python are list comprehension. # they can seem a bit arcane at first but when you break them down # they are actually very simple constructs. # list comprehensions squares = [x * x for x in range(10)] add = [x + x for x in range(5)] slist = ['sachin', 'sourav', 'dravid'] list1 = [item for item in slist if item.startswith('s')] # Best practices to use list comprehensions # values = [ expression] print(add) print(squares) print(list1)
true
9160b2901c50fe7aa9e901598409315daf832b98
sub7ata/Pattern-Programs-in-Python
/pattern12.py
215
4.25
4
""" Example: Enter the number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 """ n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end=" ") print()
true
3cdfd9358e1fd875787b179dff332289f293304a
ashley-honn/homework2-
/solution1.py
444
4.15625
4
# solutions ##This is for Solution 1 #Titles for cells cell_1 = 'Number' cell_2 = 'Square' cell_3 = 'Cube' space = '20' align = ' ' #This will print titles for all cells print(f'{cell_1 :{align}>{space}}',f'{cell_2 :{align}>{space}}',f'{cell_3 :{align}>{space}}') num = 0 #This will print number, squared, and cubed from range 0 to 6 for num in range (0, 6): print(f'{num :{space}}',f'{num*num :{space}}',f'{num*num*num :{space}}')
true
b34a8ceb62caf8cf858f8cb987890ed60d48fa2f
itchyporcupine/Project-Euler-Solutions
/problems/problem1.py
538
4.28125
4
""" If we list all of the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. http://www.projecteuler.net/index.php?section=problems&id=1 """ def problem_1(): print "The sum of all natural numbers below 1000 that are multiples of 3 and 5 is %d" % sum(filter(multiple_of_3_or_5, range(1, 1000))) def multiple_of_3_or_5(n): """Returns true if n is divisible by 3 or 5""" return (not (n%3)) or (not (n%5))
true
7a8ba86d03fd50adc54e8950c416c4dc466bb251
prepiscak/beatson_rosalind
/id_HAMM/RS/006_Rosalind_HAMM.py
2,367
4.125
4
#!/usr/bin/env python3 ''' Counting Point Mutations Problem Given two strings s and t of equal length, the Hamming distance between s and t, denoted dH(s,t), is the number of corresponding symbols that differ in s and t. Given: Two DNA strings s and t of equal length (not exceeding 1 kbp). Return: The Hamming distance dH(s,t). ''' import os import re def allowed_match(strg, search=re.compile(r'[^GCTA.]').search): return not bool(search(strg)) def hamm(s, t): dH = 0 for l in range(0, len(s)): if s[l] != t[l]: dH += 1 return dH def test(): test_s = "GAGCCTACTAACGGGATA" test_t = "CATCGTAATGACGGCCTG" print(test_s) print(test_t) print("Hamming Distance:") print(hamm(test_s, test_t)) def inputSequence(): s_i = input("Input first sequence ") t_i = input("Input second sequence: ") if s_i == 'q' or t_i == 'q': print("Quiting") exit() elif len(s_i) != len(t_i): print("Sequences of different length. Please re-enter") inputSequence() elif allowed_match(s_i) or allowed_match(t_i): print("Illegal characters in sequence. Please re-enter") inputSequence() else: print(hamm(s_i, t_i)) def check_file(lst): if len(lst[0]) != len(lst[1]): return False elif allowed_match(lst[0]) or allowed_match(lst[1]): return False else: return True def main(): fn = input("Please enter path, 'test' for test data, 'input' to input sequences or 'q' to quit\n") if fn == 'test': test() elif fn == 'input': inputSequence() elif fn == 'q': exit() else: # Check file exists and if so load in data exists = os.path.isfile(fn) if exists: # Store configuration file values print("File found") # Load data and split into two with open(fn, 'r') as fhand: dt = fhand.read().split('\n') #check_file(dt) if True: print("Hamming Distance:") print(hamm(dt[0], dt[1])) else: print("Sorry, problem with sequences in file") main() else: print("Sorry, couldn't find the file.") print() main() main()
true
1f769ec8e3df1f204b67776026c50589b3623163
bhupathirajuravivarma/positive-numbers-in-a-range
/positivenoinrange.py
523
4.3125
4
#positive numbers in lists list1 = [6,-7,5,3,-1] for num in list1: #using membership operator to check if value exists in 'list1'& iterating each element in list. if num>=0: #checking for positive number in list. print(num,end=" ") print("\n") list2=[2,14,-45,3] for num in list2: #using membership operator to check if value exists in 'list2'. if num>=0: #checking for positive number in list. print(num,end=" ")
true
39169e30f904bb9755256220e758e17e2b2afe67
stoneand2/python-washu-2014
/day2/clock2.py
1,330
4.21875
4
class Clock(): def __init__(self, hours, minutes=00): self.hours = hours # this is an instance variable, able to be accessed anywhere you call self self.minutes = minutes @classmethod #instead of self, the first thing we access is the class itself def at(cls, hours, minutes=00): return cls(hours, minutes) # basically, same as return Clock(...) def __add__(self, number): hour_time = self.hours minute_time = self.minutes if number + minute_time < 60: minute_time = minute_time + number elif number + minute_time > 60: minute_time = (number + minute_time) - 60 #### won't work if over 120 hour_time = hour_time + ((number + minute_time) / 60) else: pass if hour_time > 23: hour_time = (hour_time) - 24 else: pass self.hours = hour_time self.minutes = minute_time return self # lets you use self.hours and self.minutes in the __str__ method def __str__(self): hour_time2 = self.hours minute_time2 = self.minutes string_hour = str(hour_time2) string_minute = str(minute_time2) if len(string_hour) == 1: string_hour = "0" + string_hour else: pass if len(string_minute) == 1: string_minute = ":0" + string_minute else: pass return string_hour + string_minute clock = Clock.at(23) + 3 print clock.__str__()
true
6e948d96919febbb19d304897276e6ab366960d5
ayanakshi/journaldev
/Python-3/basic_examples/float_function.py
617
4.59375
5
# init a string with the value of a number str_to_float = '12.60' # check the type of the variable print('The type of str_to_float is:', type(str_to_float)) # use the float() function str_to_float = float(str_to_float) # now check the type of the variable print('The type of str_to_float is:', type(str_to_float)) print('\n') # init an integer int_to_float = '12.60' # check the type of the variable print('The type of int_to_float is:', type(int_to_float)) # use the float() function int_to_float = float(int_to_float) # now check the type of the variable print('The type of int_to_float is:', type(int_to_float))
true
ecb48a4e1889f6e7a88dfaf1bcea829668c3e6e9
doanthanhnhan/learningPY
/01_fundamentals/04_functions/03_built_in_functions.py
1,051
4.40625
4
# Strings # Search # a_string.find(substring, start, end) random_string = "This is a string" print(random_string.find("is")) # First instance of 'is' occurs at index 2 print(random_string.find("is", 9, 13)) # No instance of 'is' in this range # Replace # a_string.replace(substring_to_be_replace, new_string) a_string = "Welcome to Educative!" new_string = a_string.replace("Welcome to", "Greetings from") print(a_string) print(new_string) # Changing the Letter Case # In Python, the letter case of a string can be easily changed using the upper() and lower() methods. print("UpperCase".upper()) print("LowerCase".lower()) # Type Conversions print(int("12") * 10) # String to integer print(int(20.5)) # Float to integer print(int(False)) # Bool to integer # print (int("Hello")) # This wouldn't work! print(ord('a')) print(ord('0')) print(float(24)) print(float('24.5')) print(float(True)) print(str(12) + '.345') print(str(False)) print(str(12.345) + ' is a string') print(bool(10)) print(bool(0.0)) print(bool("Hello")) print(bool(""))
true
d999f45998e7e623f150f3fcad477524da21ee0a
doanthanhnhan/learningPY
/02_oop/04_polymorphism/06_abstract_base_classes.py
561
4.3125
4
from abc import ABC, abstractmethod class Shape(ABC): # Shape is a child class of ABC @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Square(Shape): def __init__(self, length): self.length = length def area(self): return (self.length * self.length) def perimeter(self): return (4 * self.length) shape = Shape() # this will code will not compile since Shape has abstract methods without # method definitions in it square = Square(4) print(square)
true
e9aba8cf06774f9232d5b242efef69fb799f3e76
doanthanhnhan/learningPY
/01_fundamentals/04_functions/02_function_scope.py
1,561
4.78125
5
# Data Lifecycle # In Python, data created inside the function cannot be used from the outside # unless it is being returned from the function. # Variables in a function are isolated from the rest of the program. When the function ends, # they are released from memory and cannot be recovered. name = "Ned" def func(): name = "Stark" func() print(name) # The value of 'name' remains unchanged. # Altering Data # When mutable data is passed to a function, the function can modify or alter it. # These modifications will stay in effect outside the function scope as well. # An example of mutable data is a list. # In the case of immutable data, the function can modify it, # but the data will remain unchanged outside the function’s scope. # Examples of immutable data are numbers, strings, etc. num = 20 def multiply_by_10(n): n *= 10 num = n # Changing the value inside the function print("Value of num inside function:", num) return n multiply_by_10(num) print("Value of num outside function:", num) # The original value remains unchanged # So, it’s confirmed that immutable objects are unaffected by the working of a function. # If we really need to update immutable variables through a function, # we can simply assign the returning value from the function to the variable. num_list = [10, 20, 30, 40] print(num_list) def multiply_by_10(my_list): my_list[0] *= 10 my_list[1] *= 10 my_list[2] *= 10 my_list[3] *= 10 return my_list multiply_by_10(num_list) print(num_list) # The contents of the list have been changed
true
6191157eb90cbf6b994c06b80b884695b36e9f01
doanthanhnhan/learningPY
/02_oop/01_classes_and_objects/12_exercise_01.py
490
4.375
4
""" Square Numbers and Return Their Sum Implement a constructor to initialize the values of three properties: x, y, and z. Implement a method, sqSum(), in the Point class which squares x, y, and z and returns their sum. Sample Properties 1, 3, 5 Sample Method Output 35 """ class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def sqSum(self): return self.x ** 2 + self.y ** 2 + self.z ** 2 test = Point(1, 3, 5) print("Sum: ", test.sqSum())
true
be2d9d9f1ea11a20209c8d2e816452567dd3114b
carolinetm82/MITx-6.00.1x
/Python_week2/week2_pbset2_pb1.py
1,305
4.21875
4
""" Problem 1 - Paying Debt off in a Year Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal monthlyPaymentRate - minimum monthly payment rate as a decimal For each month, calculate statements on the monthly payment and remaining balance.At the end of 12 months, print out the remaining balance. """ balance = 484 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 monthlyInterestRate = annualInterestRate/12 for n in range(12): # Compute the monthly payment, based on the previous month’s balance minimumMonthlyPayment = monthlyPaymentRate * balance # Update the outstanding balance by removing the payment monthlyUnpaidBalance = balance - minimumMonthlyPayment # then charging interest on the result UpdatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance) print('Month', n+1, 'Remaining balance:',round(UpdatedBalance,2)) balance=UpdatedBalance print('Remaining balance at the end of the year:',round(UpdatedBalance,2))
true
69f67048cf25a900a9eb5fa3f444c2c42f0cfb40
sarozzx/Python_practice
/Functions/18.py
205
4.3125
4
# Write a Python program to check whether a given string is number or not # using Lambda. check_number = lambda x:True if x.isnumeric() else False a=str(input("Enter a string ")) print(check_number(a))
true
0743869ff6c47e458db2290981671f555b539794
sarozzx/Python_practice
/Functions/2.py
247
4.125
4
# Write a Python function to sum all the numbers in a list. def sum1(list): return sum(list) list =[] n=int(input("Enter number of items in list")) for i in range(0,n): x=int(input()) list.append(x) print("THe sum is ",sum1(list))
true
971c857b14a11f193b4e814f8844854e587d0b0f
sarozzx/Python_practice
/Data Structures/27.py
430
4.25
4
# Write a Python program to replace the last element in a list with another list. def con_list(list1,list2): list1[-1:]=list2 return list1 list1 =[] n=int(input("Enter number of items in list1")) for i in range(0,n): x=str(input()) list1.append(x) list2 =[] n=int(input("Enter number of items in list2")) for i in range(0,n): x=str(input()) list2.append(x) list1=con_list(list1,list2) print(list1)
true
ab919b511392475452595c0610cb72f6ca0525a4
sarozzx/Python_practice
/Functions/9.py
376
4.1875
4
# Write a Python function that takes a number as a parameter and check the # number is prime or not. def prime1(n): if (n==1): return False elif (n==2): return True; else: for x in range(2,n): if(n % x==0): return False return True x=int(input("Enter a number to check if its prime ")) print(prime1(x))
true
19bcef6d7e895e153eebe00dcd434e88b340058b
sarozzx/Python_practice
/Data Structures/38.py
296
4.21875
4
# Write a Python program to remove a key from a dictionary. dict1 = {} n=int(input("Enter number of items in dictionary")) for i in range(n): x=str(input("key")) y=str(input("value")) dict1[x]=y print(dict1) q=str(input("which key do u wanna remove")) del dict1[q] print(dict1)
true
464c3eecf884c6008379552d1bfe2e151a140b4b
sarozzx/Python_practice
/Functions/5.py
320
4.28125
4
# Write a Python function to calculate the factorial of a number (a non-negative # integer). The function accepts the number as an argument. def facto(x): if(x==0): return 0 if(x==1): return 1 return x*facto(x-1) y=int(input("Enter a number : ")) print("The factorial of ",y,"is",facto(y))
true
1d0d4598b8477da1f94808a2bea06a28e3211a09
sarozzx/Python_practice
/Data Structures/23.py
312
4.28125
4
# Write a Python program to check a list is empty or not. def check_emp(list): if not list: print("it is an empty list") else: print("it is not an empty list") list =[] n=int(input("Enter number of items in list")) for i in range(0,n): x=input() list.append(x) check_emp(list)
true
56e9001a79d3810a3b29fb33e3d37e79d27b7732
starmap0312/refactoring
/dealing_with_generalization/pull_up_constructor_body.py
1,457
4.34375
4
# - if there are identical constructors in subclasses # you can pull up to superclass constructor and call superclass constructor from subclass constructor # - if see common behaviors in normal methods of subclasses, consider to pull them up to superclass # ex. if the common behaviors are in constructors, you need to pull them up to superclass contructors # you need to call them from subclass constructors unless the subclass construction does nothing # before: identical constructors in subclasses class Employee(object): def __init__(self): self._name = None self._id = None class Manager(Employee): # subclass def __init__(self, name, id, grade): self._name = name self._id = id self._grade = grade class Engineer(Employee): # subclass def __init__(self, name, id, grade): self._name = name self._id = id self._grade = grade engineer = Engineer('John', '15321', '85') print engineer._name, engineer._id, engineer._grade # after: pull up constructor to superclass class Employee(object): # superclass def __init__(self, name, id): self._name = name self._id = id class Engineer(Employee): # subclass def __init__(self, name, id, grade): super(Engineer, self).__init__(name, id) self._grade = grade engineer = Engineer('John', '15321', '85') print engineer._name, engineer._id, engineer._grade
true
fb1b1e73c7d5311e36eb7f1fd8d2cddd9ad9fb7b
starmap0312/refactoring
/simplifying_conditional_expressions/introduce_null_object.py
722
4.15625
4
# - if you have repeated checks for a null value, then replace the null value with a null object # - if one of your conditional cases is a null, use introduce null object # before: use conditionals class Customer(object): # abstract class def getPlan(self): raise NotImplementedError # client has a conditional that handles the null case if customer is None: plan = doSomething() else: plan = customer.getPlan() # after: add null object in which it performs doSomething(), thus the conditional can be removed class NullCustomer(Customer): def getPlan(self): doSomething() # simplified code: client uses polymorphism that is able to perform the null case plan = customer.getPlan()
true