blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
782b19c9bf441bca8e8c5ae754cbec05c0bce121
khuang7/3121-algorithms
/dynamic_programming/fib.py
838
4.125
4
''' A simple fibonacci but using memoization and dynamic programing An introduction to the basics of dynamic programming ''' memo = {} def main(): print(fib_naive(5)) print(fib_bottoms_up(4)) def fib_naive(n): ''' We used the recursive method in order to fine every combination from f(n) down the tree This is EXPONENTIAL and bad.. ''' #fib(1) and fib(2) are 1 if n == 1 or n == 2: return 1 else: f = fib_naive(n-1) + fib_naive(n-2) return f def fib_bottoms_up(n): ''' We iteratively start from 1..n Store it in memoization WE can actually just keep updating as we go up O(n) TIME ''' for k in range(1,n + 1): if k <= 2: f = 1 else: f = memo[k-1] + memo[k-2] memo[k] = f return memo[n] main()
false
89495c7cb55268122493bb126b1e3ea9a9c19fca
Jamilnineteen91/Sorting-Algorithms
/Merge_sort.py
1,986
4.34375
4
nums = [1,4,5,-12,576,12,83,-5,3,24,46,100,2,4,1] def Merge_sort(nums): if len(nums)<=1: return nums middle=int(len(nums)//2)#int is used to handle a floating point result. left=Merge_sort(nums[:middle])#Divises indices into singular lists. print(left)#Prints list division, lists with singular items are the final results. right=Merge_sort(nums[middle:])#Divises indices into singular lists. print(right)#Prints list division, lists with singular items are the final results. return merge(left,right) def merge(left, right): sorted_list=[] index_L=0 #index_L is used to incrementally ascend the left list. index_R=0 #index_R is used to incrementally ascend the right list. #Lists containing more than one item will enter the while loop where they'll be sorted. while index_L < len(left) and index_R < len(right): #Prints left & right groups that are have entered the while loop. print(left[index_L:], right[index_R:]) if left[index_L]<=right[index_R]: sorted_list.append(left[index_L]) index_L+=1 #Prints the current sorted_list state, the smallest item between the left group and right group has been inserted into sorted_list. print(sorted_list) else: sorted_list.append(right[index_R]) index_R+=1 #Prints the current sorted_list state, the smallest item between the left group and right group has been inserted into sorted_list. print(sorted_list) #Lists containing one item will be added to the sorted_list. #The append function is unable to append lists into new_list, hence why'+=' is used. #Unable to use 'index_L' as a list index since the incrementation only takes place in the while loop,hence why 'index_L:' and 'index_R:' are used. sorted_list+= left[index_L:] sorted_list+= right[index_R:] return sorted_list print(Merge_sort(nums))
true
b59d828a5f75746cff11a5238a485c7cc98b594d
Expert37/python_lesson_3
/123.py
1,099
4.5
4
temp_str = 'Все счастливые семьи похожи друг на друга, каждая несчастливая семья несчастлива по-своему. Все счастливые семьи' print('1) методами строк очистить текст от знаков препинания;') for i in [',','.','!',':','?']: temp_str = temp_str.replace(i,'') print(temp_str) print() print('2) сформировать list со словами (split);') temp_str = list(temp_str.split()) # приведем к типу list и применим метод split print(type(temp_str), temp_str) print() print('3) привести все слова к нижнему регистру (map);') new_temp_str = list(map(lambda x:x.lower(),temp_str)) print(type(new_temp_str), new_temp_str) print() print('4) получить из list пункта 3 dict, ключами которого являются слова, а значениями их количество появлений в тексте;') #dict_temp = dict.new_temp_str #print(type(dict_temp))
false
b4d3e19be67069f37487506a473ba9bce4def0be
jeffjbilicki/milestone-5-challenge
/milestone5/m5-bfs.py
631
4.1875
4
#!/usr/bin/env python # Given this graph graph = {'A': ['B', 'C', 'E'], 'B': ['A','D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B','D'], 'F': ['C'], 'G': ['C']} # Write a BFS search that will return the shortest path def bfs_shortest_path(graph, start, goal): explored = [] # keep track of all the paths to be checked queue = [start] # return path if start is goal if start == goal: return "Home sweet home!" # Find the shortest path to the goal return "Cannot reach goal" ans = bfs_shortest_path(graph,'G', 'A') print(ans)
true
580a215b24366f1e6dcf7d3d5253401667aa1aae
afialydia/Graphs
/projects/ancestor/ancestor.py
2,127
4.125
4
from util import Queue class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex_id): """ Add a vertex to the graph. """ if vertex_id not in self.vertices: self.vertices[vertex_id] = set() def add_edge(self, v1, v2): """ Add a directed edge to the graph. """ if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2) else: raise IndexError('Vertex does not exist in graph') def get_neighbors(self, vertex_id): """ Get all neighbors (edges) of a vertex. """ if vertex_id in self.vertices: return self.vertices[vertex_id] else: raise IndexError('ERROR: No such Vertex exist.') def earliest_ancestor(ancestors, starting_node): g = Graph() for pair in ancestors: #< instead of for pair do for parent , child for more readability of code g.add_vertex(pair[0]) g.add_vertex(pair[1]) g.add_edge(pair[1],pair[0]) q = Queue() q.enqueue([starting_node]) # <- enqueue a path to starting node visited = set() #<- creating a set to store visited earliest_ancestor = -1 #<- no parents set to -1 initializing parents while q.size() > 0: path = q.dequeue()#<- gets the first path in the queue v = path[-1]#<- gets last node in the path if v not in visited:#<- check if visited and if not do the following visited.add(v) if((v < earliest_ancestor) or (len(path)>1)): #<-checks if path(v) is less than parent meaning if there was no path it would be the parent or length is longer than 1 earliest_ancestor = v #sets ancestor for neighbor in g.get_neighbors(v): # copy's path and enqueues to all its neighbors copy = path.copy() copy.append(neighbor) q.enqueue(copy) return earliest_ancestor
true
4e21512a276938c54dc5a26524338584d3d31673
snangunuri/python-examples
/pyramid.py
1,078
4.25
4
#!/usr/bin/python ############################################################################ #####This program takes a string and prints a pyramid by printing first character one time and second character 2 timesetc.. within the number of spaces of length of the given string### ############################################################################ seq="abcdefghijklmnopqrstuvwxyz" spaces="" letters_str="" for letter in seq: #runs for length of seq for i in range(1, len(seq) - seq.index(letter)): #uses a backwards for loop to add the number of spaces required and decrease the number of spaces by one each time spaces += " " #adds spaces to the list concat_space for j in range(0, seq.index(letter) + 1): #uses a forward for loop to add the right letter and number of letters to the triangle letters_str += letter #adds letters to the list concat_str print spaces + letters_str #joins the spaces and the letters together spaces = "" #resets for a new line of the triangle letters_str="" #resets for a new line of the triangle
true
76c008e9115f338deac839e9e2dafd583377da46
pkongjeen001118/awesome-python
/generator/simple_manual_generator.py
517
4.15625
4
def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n if __name__ == '__main__': a = my_gen() # return generator obj. print(a) print(next(a)) # it will resume their execution and state around the last point of value print(next(a)) # and go to next yield print(next(a)) # and when no more yiled it will do a 'StopIteration' print(next(a))
true
5cb87538a3b33dd04ec2d3ded59f0524c04519c4
pkongjeen001118/awesome-python
/data-strucutre/dictionaries.py
480
4.375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # simple dictionary mybasket = {'apple':2.99,'orange':1.99,'milk':5.8} print(mybasket['apple']) # dictionary with list inside mynestedbasket = {'apple':2.99,'orange':1.99,'milk':['chocolate','stawbery']} print(mynestedbasket['milk'][1].upper()) # append more key mybasket['pizza'] = 4.5 print(mybasket) # get only keys print(mybasket.keys()) # get only values print(mybasket.values()) # get pair values print(mybasket.items())
false
ff8bc8c1966b5211da2cba678ef60cad9a4b225d
RossySH/Mision_04
/Triangulos.py
1,020
4.25
4
# Autor: Rosalía Serrano Herrera # Define qué tipo de triángulo corresponde a las medidas que teclea el usuario def definirTriangulo(lado1, lado2, lado3): #determina que tipo de triangulo es dependiendo sus lados if lado1 == lado2 == lado3: return "Equilátero" elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3: return "Isósceles" elif lado1**2 == lado2**2 + lado3**2 or lado2**2 == lado1**2 + lado3**2 or lado3**2 == lado1**2 + lado2**2: return "Rectángulo" else: return "Otro" def main(): lado1 = int(input("Teclea un lado del triángulo: ")) lado2 = int(input("Teclea otro lado del triángulo: ")) lado3 = int(input("Teclea el último lado del triángulo: ")) if lado1 > lado2 + lado3 or lado2 > lado1 + lado3 or lado3 > lado2 + lado1: print("Estos lados no corresponden a un triángulo.") else: triangulo = definirTriangulo(lado1, lado2, lado3) print("El tipo de triángulo es:", triangulo) main()
false
1f291ba8c19a6b242754f14b58e0d229385efe8b
JunyoungJang/Python
/Introduction/01_Introduction_python/10 Python functions/len.py
663
4.1875
4
import numpy as np # If x is a string, len(x) counts characters in x including the space multiple times. fruit = 'banana' fruit_1 = 'I eat bananas' fruit_2 = ' I eat bananas ' print len(fruit) # 6 print len(fruit_1) # 13 print len(fruit_2) # 23 # If x is a (column or row) vector, len(x) reports the length of vector x. a = np.array([[1], [2], [3]]) b = np.array([1, 2, 3]) print len(a) print len(b) # If x is a matrix, len(x) reports the number of rows in matrix x. c = np.array([[1, 2, 3], [1, 2, 3]]) d = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) e = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]) print len(a) print len(b) print len(c)
true
6e8ac507b80dd1641922f895a1d06bba718065c3
ICESDHR/Bear-and-Pig
/笨蛋为面试做的准备/leetcode/Algorithms and Data Structures/sort/bubble_sort.py
343
4.15625
4
def bubble_sort(lists): if len(lists) <= 1: return lists for i in range(0, len(lists)): for j in range(i + 1, len(lists)): if lists[i] > lists[j]: lists[j], lists[i] = lists[i], lists[j] return lists if __name__ == "__main__": lists = [9, 8, 7, 6, 5] print(bubble_sort(lists))
false
0ff9201f5970cca2af58757d2d855446994e0335
ICESDHR/Bear-and-Pig
/Practice/Interview/16.数值的整数次方.py
1,054
4.3125
4
# -*- coding:utf-8 -*- # 看似简单,但是情况要考虑周全 def Pow(base,exponent): if exponent == 0: return 1 elif exponent > 0: ans = base for i in range(exponent-1): ans *= base return ans else: if base == 0: return 'Error!' else: ans = base for i in range(-exponent-1): ans *= base return 1/ans # 对算法效率进行优化,采用递归,同时用位运算代替乘除运算及求余运算 # 但是不能处理底数为浮点数的运算 def Pow2(base,exponent): if exponent == 0: return 1 elif exponent == 1: return base elif exponent > 1: ans = Pow2(base, exponent>>1) # 右移代替整除 ans *= ans if exponent & 1 == 1: # 用位运算判断奇偶 ans *= base return ans else: if base == 0: return 'Error!' ans = Pow2(base, (-exponent)) return 1.0/ans if __name__ == '__main__': test = [(2,3),(0,-5),(-2,-3),(0.5,2)] for base,exponent in test: print('base =', base, ',exponent =', exponent) print(Pow(base, exponent), end='\t') print(Pow2(base, exponent))
false
571400657495936c96d31a67b1bc2afeeeaa1bf6
ICESDHR/Bear-and-Pig
/Practice/Interview/24.反转链表.py
1,016
4.34375
4
# -*- coding:utf-8 -*- class ListNode: def __init__(self,value): self.value = value self.next = None # 没思路 def ReverseList(root): pNode,parent,pHead = root,None,None while pNode: child = pNode.next if child is None: pHead = pNode pNode.next = parent parent = pNode pNode = child return pHead # 递归方法,需要返回两个值 def ReverseList2(root): if root and root.next: pHead,parent = ReverseList2(root.next) parent.next = root root.next = None return pHead,root return root,root def Build(): root = ListNode(0) node1 = ListNode(1) root.next = node1 node2 = ListNode(2) node1.next = node2 node3 = ListNode(3) node2.next = node3 node4 = ListNode(4) node3.next = node4 return root def Print(root): temp = root while temp: print(temp.value) temp = temp.next if __name__ == '__main__': test = [] root = Build() print('The List is:') Print(root) print('After reverse:') Print(ReverseList(root)) # pHead,parent = ReverseList2(root) # Print(pHead)
true
c247ba288604b38dafbb692aa49acf8b74ebd353
izdomi/python
/exercise10.py
482
4.25
4
# Take two lists # and write a program that returns a list that contains only the elements that are common between the lists # Make sure your program works on two lists of different sizes. Write this using at least one list comprehension. # Extra: # Randomly generate two lists to test this import random list1 = random.sample(range(1,15), 10) list2 = random.sample(range(1,30), 8) common = [i for i in list1 if i in list2] print(f'list1 = {list1} \nlist2 = {list2}') print(common)
true
086daed19d3d5115b9be43430c74c52d4cda4e15
izdomi/python
/exercise24.py
1,385
4.375
4
# Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s # print statement. def board_draw(height, width): top = "┌" + "┬".join(["─"*4]*width) + "┐\n" bottom = "└" + "┴".join(["─"*4]*width) + "┘" middle = "├" + "┼".join(["─"*4]*width) + "┤\n" print(top + middle.join( "│" + "│".join(' '.format(x * width + y + 1) for y in range(width)) + "│\n" for x in range(height)) + bottom) print(board_draw(4,3)) def board_draw(height, width): square = 0 print(" --- " * width) for x in range(height): line = "| " for i in range(0, width): line += format(square, '02d') + " | " square += 1 print(line) print(" --- " * width) heightinp= int(input("Enter the height of the board: ")) widthinp= int(input("Enter the width of the board: ")) board_draw(heightinp,widthinp) def drawboard(size): size = int(size) i = 0 top = "--- " middle = "| " top = top * size middle = middle * (size+1) while i < size+1: print(top) if not (i == size): print(middle) i += 1 print(drawboard(4)) a = '---'.join(' ') b = ' '.join('||||') print('\n'.join((a, b, a, b, a, b, a)))
false
698212d5376c53e07b4c5410dfd77aac16e97bd2
izdomi/python
/exercise5.py
703
4.21875
4
# Take two lists, # and write a program that returns a list that contains only the elements that are common between the lists. # Make sure your program works on two lists of different sizes. # Extras: # Randomly generate two lists to test this # Write this in one line of Python lst1 = [] lst2 = [] num1 = int(input("length of list 1: ")) for i in range(num1): element1 = int(input("Element for list 1: ")) lst1.append(element1) num2 = int(input("length of list 2: ")) for j in range(num2): element2 = int(input("Element for list 2: ")) lst2.append(element2) if num1 < num2: common = [i for i in lst1 if i in lst2] else: common = [j for j in lst2 if j in lst1] print(common)
true
7b9a073898d2fcd5854326707e0ce0bd464449e1
muyisanshuiliang/python
/function/param_demo.py
2,612
4.1875
4
# 函数的参数分为形式参数和实际参数,简称形参和实参: # # 形参即在定义函数时,括号内声明的参数。形参本质就是一个变量名,用来接收外部传来的值。 # # 实参即在调用函数时,括号内传入的值,值可以是常量、变量、表达式或三者的组合: # 定义位置形参:name,age,sex,三者都必须被传值,school有默认值 def register(name, age, sex, school='Tsinghua'): print('Name:%s Age:%s Sex:%s School:%s' % (name, age, sex, school)) def foo(x, y, z=3, *args): print(x) print(y) print(z) print(args) return def foo1(x, y, z=3, **args): print(x) print(y) print(z) print(args) return # 用*作为一个分隔符号,号之后的形参称为命名关键字参数。对于这类参数,在函数调用时,必须按照key=value的形式为其传值,且必须被传值 # 另外,如果形参中已经有一个args了,命名关键字参数就不再需要一个单独的*作为分隔符号了 def register1(name, age, *args, sex='male', height): # def register1(name, age, *, sex, height): print('Name:%s Age:%s Sex:%s Height:%s Other:%s' % (name, age, sex, height, args)) x = 1 def outer(): # 若要在函数内修改全局名称空间中名字的值,当值为不可变类型时,则需要用到global关键字 # global x x = 2 def inner(): # 函数名inner属于outer这一层作用域的名字 # 对于嵌套多层的函数,使用nonlocal关键字可以将名字声明为来自外部嵌套函数定义的作用域(非全局) nonlocal x x = 3 print('inner x:%s' % x) inner() print('outer x:%s' % x) print("全局变量修改前 x = %d" % x) outer() print("全局变量修改后 x = %d" % x) # register() # TypeError:缺少3个位置参数 # register(sex='male', name='lili', age=18) # register('lili', sex='male', age=18, school="Peking University") # 正确使用 # 实参也可以是按位置或按关键字的混合使用,但必须保证关键字参数在位置参数后面,且不可以对一个形参重复赋值 # register(name='lili',18,sex='male') #SyntaxError: positional argument follows keyword argument:关键字参数name=‘lili’在位置参数18之前 # register('lili',sex='male',age=18,name='jack') #TypeError: register() got multiple values for argument 'name':形参name被重复赋值 # foo(1, 2, 3, 4, 5, 6, 7) # L = [3, 4, 5] # foo(1, 2, *L) # foo(1, 2, L) # dic = {'a': 1, 'b': 2} # foo1(1, 2, **dic) # register1('lili', 18, height='1.8m')
false
3a53ab12f8144942fbfcb56bbb56d407c32bdf3e
autumnalfog/computing-class
/Week 2/a21_input_int.py
345
4.21875
4
def input_int(a, b): x = 0 while x != "": x = input() if x.isdigit(): if int(x) >= a and int(x) <= b: return x print("You should input a number between " + str(a) + " and " + str(b) + "!") print("Try once more or input empty line to cancel input check.")
true
9fdc839e30c4eccbb829abfa30178545f2f3f7b3
sheayork/02A-Control-Structures
/E02a-Control-Structures-master/main06.py
719
4.5
4
#!/usr/bin/env python3 import sys assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') color = input("What is my favorite color? ") if (color.lower().strip() == 'red'): print('Correct!') else: print('Sorry, try again.') ##BEFORE: Same as before, but some people may put spaces in-between letter or right after typing something ## (I know I have a bad habit of doing the latter when it comes to typing papers). So basically the program ## will remove those spaces and change everything to lowercase letters to tell if the answer ## is right or not. ##AFTER: It didn't do it for spaces in-between letters, but otherwise I was correct.
true
b93667bb58dfc610850d6ffa407ee418af6f44b0
Mamedefmf/Python-Dev-Course-2021
/magic_number/main.py
1,233
4.15625
4
import random def ask_number (min, max): number_int = 0 while number_int == 0: number_str = input(f"What is the magic number ?\nType a number between {min} and {max} : ") try: number_int = int(number_str) except: print("INPUT ERROR: You need to type a valid number") else: if number_int < min or number_int > max: print(f"INPUT ERROR: You must give a number between {min} and {max}") number_int = 0 return number_int MIN_NUMBER = 1 MAX_NUMBER = 10 MAGIC_NUMBER = random.randint(MIN_NUMBER, MAX_NUMBER) NB_LIVES = 4 number = 0 lives = NB_LIVES while not number == MAGIC_NUMBER and lives > 0: print(f"You have {lives} attempts left") number = ask_number(MIN_NUMBER, MAX_NUMBER) if number > MAGIC_NUMBER: print(f"{number} is greater than the Magic Number") lives -= 1 # subtract 1 live elif number < MAGIC_NUMBER: print(f"{number} is lower than the Magic Number") lives = lives - 1 # subtract 1 live else: print(f"You Won! the Magic Number is {MAGIC_NUMBER}\n Congratulations !!!") if lives == 0: print(f"You Lost!\nThe magic number was: {MAGIC_NUMBER}")
true
2a2ae134cceba04732db0f61fb19f83221ca3f1d
pranavkaul/Coursera_Python_for_Everybody_Specialization
/Course-1-Programming for everybody-(Getting started with Python/Assignment_6.py
999
4.3125
4
#Write a program to prompt the user for hours and rate per hour using input to compute gross pay. #Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. #Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. #The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). #You should use input to read a string and float() to convert the string to a number. #Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. #Do not name your variable sum or use the sum() function. def computepay(h,r): if h > 40: total = (((1.5 * r) * (h-40)) + (40 * r)) else: total = h * r return total hours = input('Hours') h = float(hours) rate = input('Rate') r = float(rate) total = computepay(h,r) print ("Pay",total)
true
412e2228c42ecdd818ffc52c0ebad6ef7e5035ad
vid083/dsa
/Python_Youtube/type.py
241
4.1875
4
value = int(input('Input a value: ')) if type(value) == str: print(value, 'is a string') elif type(value) == int: print(value, 'is a integer') elif type(value) == list: print(value, 'is a list') else: print(value, 'is none')
false
050611de1ceb8e48c8ee2f79ca721147e5a4f0cb
zhouyuhangnju/freshLeetcode
/Sort Colors.py
1,153
4.21875
4
def sortColors(nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ def quicksort(nums): def subquicksort(nums, start, end): if start >= end: return p = nums[start] i, j, direction = start, end, -1 while i < j: if direction == -1: if nums[j] < p: nums[i] = nums[j] i += 1 direction = 1 else: j -= 1 elif direction == 1: if nums[i] > p: nums[j] = nums[i] j -= 1 direction = -1 else: i += 1 assert i == j nums[i] = p subquicksort(nums, start, i - 1) subquicksort(nums, i + 1, end) subquicksort(nums, 0, len(nums)-1) quicksort(nums) if __name__ == '__main__': colors = [2,1,2,3,1,1] sortColors(colors) print colors
false
fb801c2f3b6afaab1a64650d8a10811d0726a5e7
wohao/cookbook
/counter1_12.py
563
4.15625
4
from collections import Counter words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] word_counters = Counter(words) top_three = word_counters.most_common(3) print(top_three) morewords = ['why','are','you','not','looking','in','my','eyes'] # for word in morewords: # word_counters[word] += 1 word_counters.update(morewords) print(word_counters['eyes'])
false
df4a4165ed70cee917e537eb19b1ed040703dbc7
Craby4GitHub/CIS129
/Mod 2 Pseudocode 2.py
2,879
4.3125
4
######################################################################################################################## # William Crabtree # # 27Feb17 # # Purpose: To figure out what the user will do for a week long vaction based on certain perferances # # and money avaiablity. # ######################################################################################################################## # Setting trip values florence = 1500 staycation = 1400 camping = 240 visitingParents = 100 kayakinginLake = 100 print("Oh, you are going on a vacation? Lucky you!") print("So we need to ask how much money you have to spend on this vacation") totalMoney = int(input("What disposable income do you have for this trip? ")) print("Ok, now that we know how much you have, lets figure out what some of your perferences are.") # Then we start asking questions goingAbroad = input("What about going abroad? ") if goingAbroad == "y": if florence <= totalMoney: print("Hey, you can go to Florence!") print("Going to Florence will cost a total of", florence) else: print("You can't go abroad because it will cost", florence) drivingLongDistance = input("Are you willing or capable of driving a long distance? ") if drivingLongDistance == "y": alone = input("Do you want to be alone? ") if alone == "y": if kayakinginLake <= totalMoney: print("You can go Kayaking in a remote lake.") print("That will only cost you gass money in the total of", kayakinginLake) else: print("You can't afford Kayaking in a lake becauseit costs", kayakinginLake) if camping <= totalMoney: print("You can go camping in a park.") print("That will cost you a total of", camping) else: print("You can't go camping because it costs", camping) if alone == "n": if visitingParents <= totalMoney: print("You can vist your parents, they miss you.") print("The only thing you need to buy is gas with a total cost of", visitingParents) else: print("You can't visit your parents because it costs", visitingParents) elif drivingLongDistance == "n": if staycation <= totalMoney: print("Hey, you can do a Staycation at a nearby resort.") print("A Staycation will cost you a total of", staycation) else: print("You cant do a Staycation because it costs", staycation)
true
4b1ae200aa26d0259e03ec346abdb42c4671b26b
Craby4GitHub/CIS129
/Final/Final.py
2,265
4.1875
4
######################################################################################################################## # William Crabtree # # 26Apr17 # # Purpose: The magic Triangle! # ######################################################################################################################## # Create list to show user where their input goes usersNum = ["First Entry", "Second Entry", "Third Entry"] genNum = ['Empty', 'Empty', 'Empty'] # Define how the triangle prints out def triangle(): # Basically, centering of the triangle so it always looks like a triangle fourth = '({}) [{}] ({})'.format(genNum[0], usersNum[1], genNum[2]) second = '[{}]'.format(usersNum[2]).center(int(len(fourth)/2), ' ') third = '[{}]'.format(usersNum[0]).center(int(len(fourth)/2), ' ') first = '({})'.format(genNum[1]).center(int(len(second) + len(third)), ' ') print(first) print(second, end="") print(third) print(fourth) def UserLoop(): # Loop three times for i in range(3): # Error Catch try: # Ask user for a number number = int(input("Enter a number between -40 and 40: ")) # if users number is less than -40 or greater than 40, kick em out if -40 <= number <= 40: usersNum[i] = number else: print("Number was not in the correct range.") print(len(usersNum)) exit() except ValueError: print("You did not enter a valid number.") exit() def Math(): # Get the total sum of numbers inputted and half it totalSum = int(sum(usersNum))/2 # Subtract the sum from the opposite number and input that value into genNum for generatedNumber in range(3): genNum[generatedNumber] = totalSum - int(usersNum[generatedNumber]) print("Here is the triangle:") triangle() UserLoop() Math() print("Here is your final triangle.") triangle()
true
f5f85d737006dc462254a2926d4d7db88db72cb6
WarrenJames/LPTHWExercises
/exl9.py
1,005
4.28125
4
# Excercise 9: Printing, Printing, Printing # variable "days" is equal to "Mon Tue Wed Thu Fri Sat Sun" days = "Mon Tue Wed Thu Fri Sat Sun" # variable "months" is Jan Feb Mar Apr May Jun Aug seperated by \n # \n means words written next will be printed on new a line months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nAug" # prints string of text "Here are the days: " and varible, days print "Here are the days: ", days # prints as "Here are the days: Mon Tue Wed Thu Fri Sat Sun" print "Here are the months: ", months # prints as "Here are the months: # Jan # Feb # Mar # Apr # Jun # Aug # prints """ triple double-quotes which is a long string capable of printing on multiple lines. print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5 , or 6. """ # prints as # "There's something going on here. # With the three double-quotes. # We'll be able to type as much as we like. # Even 4 lines if we want, or 5 , or 6."
true
e6f1bf912c575ed81b4b0631514ee67943a26f2f
WarrenJames/LPTHWExercises
/exl18.py
1,977
4.875
5
# Excercise 18: Names, Variables, Code, Functions # Functions do three things: # They name pieces of code the way variables name strings and numbers. # They take arguments the way your scripts take argv # Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands" # First we tell python we want to make a function using def for "define". # On the same line as def we give the function a name. In this case we just # called it print_two but it could also be "peanuts". It doens't matter, # except that the function should have a short name that says what it does. # without the asterisk, python will believe print_two accepts 1 variable. # Tells python to take all the arguments to the function and then put them in # args as a list. It's like agrv but for functions. not used too # often unless specifically needed ## def print_two(*args): ## arg1, arg2 = args ## print "arg1: %r, arg2: %r" % (arg1, arg2) # okay that *args is actually pointless # define(function) name is print_two_again(arg1, arg2): <-- don't forget the ":" # it tells what print_two_again consists of, which so happens to be printing # "Senor: (raw modulo), El: (raw modulo)" % modulo is (arg1, arg2) or # (James, Warren) def print_two_again(arg1, arg2): print "Senor: %r, El: %r" % (arg1, arg2) # this just takes one argument # define(function) print_one(variable arg1 which equals First): <-- consists of # print "the: %raw modulo" raw modulo is arg1 which is "first" def print_one(arg1): print "the: %r" % arg1 # this one takes no arguments # define print_none(): empty call expression consists of printing # "I got nothin'." def print_none(): print "I got nothin'." ## print_two("James","Warren") # lines 43 to 45 all call functions # calls print_two_again("James", "Warren") for arg1 and arg2 # calls print_one("First!") for arg1 # calls print_none() with no arguments print_two_again("James","Warren") print_one("First!") print_none()
true
fd90e5312f0798ca3eb88c8139bdd2fe17786654
SaloniSwagata/DSA
/Tree/balance.py
1,147
4.15625
4
# Calculate the height of a binary tree. Assuming root is at height 1 def heightTree(root): if root is None: return 0 leftH = heightTree(root.left) rightH = heightTree(root.right) H = max(leftH,rightH) # height of the tree will be the maximum of the heights of left subtree and right subtree return H+1 # +1 for the contribution of root # Check if tree is balanced or not def BalanceTree(root): if root is None: return True leftH = heightTree(root.left) rightH = heightTree(root.right) if abs(leftH-rightH)>1: return False isLeftBalance = BalanceTree(root.left) isRightBalance = BalanceTree(root.right) if isLeftBalance and isRightBalance: return True else: return False # Check if tree is balanced or not using single function def isBalanced(root): if root is None: return 0,True lh, leftisB = isBalanced(root.left) rh, rightisB = isBalanced(root.right) h = max(lh,rh)+1 if abs(lh-rh)>1: return h,False if leftisB and rightisB: return h,True else: return h,False
true
4af84efdf7b997185c340f2b69e7873d5b87df73
SaloniSwagata/DSA
/Tree/BasicTree.py
1,377
4.1875
4
# Creating and printing a binary tree # Creating a binary tree node class BinaryTreeNode: def __init__(self,data): self.left = None self.data = data self.right = None # Creating a tree by taking input tree wise (i.e, root - left subtree - right subtree) # For None, the user enters -1 def FullTreeInput(): rootdata = int(input()) if rootdata==-1: return None root = BinaryTreeNode(rootdata) leftChild = FullTreeInput() rightChild = FullTreeInput() root.left = leftChild root.right = rightChild return root # Printing tree simple way def printTree(root): if root==None: return print(root.data) printTree(root.left) printTree(root.right) # Detailed printing of tree def printDetailedTree(root): if root == None: return print(root.data, end=":") if root.left != None: print("L ",root.left.data, end=" ,") if root.right!=None: print("R ",root.right.data) print() printDetailedTree(root.left) printDetailedTree(root.right) # Counting the number of nodes in tree def numnodes(root): if root == None: return 0 left = numnodes(root.left) right= numnodes(root.right) return 1+left+right btn1 = BinaryTreeNode(2) btn2 = BinaryTreeNode(3) btn3 = BinaryTreeNode(4) btn1.left = btn2 btn1.right = btn3
true
c868093ac8ba3e14bad9835728fcc45598e0dfd5
SaloniSwagata/DSA
/Tree/levelOrder.py
1,309
4.25
4
# Taking input level order wise using queue # Creating a binary tree node class BinaryTreeNode: def __init__(self,data): self.left = None self.data = data self.right = None import queue # Taking Level Order Input def levelInput(): rootData = int(input("Enter the root node data: ")) if rootData ==-1: return None root = BinaryTreeNode(rootData) q = queue.Queue() q.put(root) while not(q.empty()): current_node = q.get() leftdata = int(input("Enter the left node data: ")) if leftdata!=-1: leftnode = BinaryTreeNode(leftdata) current_node.left = leftnode q.put(leftnode) rightdata = int(input("Enter the right node data: ")) if rightdata!=-1: rightnode = BinaryTreeNode(rightdata) current_node.right = rightnode q.put(rightnode) return root # Level Order Output def levelInput(root): if root is None: print("Empty tree") else: q = queue.Queue() q.put(root) while not(q.empty()): current_node = q.get() if current_node is not None: print(current_node.data,end=" ") q.put(current_node.left) q.put(current_node.right)
true
dbd90779db40037c1cdf29d85485c84b397405fc
Sudeep-K/hello-world
/Automating Tasks/Mad Libs.py
1,445
4.5
4
#! python ''' Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. The program would find these occurrences and prompt the user to replace them. The results should be printed to the screen and saved to a new text file. ''' import re #textFile = input('Enter the name of path of your file:)') #TODO: read the content of file fileObject = open('F:\\python\\purre.txt') text = fileObject.read() fileObject.close() #TODO: replace the occurences of word ADJECTIVE, NOUN, ADVERB, or VERB appearing in the text file. adjective = input('Enter an adjective') noun1 = input('Enter a noun') verb = input('Enter a verb') noun2 = input('Enter a noun') #TODO: create regex to replace above occurences in text file #replace occurence of adjective text = re.sub(r'\b{}\b'.format('ADJECTIVE'), adjective, text) #replace occurence of noun text = re.sub(r'^(.*?)\b{}\b'.format('NOUN'), r'\1{}'.format(noun1), text) #replace occurence of verb text = re.sub(r'\b{}\b'.format('VERB'), verb, text) #replace occurence of noun text = re.sub(r'^(.*?)\b{}\b'.format('NOUN'), r'\1{}'.format(noun2), text) #TODO: print result to the screen print(text) #TODO: save result to the file fileObject = open('F:\\python\\textfile.txt', 'w') fileObject.write(text) fileObject.close() input('Enter \'ENTER\' to exit (:')
true
e10c4cd35fce90bc44dbb4dd3ffaf75b13adcaa9
harishvinukumar/Practice-repo
/Break the code.py
1,503
4.28125
4
import random print('''\t\t\t\t\t\t\t\t### --- CODEBREAKER --- ### \t\t\t\t\t1. The computer will think of 3 digit number that has no repeating digits. \t\t\t\t\t2. You will then guess a 3 digit number \t\t\t\t\t3. The computer will then give back clues, the possible clues are: \t\t\t\t\tClose: You've guessed a correct number but in the wrong position \t\t\t\t\tMatch: You've guessed a correct number in the correct position \t\t\t\t\tNope: You haven't guess any of the numbers correctly \t\t\t\t\t4. Based on these clues you will guess again until you break the code with a perfect match!''') digits = list(range(10)) random.shuffle(digits) list1 = digits[:3] #print(list1) string1 = "" random.shuffle(list1) for i in list1: string1 = string1 + str(i) # Another hint: string2 = "123" while string1 != string2: guess = int(input("What is your guess?: ")) string2 = str(guess) if string1[0] == string2[0]: print("Match (in first position!)") if string1[1] == string2[1]: print("Match (in second position!)") if string1[2] == string2[2]: print("Match (in third position!)") if (string2[0] in string1[1:]) or (string2[2] in string1[:2]) or (string2[1] == string1[0] or string2[1] == string1[2]): print("Close") if (string2[0] not in string1) and (string2[1] not in string1) and (string2[2] not in string1): print("Nope") if string1 == string2: print("You Broke the Code! (Code: {})".format(string1)) break
true
af069f0404ed5594b2fb77da8613ebda76b8c040
DreamHackchosenone/python-algorithm
/binary_tree/traversing.py
1,311
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/19 22:10 class TreeNode(object): # 定义树结构 def __init__(self, root=None, left=None, right=None): self.root = root self.left = left self.right = right def preorder_traverse(tree): # 递归遍历顺序:根->左->右 if tree is None: return print(tree.root) preorder_traverse(tree.left) preorder_traverse(tree.right) def inorder_traverse(tree): # 递归遍历顺序:左->根->右 if tree is None: return inorder_traverse(tree.left) print(tree.root) inorder_traverse(tree.right) def postorder_treverse(tree): # 递归遍历顺序:左->右->根 if tree is None: return postorder_treverse(tree.left) postorder_treverse(tree.right) print(tree.root) if __name__ == '__main__': node = TreeNode("A", TreeNode("B", TreeNode("D"), TreeNode("E") ), TreeNode("C", TreeNode("F"), TreeNode("G") ) ) preorder_traverse(node) inorder_traverse(node) postorder_treverse(node)
false
2b25649637cefbdec2e8e389202a08fd82dbf1f0
ramyagoel98/acadview-assignments
/assignment11.py
651
4.28125
4
#Regular Expressions: #Question 1: Valid Emaild Address: import re as r email = input("Enter the E-mail ID: ") matcher = r.finditer('^[a-z][a-zA-Z0-9]*[@](gmail.com|yahoo.com)', email) count = 0 for i in matcher: count += 1 if count == 1: print('Valid E-mail Address') else: print('Invalid E-mail Address') #Question 2: Valid Phone Number: import re as r number = str(input('Enter the phone number: ')) matcher = r.finditer('^[+][9][1][-][6-9][\d]{9}', number) count = 0 for i in matcher: count += 1 if count == 1: print('Valid Phone Number.') else: print("Invalid Phone Number')
false
97aa8452a4bab355d139eed764ebfd5f692ab06b
shaikzia/Classes
/yt1_cor_classes.py
691
4.21875
4
# Program from Youtube Videos - corey schafer """ Tut1 - Classes and Instances """ #Defining the class class Employee: def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) # Creating an instances of the class emp1 = Employee('Muhammad', 'Faiz', 60000) emp2 = Employee('Zairah', 'Shaik',50000) emp3 = Employee('Muhammad', 'Saad',50000) #Printing the email print(emp1.email) print(emp2.email) print(emp3.email) # Print the Full Name print(emp1.fullname()) print(emp2.fullname()) print(emp3.fullname())
true
94d737b1eb5d4fa7d9714e85c7c3fd2f925077a0
lukasbindreiter/enternot-pi
/enternot_app/pi/distance.py
774
4.125
4
from math import sin, cos, sqrt, atan2, radians def calculate_distance(lon1: float, lat1: float, lon2: float, lat2: float) -> float: """ Calculate the distance in meters between the two given geo locations. Args: lon1: Longitude from -180 to 180 lat1: Latitude from -90 to 90 lon2: Longitude from -180 to 180 lat2: Latitude from -90 to 90 Returns: Distance in meters """ earth_radius = 6371000 # meters delta_lon = radians(lon2 - lon1) delta_lat = radians(lat2 - lat1) a = sin(delta_lat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin( delta_lon / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = earth_radius * c return distance
false
4e592149e3f98f2d428bb5a37dd85431ad7be763
Deepkumarbhakat/Python-Repo
/factorial.py
206
4.25
4
#Write a program to find the factorial value of any number entered through the keyboard n=5 fact=1 for i in range(0,n,-1): if i==1 or i==0: fact=fact*1 else: fact=fact*i print(fact)
true
866d38f72f63b3d2d1ec87bfd1b330f04cf33635
Deepkumarbhakat/Python-Repo
/Write a program to check if a year is leap year or not. If a year is divisible by 4 then it is leap year but if the year is century year like 2000, 1900, 2100 then it must be divisible by 400..py
320
4.28125
4
#Write a program to check if a year is leap year or not. y=int(input('enter any year : ')) if (y % 4 == 0): if (y % 100 == 0): if (y % 400 == 0): print('leap year') else: print('not a leap year') else: print('leap year') else: print('not a leap year')
false
27cd32606dddc864ce68c35f824a533e1467419d
Deepkumarbhakat/Python-Repo
/function3.py
243
4.28125
4
# Write a Python function to multiply all the numbers in a list. # Sample List : (8, 2, 3, -1, 7) # Expected Output : -336 def multiple(list): mul = 1 for i in list: mul =mul * i print(mul) list=[8,2,3,-1,7] multiple(list)
true
3a98e9a55e3217f3f4faa76b71ab08a75adf1d8e
Deepkumarbhakat/Python-Repo
/function9.py
434
4.25
4
# Write a Python function that takes a number as a parameter and check the number is prime or not. # Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors # other than 1 and itself. def prime(num): for i in range(2,num//2): if num % i == 0: print("not prime") break else: print("prime") num=int(input("enter any number : ")) prime(num)
true
63507dcd1e550687bbc7d6108211bd15cf2164af
Deepkumarbhakat/Python-Repo
/string15.py
282
4.15625
4
# Write a Python program that accepts a comma separated sequence of words as input # and prints the unique words in sorted form (alphanumerically). # Sample Words : red, white, black, red, green, black # Expected Result : black, green, red, white,red st=("input:"," , ") print(st)
true
5ed7472af54b4e92e4f8b8160dbdfa42fc8a0c7b
deepabalan/byte-of-python
/functions/function_varargs.py
720
4.15625
4
# When we declare a starred parameter such as *param, then all the # positional arguments from that point till the end are collected as # a tuple called 'param'. # Similarly, when we declare a double-starred parameter such as **param, # then all the keyword arguments from that point till end are collected # as a dictionary called 'param'. def total(a=5, *numbers, **phonebook): print ('a', a) # iterate through all the items in tuple for single_item in numbers: print('single_item', single_item) # iterate through all the items in dictionary for first_part, second_part in phonebook.items(): print(first_part, second_part) total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560)
true
e2f198706079a03d282121a9959c8e913229d07c
hazydazyart/OSU
/CS344/Homework2/Problem4.py
959
4.15625
4
#Megan Conley #conleyme@onid.oregonstate.edu #CS344-400 #Homework 2 import os import sys import getopt import math #Function to check if a number is prime #Arguments: int #Return: boolean #Notes: a much improved function to find primes using the sieve, this time using the #square root hint from Homework 1. def isPrime(input): for i in range (2, int(math.sqrt(input))+1): if (input % i) == 0: return False return True #Function which finds and prints nth prime #Arguments: passed from command line #Return: none def findPrime(argv): count = 0 val = 2 if len(sys.argv) != 2: print 'Usage: python Problem4.py <number>' sys.exit(2) userInput = int(sys.argv[1]) #Loops until the number of primes founds reaches the user's input upper bound and prints it while count < userInput: if isPrime(val): count += 1 if count == userInput: print 'The ' + str(userInput) + 'th prime is ' + str(val) val += 1 if __name__ == '__main__': findPrime(sys.argv[1:])
true
a5b0bcd93668247dbaeaa869de1e1f136aa32f28
emilyscarroll/MadLibs-in-Python
/MadLibs.py
593
4.21875
4
# Story: There once was a very (adjective) (animal) who lived in (city). He loved to eat (type of candy). #1) print welcome #2) ask for input for each blank #3) print story print("Hello, and welcome to MadLibs! Please enter the following words to complete your story.") adj = input("Enter an adjective: ") animal = input("Enter a type of animal: ") city = input( "Enter the name of a city: ") candy = input("Enter a type of candy: ") \n print("Thank you! Your story is:") \n print("There once was a very " + adj + " " + animal + " who lived in " + city + ". He loved to eat " + candy + ".")
true
4f82dfb7a6b951b9a5fed1546d0743adb4109fbd
kkeller90/Python-Files
/newton.py
335
4.375
4
# newtons method # compute square root of 2 def main(): print("This program evaluates the square root of 2 using Newton's Method") root = 2 x = eval(input("Enter number of iterations: ")) for i in range(x): root = root - (root**2 - 2)/(2*root) print(root) main()
true
35a1dde2f54c79e8bdb80f5cd0b0d727c3ee1e4f
Rurelawati/pertemuan_12
/message.py
1,000
4.1875
4
# message = 'Hello World' # print("Updated String :- ", message[:6] + 'Python') # var1 = 'Hello World!' # penggunaan petik tunggal # var2 = "Python Programming" # penggunaan petik ganda # print("var1[0]: ", var1[0]) # mengambil karakter pertama # print("var2[1:5]: ", var2[1:5]) # karakter ke-2 s/d ke-5 # Nama : Rurelawati # Kelas : TI.20.A2 # Mata Kuliah : Bahasa Pemrograman txt = 'Hello World' print(80*"=") print(len(txt)) print(txt[10]) # Ambil Karakter Terakhir print(txt[2:5]) # Ambil Karakter index ke-2 sampai index ke-4 (llo) print(txt[:5]+'World') # Hilangkan Spasi pada text menjadi (HelloWorld) print(txt.upper()) # Merubah txt menjadi huruf besar print(txt.lower()) # Merubah txt menjadi huruf kecil print(txt.replace("H", "J")) # Merubah (H) menjadi (J) print(80*"=") # Latihan 2 print("============>>>>> LATIHAN 2") print("______________________________") umur = 20 txt = 'Hello, nama saya Mitchel, umur saya {} tahun' print(txt.format(umur)) print(80*"=")
false
bb83df21cb7dc89440d61876288bfd6bafce994d
ZzzwyPIN/python_work
/chapter9/Demo9_2.py
1,137
4.28125
4
class Car(): """一次模拟汽车的简单尝试""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """返回整洁的描述性信息""" long_name = str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading)+" miles on it.") def updat_odometer(self,mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self,miles): if miles >= 0: self.odometer_reading += miles else: print("You can't roll back the odometer!") # ~ my_new_car = Car('audi','a4','2016') # ~ print(my_new_car.get_descriptive_name()) # ~ my_new_car.read_odometer() # ~ my_new_car.odometer_reading = 23 # ~ my_new_car.read_odometer() # ~ my_new_car.updat_odometer(80) # ~ my_new_car.read_odometer() # ~ my_new_car.increment_odometer(100) # ~ my_new_car.read_odometer() # ~ my_new_car.updat_odometer(38) # ~ my_new_car.increment_odometer(-1)
true
2785927c8c0c73534d66a3e2742c334e3c9c67bd
rocksolid911/lucky13
/weight_change.py
314
4.21875
4
weight = int(input("enter your weight: ")) print(f'''your weight is {weight} is it in pound or kilos ?''') unit = input("(l)pound or (k)kilogram: ") if unit.upper() == "L": convert = weight * 0.45 print(f"you are {convert} kilos") else: convert = weight / 0.45 print(f"you are {convert} pound")
false
eac160ec897eed706fd6924ef2c55bef93159034
AlirieGray/Tweet-Generator
/qu.py
1,052
4.21875
4
from linkedlist import LinkedList from linkedlist import Node class Queue(LinkedList): def __init__(self, iterable=None): super().__init__(iterable) def enqueue(self, item): """Add an object to the end of the Queue.""" self.append(item) def dequeue(self): """Remove and return the object at the beginning of the Queue.""" if self.is_empty(): raise IndexError("Cannot dequeue from empty queue") temp = self.head.data self.head = self.head.next return temp def peek(self): if self.is_empty(): raise IndexError("Cannot peek from empty queue") return self.head.data def toTuple(self): q_list = [] current = self.head while current: q_list.append(current.data) current = current.next return tuple(q_list) if __name__ == '__main__': q = Queue(["Hello", "world,", "I", "am", "a", "queue!"]) print(q.toTuple()) while not q.is_empty(): print(q.dequeue())
true
09a979bccf9cce42b1fa77cf88cf8fa889037879
michaelworkspace/AdventOfCode2020
/day01.py
1,277
4.40625
4
from typing import List def find_product(inputs: List[int]) -> int: """Given a list of integers, if the sum of two element is 2020, return it's product.""" # This is the classic Two Sum problem # This is not good solution because it is O(n^2) # for x in INPUTS: # for y in INPUTS: # if x + y == 2020: # ans = x * y # return ans # This is the optimal solution because its time complexity is O(n) needs = {2020 - x for x in inputs} for num in inputs: if num in needs: ans = num * (2020-num) return ans """--- PART 2 --- """ def find_product_part2(inputs: List[int]) -> int: """Given a list of integers, if the sum of three element is 2020, return it's product.""" n = len(inputs) # This is the classic Three Sum problem # Naive run time is O(n^3) cube which is not very efficient for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if inputs[i] + inputs[j] + inputs[k] == 2020: ans = inputs[i] * inputs[j] * inputs[k] return ans with open("Inputs/day01.txt") as f: inputs = [int(line.strip()) for line in f] print(find_product(inputs)) print(find_product_part2(inputs))
true
0ad185da2701617e9580000faad35f2c31df8c9a
YasmineCodes/Interview-Prep
/recursion.py
2,641
4.3125
4
# Write a function fib, that finds the nth fibonacci number def fib(n): assert n >= 0 and int(n) == n, "n must be a positive integer" if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) print("The 4th fibonacci number is: ", fib(4)) # 2 print("The 10th fibonacci number is: ", fib(10)) # 34 # Write a recursive function to find the sum all the digits in a positive number n # For example: the number 223 shoudl return 7 def sum_digits(n): # Constraint assert n >= 0 and int(n) == n, "n must be a positive int" # Base case if n < 10: return n else: # recursion case return n % 10 + sum_digits(int(n/10)) print("The sum of digits in the number 100 is: ", sum_digits(100)) # 1 print("The sum of digits in the number 112 is: ", sum_digits(11234)) # 11 print("The sum of digits in the number 23 is: ", sum_digits(23)) # 5 # Write recursive function that finds the Greates Common Denominator using Euclidean Algorithm (https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm) def gcd(n1, n2): assert int(n1) == n1 and int(n2) == n2, 'numbers must be integers' a = max(n1, n2) b = min(n1, n2) if a < 0: a = a*-1 if b < 0: b = b*-1 if a % b == 0: return b else: return gcd(b, a % b) print("The GCD for 8 and 12 is: ", gcd(8, 12)) print("The GCD for 10 and 85 is: ", gcd(20, 85)) print("The GCD for 48 and 18 is: ", gcd(48, 18)) # Write a function that uses recursion to find the binary representation of a number def binary(n): if n == 0: return "" else: return binary(int(n/2)) + str(n % 2) print("The binary representation of 10 is: ", binary(10)) # 1010 print("The binary representation of 13 is: ", binary(13)) # 1101 def binary2(n): if int(n/2) == 0: return n % 2 else: return n % 2 + 10*binary2(int(n/2)) print("Using binary2: The binary representation of 10 is: ", binary2(10)) # 1010 print("Using binary2: The binary representation of 13 is: ", binary2(13)) # 1101 # Write a recursive function called power that returns the base raised to the exponent # 2, 4 : 2 * power(2, 3) # 2 * power(2, 2) # 2 * power(2, 1) #2* power(2, 0) # 1 def power(base, exponent): if exponent == 0: return 1 else: return base * power(base, exponent-1) print("3 raised to the power of 0 is : ", power(3, 0)) # 1 print("2 raised to the power of 2 is : ", power(2, 2)) # 4 print("5 raised to the power of 4 is : ", power(2, 4)) # 625
true
e3382c4e700995d5decef3245d859372123decae
b21727795/Programming-with-Python
/Quiz2/quiz2_even_operation.py
596
4.3125
4
import sys def choose_evens(input_string): evens = [int(element) for element in input_string.split(',') if(int(element)> 0 and int(element) % 2 == 0) ] all_numbers = [int(element) for element in input_string.split(',') if int(element)> 0] even_number_rate = sum(evens) / sum(all_numbers) print("Even Numbers: "+'"'+','.join([str(x) for x in evens])+'"') print("Sum of Even Numbers:", str(sum(evens))) print("Even Number Rate:{:.3f}".format(even_number_rate)) def main(input_string): choose_evens(input_string) if __name__ == "__main__": main(sys.argv[1])
false
aa92573b123c0f334eca8304adae5b1410f108e5
Xia-Sam/hello-world
/rock paper scissors game against computer.py
1,714
4.3125
4
import random rand_num=random.randint(1,3) if rand_num==1: com_side="rock" elif rand_num==2: com_side="paper" else: com_side="scissors" i=0 while i<5: print("You can input 'stop' at anytime to stop the game but nothing else is allowed.") user_side=input("Please input your choice (R P S stands for rock paper scissors respectively):") if user_side=="R" or user_side=="P" or user_side=="S": if user_side=="R": if rand_num==1: print(" Game is a tie. Try again. 5 more chances") elif rand_num==2: print("Computer win. You lose. ") i+=1 print(5-i," chances left.") else: print("You win. You can continue playing.") elif user_side=="P": if rand_num==2: print(" Game is a tie. Try again. 5 more chances") elif rand_num==1: print("You win. You can continue playing.") else: print("Computer win. You lose. ") i += 1 print(5 - i, " chances left.") else: if rand_num==1: print("Computer win. You lose. ") i += 1 print(5 - i, " chances left.") elif rand_num==2: print("You win. You can continue playing.") else: print(" Game is a tie. Try again. 5 more chances") elif user_side=="stop": break else: print("You can only input R, S or P!! ") print("Try again. You only have 5 chances totally. ") i+=1 print(5-i," chances left") print("Game over. Thank you for playing my game.")
true
2d30aaf0eddd3a054f84063e3d6971b4933097af
irosario1999/30days-of-python
/day_2/variables.py
1,014
4.125
4
from math import pi print("Day 2: 30 days of python") firstName = "ivan" lastName = "Rosario" fullName = firstName + " " + lastName country = "US" city = "miami" age = "21" year = "2020" is_married = False is_true = True is_light_on = False i, j = 0, 3 print(type(firstName)) print(type(lastName)) print(type(fullName)) print(type(country)) print(type(city)) print(type(age)) print(type(year)) print(type(is_married)) print(type(is_true)) print(type(is_light_on)) print(type(i)) print(type(j)) print("firstName length:", len(firstName)) print("diff of firstname and lastname", len(firstName) - len(lastName)) num_one, num_two = 5, 4 _total = num_one + num_two _diff = num_two - num_one _product = num_two * num_one _division = num_one / num_two _floor_division = num_two % num_one radius = input("insert radius: ") area_of_circle = pi * radius ** 2 circum_of_circle = 2 * pi * radius print(circum_of_circle) print(area_of_circle) # name = input("firstname: ") # last = input("lastName: ") help("keywords")
false
55ae7ae4ad64c690800e9d2a9d37684eb3069bb9
andkoc001/pands-problem-set
/06-secondstring.py
1,379
4.15625
4
# Title: Second Strig # Description: Solution to problem 6 - program that takes a user input string and outputs every second word. # Context: Programming and Scripting, GMIT, 2019 # Author: Andrzej Kocielski # Email: G00376291@gmit.ie # Date of creation: 10-03-2019 # Last update: 10-03-2019 ### # Prompt for the user; definition of a new variable "sentence" for the user's input # Intermediate test of the program - predefined sentence # sentence = "1abc 2def 3geh 4ijk 5lkm 6nop 7rst 8uwz" sentence = input("Please enter a sentence: ") # Intermediate test of the program - prints out the user's input # print(type(sentence)) # print(sentence) # Calls method split method in order to split the user input into single words, separated by a space sentence.split() # Assignment of number of words in the sentence to variable n n = len(sentence.split()) # Intermediate test of the program - shows number of words in the sentence # print(n) # Joining the words by contanation - pre-definintion of empty (for now) variable, which will be subsequently updated as the program runs result_line = "" # Prints out odd words from the sentence for i in range(n): # Separation of odd and even words if i % 2 == 0: # this was original command that returned words in separate lines # print(sentence.split()[i]) result_line += (sentence.split()[i]) + " " print(result_line)
true
3cc0fcee11a7eea3411f26afebac5fea6eebd6b1
BlackJimmy/SYSU_QFTI
/mateig.py
427
4.15625
4
#this example shows how to compute eigen values of a matrix from numpy import * #initialize the matrix n = 5 a = zeros( (n, n) ) for i in range(n): a[i][i] = i if(i>0): a[i][i-1] = -1 a[i-1][i] = -1 #print the matrix print "The matrix is:" for i in range(n): print a[i] #compute the eigen values of the matrix (eigvalues, eigvectors) = linalg.eig(a) print "Its eigen values are:" print eigvalues
true
d7d9550e9acb11727564ba122a9427139f47a5e3
ode2020/bubble_sort.py
/bubble.py
388
4.1875
4
def bubble_sort(numbers): for i in range (len(numbers) - 1, 0, -1): for j in range (i): if numbers[j] > numbers[j+1]: temp = numbers[j] numbers[j] = numbers[j+1] numbers[j+1] = temp print(numbers) numbers = [5, 3, 8, 6, 7, 2] bubble_sort(numbers) print(numbers) print("The code executed successfully")
true
aa83f5258b80e1c403a25d30aeb96f2a8125ec73
ravalrupalj/BrainTeasers
/Edabit/Day 3.3.py
459
4.125
4
#Get Word Count #Create a function that takes a string and returns the word count. The string will be a sentence. #Examples #count_words("Just an example here move along") ➞ 6 #count_words("This is a test") ➞ 4 #count_words("What an easy task, right") ➞ 5 def count_words(txt): t = txt.split() return len(t) print(count_words("Just an example here move along")) print(count_words("This is a test")) print(count_words("What an easy task, right"))
true
9975f7dc75b81bbbe7cfdcd701f2e09335a3ce54
ravalrupalj/BrainTeasers
/Edabit/Emptying_the_values.py
1,532
4.4375
4
#Emptying the Values #Given a list of values, return a list with each value replaced with the empty value of the same type. #More explicitly: #Replace integers (e.g. 1, 3), whose type is int, with 0 #Replace floats (e.g. 3.14, 2.17), whose type is float, with 0.0 #Replace strings (e.g. "abcde", "x"), whose type is str, with "" #Replace booleans (True, False), whose type is bool, with False #Replace lists (e.g. [1, "a", 5], [[4]]), whose type is list, with [] #Replace tuples (e.g. (1,9,0), (2,)), whose type is tuple, with () #Replace sets (e.g. {0,"a"}, {"b"}), whose type is set, with set() #Caution: Python interprets {} as the empty dictionary, not the empty set. #None, whose type is NoneType, is preserved as None #Notes #None has the special NoneType all for itself. def empty_values(lst): l=[] for i in lst: if type(i)==int: l.append(0) elif type(i)==float: l.append(0.0) elif type(i)==str: l.append('') elif type(i)==bool: l.append(False) elif type(i)==list: l.append([]) elif type(i)==tuple: l.append(()) elif type(i)==set: l.append(set()) else: l.append(None) return l print(empty_values([1, 2, 3]) ) #➞ [0, 0, 0] print(empty_values([7, 3.14, "cat"]) ) #➞ [0, 0.0, ""] print(empty_values([[1, 2, 3], (1,2,3), {1,2,3}]) ) #➞ [[], (), set()] print(empty_values([[7, 3.14, "cat"]])) #➞ [[]] print(empty_values([None]) ) #➞ [None]
true
60a84a613c12d723ba5d141e657989f33930ab74
ravalrupalj/BrainTeasers
/Edabit/Powerful_Numbers.py
615
4.1875
4
#Powerful Numbers #Given a positive number x: #p = (p1, p2, …) # Set of *prime* factors of x #If the square of every item in p is also a factor of x, then x is said to be a powerful number. #Create a function that takes a number and returns True if it's powerful, False if it's not. def is_powerful(num): i=1 l=[] while i<=num: if num%i==0: l.append(i) i=i+1 return l print(is_powerful(36)) #➞ True # p = (2, 3) (prime factors of 36) # 2^2 = 4 (factor of 36) # 3^2 = 9 (factor of 36) print(is_powerful(27)) #➞ True print(is_powerful(674)) #➞ False #Notes #N/A
true
4dd2faade46f718a07aeba94270ea71ff90b5996
ravalrupalj/BrainTeasers
/Edabit/Is_the_Number_Symmetrical.py
462
4.4375
4
#Create a function that takes a number as an argument and returns True or False depending on whether the number is symmetrical or not. A number is symmetrical when it is the same as its reverse. def is_symmetrical(num): t=str(num) return t==t[::-1] print(is_symmetrical(7227) ) #➞ True print(is_symmetrical(12567) ) #➞ False print(is_symmetrical(44444444)) #➞ True print(is_symmetrical(9939) ) #➞ False print(is_symmetrical(1112111) ) #➞ True
true
885a0a3ce15dbf2504dd24ce14552a4e245b3790
ravalrupalj/BrainTeasers
/Edabit/Big_Countries.py
1,652
4.53125
5
#Big Countries #A country can be said as being big if it is: #Big in terms of population. #Big in terms of area. #Add to the Country class so that it contains the attribute is_big. Set it to True if either criterea are met: #Population is greater than 250 million. #Area is larger than 3 million square km. #Also, create a method which compares a country's population density to another country object. Return a string in the following format: #{country} has a {smaller / larger} population density than {other_country} class Country: def __init__(self, name, population, area): self.name = name self.population = population self.area = area # implement self.is_big self.is_big = self.population > 250000000 or self.area > 3000000 def compare_pd(self, other): # code this_density = self.population / self.area other_density = other.population / other.area if this_density > other_density: s_or_l = 'larger' else: s_or_l = 'smaller' return self.name + ' has a ' + s_or_l + ' population density than ' + other.name australia = Country("Australia", 23545500, 7692024) andorra = Country("Andorra", 76098, 468) print(australia.is_big ) #➞ True print(andorra.is_big ) #➞ False andorra.compare_pd(australia) #➞ "Andorra has a larger population density than Australia" #Notes #Population density is calculated by diving the population by the area. #Area is given in square km. #The input will be in the format (name_of_country, population, size_in_km2), where name_of_country is a string and the other two inputs are integers.
true
a22a66ffd651519956fc0f1ea0eb087a4146e8dd
ravalrupalj/BrainTeasers
/Edabit/Loves_Me_Loves_Me.py
1,034
4.25
4
#Loves Me, Loves Me Not... #"Loves me, loves me not" is a traditional game in which a person plucks off all the petals of a flower one by one, saying the phrase "Loves me" and "Loves me not" when determining whether the one that they love, loves them back. #Given a number of petals, return a string which repeats the phrases "Loves me" and "Loves me not" for every alternating petal, and return the last phrase in all caps. Remember to put a comma and space between phrases. def loves_me(num): l=['Loves me','Loves me not'] final_l=[] add=l[0] for i in range(0,num): final_l.append(add) if final_l[-1]==l[0]: add=l[1] else: add=l[0] final_l[-1]=final_l[-1].upper() return ', '.join(final_l) print(loves_me(3)) #➞ "Loves me, Loves me not, LOVES ME" print(loves_me(6) ) #➞ "Loves me, Loves me not, Loves me, Loves me not, Loves me, LOVES ME NOT" print(loves_me(1)) #➞ "LOVES ME" #Notes #Remember to return a string. #he first phrase is always "Loves me".
true
13b3a8a4d538ca1404902f5cc9d0d4cb5380f231
ravalrupalj/BrainTeasers
/Edabit/sum_of_even_numbers.py
698
4.1875
4
#Give Me the Even Numbers #Create a function that takes two parameters (start, stop), and returns the sum of all even numbers in the range. #sum_even_nums_in_range(10, 20) ➞ 90 # 10, 12, 14, 16, 18, 20 #sum_even_nums_in_range(51, 150) ➞ 5050 #sum_even_nums_in_range(63, 97) ➞ 1360 #Remember that the start and stop values are inclusive. def sum_even_nums_in_range(start, stop): count=0 for i in range(start,stop+1): if i%2==0: count=count+i return count #return sum(i for i in range(start, stop+1) if not i%2) print(sum_even_nums_in_range(10, 20) ) # 10, 12, 14, 16, 18, 20 print(sum_even_nums_in_range(51, 150) ) print(sum_even_nums_in_range(63, 97) )
true
7801a9735e3d51e4399ee8297d719d86eb44bc58
ravalrupalj/BrainTeasers
/Edabit/Recursion_Array_Sum.py
440
4.15625
4
#Recursion: Array Sum #Write a function that finds the sum of a list. Make your function recursive. #Return 0 for an empty list. #Check the Resources tab for info on recursion. def sum_recursively(lst): if len(lst)==0: return 0 return lst[0]+sum_recursively(lst[1:]) print(sum_recursively([1, 2, 3, 4])) #➞ 10 print(sum_recursively([1, 2]) ) #➞ 3 print(sum_recursively([1]) ) #➞ 1 print(sum_recursively([]) ) #➞ 0
true
207c144e096524b8de5e6d9ca11ce5cb4969d8e1
ravalrupalj/BrainTeasers
/Edabit/Letters_Only.py
496
4.25
4
#Letters Only #Write a function that removes any non-letters from a string, returning a well-known film title. #See the Resources section for more information on Python string methods. def letters_only(string): l=[] for i in string: if i.isupper() or i.islower(): l.append(i) return ''.join(l) print(letters_only("R!=:~0o0./c&}9k`60=y") ) #➞ "Rocky" print(letters_only("^,]%4B|@56a![0{2m>b1&4i4")) #➞ "Bambi" print(letters_only("^U)6$22>8p).") ) #➞ "Up"
true
4fad5f1ab4362dbc1119d1f72a85d6c91abdfa8f
ravalrupalj/BrainTeasers
/Edabit/The_Fibonacci.py
368
4.3125
4
#The Fibonacci Number #Create a function that, given a number, returns the corresponding Fibonacci number. #The first number in the sequence starts at 1 (not 0). def fibonacci(num): a=0 b=1 for i in range(1,num+1): c=a+b a=b b=c return c print(fibonacci(3) ) #➞ 3 print(fibonacci(7)) #➞ 21 print(fibonacci(12)) #➞ 233
true
5182829f043490134cb86a3962b07a791e7ae0cb
ravalrupalj/BrainTeasers
/Edabit/How_many.py
601
4.15625
4
#How Many "Prime Numbers" Are There? #Create a function that finds how many prime numbers there are, up to the given integer. def prime_numbers(num): count=0 i=1 while num: i=i+1 for j in range(2,i+1): if j>num: return count elif i%j==0 and i!=j: break elif i==j: count=count+1 break print(prime_numbers(10)) #➞ 4 # 2, 3, 5 and 7 print(prime_numbers(20)) #➞ 8 # 2, 3, 5, 7, 11, 13, 17 and 19 print(prime_numbers(30)) #➞ 10 # 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29
true
f07bfd91788707f608a580b702f3905be2bf201b
ravalrupalj/BrainTeasers
/Edabit/One_Button_Messagin.py
650
4.28125
4
# One Button Messaging Device # Imagine a messaging device with only one button. For the letter A, you press the button one time, for E, you press it five times, for G, it's pressed seven times, etc, etc. # Write a function that takes a string (the message) and returns the total number of times the button is pressed. # Ignore spaces. def how_many_times(msg): if len(msg)==0: return 0 current=msg[0] rest_of_string = msg[1:] char_int=ord(current)-96 return char_int+how_many_times(rest_of_string) print(how_many_times("abde")) # ➞ 12 print(how_many_times("azy")) # ➞ 52 print(how_many_times("qudusayo")) # ➞ 123
true
d9acdd4825dfd641d4eac7dd92d15b428b0e07f0
ravalrupalj/BrainTeasers
/Edabit/Iterated_Square_Root.py
597
4.5
4
#Iterated Square Root #The iterated square root of a number is the number of times the square root function must be applied to bring the number strictly under 2. #Given an integer, return its iterated square root. Return "invalid" if it is negative. #Idea for iterated square root by Richard Spence. import math def i_sqrt(n): if n < 0: return 'invalid' count = 0 while n >= 2: n **= 0.5 count += 1 return count print(i_sqrt(1)) #➞ 0 print(i_sqrt(2)) #➞ 1 print(i_sqrt(7)) #➞ 2 print(i_sqrt(27)) #➞ 3 print(i_sqrt(256)) #➞ 4 print(i_sqrt(-1) ) #➞ "invalid"
true
edb6aaff5ead34484d01799aef3df830208b574c
ravalrupalj/BrainTeasers
/Edabit/Identical Characters.py
460
4.125
4
#Check if a String Contains only Identical Characters #Write a function that returns True if all characters in a string are identical and False otherwise. #Examples #is_identical("aaaaaa") ➞ True #is_identical("aabaaa") ➞ False #is_identical("ccccca") ➞ False #is_identical("kk") ➞ True def is_identical(s): return len(set(s))==1 print(is_identical("aaaaaa")) print(is_identical("aabaaa") ) print(is_identical("ccccca")) print(is_identical("kk"))
true
da002bf4a8ece0c60f4103e5cbc92f641d27f573
ravalrupalj/BrainTeasers
/Edabit/Stand_in_line.py
674
4.21875
4
#Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove the first element of the list. The function should then return the updated list. #For an empty list input, return: "No list has been selected" def next_in_line(lst, num): if len(lst)>0: t=lst.pop(0) r=lst.append(num) return lst else: return 'No list has been selected' print(next_in_line([5, 6, 7, 8, 9], 1)) #➞ [6, 7, 8, 9, 1] print(next_in_line([7, 6, 3, 23, 17], 10)) #➞ [6, 3, 23, 17, 10] print(next_in_line([1, 10, 20, 42 ], 6)) #➞ [10, 20, 42, 6] print(next_in_line([], 6)) #➞ "No list has been selected"
true
b5255591c5a67f15767deee268a1972ca61497cd
ravalrupalj/BrainTeasers
/Edabit/Emphasise_the_Words.py
617
4.21875
4
#Emphasise the Words #The challenge is to recreate the functionality of the title() method into a function called emphasise(). The title() method capitalises the first letter of every word. #You won't run into any issues when dealing with numbers in strings. #Please don't use the title() method directly :( def emphasise(string): r='' for i in string.split(): t=(i[0].upper())+(i[1:].lower())+' ' r=r+t return r.rstrip() print(emphasise("hello world")) #➞ "Hello World" print(emphasise("GOOD MORNING") ) #➞ "Good Morning" print(emphasise("99 red balloons!")) #➞ "99 Red Balloons!"
true
6eceebf49b976ec2b757eee0c7907f2845c65afd
ravalrupalj/BrainTeasers
/Edabit/Is_String_Order.py
405
4.25
4
#Is the String in Order? #Create a function that takes a string and returns True or False, depending on whether the characters are in order or not. #You don't have to handle empty strings. def is_in_order(txt): t=''.join(sorted(txt)) return t==txt print(is_in_order("abc")) #➞ True print(is_in_order("edabit")) #➞ False print(is_in_order("123")) #➞ True print(is_in_order("xyzz")) #➞ True
true
56bf743185fc87230c9cb8d0199232d393757809
ravalrupalj/BrainTeasers
/Edabit/Day 2.5.py
793
4.53125
5
#He tells you that if you multiply the height for the square of the radius and multiply the result for the mathematical constant π (Pi), you will obtain the total volume of the pizza. Implement a function that returns the volume of the pizza as a whole number, rounding it to the nearest integer (and rounding up for numbers with .5 as decimal part). #vol_pizza(1, 1) ➞ 3 # (radius² x height x π) = 3.14159... rounded to the nearest integer. #vol_pizza(7, 2) ➞ 308 #vol_pizza(10, 2.5) ➞ 785 import math def vol_pizza(radius, height): t=(radius ** 2) * height *math.pi y=round(t,1) return round(y) print(vol_pizza(1, 1)) # (radius² x height x π) = 3.14159... rounded to the nearest integer. print(vol_pizza(7, 2)) print(vol_pizza(10, 2.5)) print(vol_pizza(15, 1.3))
true
d9d1a7dbd41fea7d00f7299ae6708fc46e21d42d
ravalrupalj/BrainTeasers
/Edabit/Day 4.4.py
510
4.46875
4
#Is It a Triangle? #Create a function that takes three numbers as arguments and returns True if it's a triangle and False if not. #is_triangle(2, 3, 4) ➞ True #is_triangle(3, 4, 5) ➞ True #is_triangle(4, 3, 8) ➞ False #Notes #a, b and, c are the side lengths of the triangles. #Test input will always be three positive numbers. def is_triangle(a, b, c): return a+b>c and a+c>b and b+c>a print(is_triangle(2, 3, 4)) print(is_triangle(3, 4, 5)) print(is_triangle(4, 3, 8)) print(is_triangle(2, 9, 5))
true
a055bcd166678d801d9f2467347d9dfcd0e49254
ravalrupalj/BrainTeasers
/Edabit/Count_and_Identify.py
832
4.25
4
#Count and Identify Data Types #Given a function that accepts unlimited arguments, check and count how many data types are in those arguments. Finally return the total in a list. #List order is: #[int, str, bool, list, tuple, dictionary] def count_datatypes(*args): lst=[type(i) for i in args] return [lst.count(i) for i in (int, str, bool, list, tuple, dict)] print(count_datatypes(1, 45, "Hi", False) ) #➞ [2, 1, 1, 0, 0, 0] print(count_datatypes([10, 20], ("t", "Ok"), 2, 3, 1) ) #➞ [3, 0, 0, 1, 1, 0] print(count_datatypes("Hello", "Bye", True, True, False, {"1": "One", "2": "Two"}, [1, 3], {"Brayan": 18}, 25, 23) ) #➞ [2, 2, 3, 1, 0, 2] print(count_datatypes(4, 21, ("ES", "EN"), ("a", "b"), False, [1, 2, 3], [4, 5, 6]) ) #➞ [2, 0, 1, 2, 2, 0] #Notes #If no arguments are given, return [0, 0, 0, 0, 0, 0]
true
fde94a7ba52fa1663a992ac28467e42cda866a9b
ravalrupalj/BrainTeasers
/Edabit/Lexicorgraphically First_last.py
762
4.15625
4
#Lexicographically First and Last #Write a function that returns the lexicographically first and lexicographically last rearrangements of a string. Output the results in the following manner: #first_and_last(string) ➞ [first, last] #Lexicographically first: the permutation of the string that would appear first in the English dictionary (if the word existed). #Lexicographically last: the permutation of the string that would appear last in the English dictionary (if the word existed). def first_and_last(s): t=sorted(s) e=''.join(t) r=e[::-1] p=e,r return list(p) print(first_and_last("marmite")) #➞ ["aeimmrt", "trmmiea"] print(first_and_last("bench")) #➞ ["bcehn", "nhecb"] print(first_and_last("scoop")) #➞ ["coops", "spooc"]
true
5c503edd8d4241b5e674e0f88b5c0edbe0888235
ravalrupalj/BrainTeasers
/Edabit/Explosion_Intensity.py
1,312
4.3125
4
#Explosion Intensity #Given an number, return a string of the word "Boom", which varies in the following ways: #The string should include n number of "o"s, unless n is below 2 (in that case, return "boom"). #If n is evenly divisible by 2, add an exclamation mark to the end. #If n is evenly divisible by 5, return the string in ALL CAPS. #The example below should help clarify these instructions. def boom_intensity(n): if n<2: return 'boom' elif n%2==0 and n%5==0: return 'B'+'O'*n+'M'+'!' elif n%2==0: return 'B'+('o'*n)+'m'+'!' elif n%5==0: return 'B' + ('O' * n) + 'M' else: return 'B'+('o'*n)+'m' print(boom_intensity(4) ) #➞ "Boooom!" # There are 4 "o"s and 4 is divisible by 2 (exclamation mark included) print(boom_intensity(1) ) #➞ "boom" # 1 is lower than 2, so we return "boom" print(boom_intensity(5) ) #➞ "BOOOOOM" # There are 5 "o"s and 5 is divisible by 5 (all caps) print(boom_intensity(10) ) #➞ "BOOOOOOOOOOM!" # There are 10 "o"s and 10 is divisible by 2 and 5 (all caps and exclamation mark included) #Notes #A number which is evenly divisible by 2 and 5 will have both effects applied (see example #4). #"Boom" will always start with a capital "B", except when n is less than 2, then return a minature explosion as "boom".
true
bc123a73adc60347bc2e8195581e6d556b27c329
ravalrupalj/BrainTeasers
/Edabit/Check_if_an_array.py
869
4.28125
4
#Check if an array is sorted and rotated #Given a list of distinct integers, create a function that checks if the list is sorted and rotated clockwise. If so, return "YES"; otherwise return "NO". def check(lst): posi = sorted(lst) for i in range(0,len(lst)-1): first=posi.pop(0) posi.append(first) if posi==lst: return "YES" return 'NO' print(check([3, 4, 5, 1, 2])) #➞ "YES" # The above array is sorted and rotated. # Sorted array: [1, 2, 3, 4, 5]. # Rotating this sorted array clockwise # by 3 positions, we get: [3, 4, 5, 1, 2]. print(check([1, 2, 3])) #➞ "NO" # The above array is sorted but not rotated. print(check([7, 9, 11, 12, 5]) ) #➞ "YES" # The above array is sorted and rotated. # Sorted array: [5, 7, 9, 11, 12]. # Rotating this sorted array clockwise # by 4 positions, we get: [7, 9, 11, 12, 5].
true
a3b5f7ffe220bd211b6fde53c99b9bcb086dbf39
ravalrupalj/BrainTeasers
/Edabit/Reverse_the_odd.py
656
4.4375
4
#Reverse the Odd Length Words #Given a string, reverse all the words which have odd length. The even length words are not changed. def reverse_odd(string): new_lst=string.split() s='' for i in new_lst: if len(i)%2!=0: t=i[::-1] s=s+t+' ' else: s=s+i+' ' return s.strip() print(reverse_odd("Bananas")) #➞ "sananaB" print(reverse_odd("One two three four")) #➞ "enO owt eerht four" print(reverse_odd("Make sure uoy only esrever sdrow of ddo length")) #➞ "Make sure you only reverse words of odd length" #Notes #There is exactly one space between each word and no punctuation is used.
true
8124f901f1650f94c89bdae1eaf3f837925effde
ravalrupalj/BrainTeasers
/Edabit/Balancing_Scales.py
944
4.5
4
#Balancing Scales #Given a list with an odd number of elements, return whether the scale will tip "left" or "right" based on the sum of the numbers. The scale will tip on the direction of the largest total. If both sides are equal, return "balanced". #The middle element will always be "I" so you can just ignore it. #Assume the numbers all represent the same unit. #Both sides will have the same number of elements. #There are no such things as negative weights in both real life and the tests! def scale_tip(lst): t=len(lst)//2 l= sum(lst[0:t]) r=sum(lst[t+1:]) if l>r: return 'left' elif l<r: return 'right' else: return 'balanced' print(scale_tip([0, 0, "I", 1, 1])) #➞ "right" # 0 < 2 so it will tip right print(scale_tip([1, 2, 3, "I", 4, 0, 0])) #➞ "left" # 6 > 4 so it will tip left print(scale_tip([5, 5, 5, 0, "I", 10, 2, 2, 1])) #➞ "balanced" # 15 = 15 so it will stay balanced
true
d183ee49cc90ee2ede5a0d6383404edd9f08a4a8
nicolaespinu/LightHouse_Python
/spinic/Day14.py
1,572
4.15625
4
# Challenge # Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley, # and that the sulfates can't be that high. The problem is, Dot can't really afford to spend tons # of money on the wine. Dot's conditions for searching for wine are: # # Sulfates cannot be higher than 0.6. # The price has to be less than $20. # Use the above conditions to filter the data for questions 2 and 3 below. # # Questions: # # 1. Where is Stellenbosch, anyway? How many wines from Stellenbosch are there in the entire dataset? # 2. After filtering with the 2 conditions, what is the average price of wine from the Bordeaux region? # 3. After filtering with the 2 conditions, what is the least expensive wine that's of the highest quality # from the Okanagan Valley? # # Stretch Question: # What is the average price of wine from Stellenbosch, according to the entire unfiltered dataset? # Note: Check the dataset to see if there are missing values; if there are, fill in missing values with the mean. import pandas as pd df = pd.read_csv('winequality-red_2.csv') df = df.drop(columns = ['Unnamed: 0']) df.head() print('Q1 of wines from Stellenbosch:',df[df['region'].str.contains('Stellenbosch')].shape[0]) filterDF = df[(df['sulphates']<=0.6) & (df['price']<20)] print("Q2 avg price of wines from Bordeaux: ",filterDF[filterDF['region']=='Bordeaux']['price'].mean()) print(filterDF[filterDF['region'].str.contains('Okanagan Valley')].sort_values(['quality','price'],ascending=[False,True])) # 1. 35 Wines # 2 .$11.30 # 3. Wine 1025
true
3a419523fb1fc6bbef5cf3da4ad3d07cc3d77b34
PranavDev/Sorting-Techniques
/RadixSort.py
803
4.15625
4
# Implementing Radix Sort using Python # Date: 01/04/2021 # Author: Pranav H. Deo import numpy as np def RadixSort(L, ord): Reloader_List = [] temp = [] for i in range(0, 10): Reloader_List.append([]) for i in range(0, ord): print('Iteration ', i, ' : ', L) for ele in L: n = int((ele / np.power(10, i)) % 10) Reloader_List[n].append(ele) for lst in Reloader_List: if len(lst) > 0: for e in lst: temp.append(e) L = temp temp = [] for k in range(0, 10): Reloader_List[k] = [] return L # MyList = [102, 209, 90, 1, 458, 923, 9, 48, 20] MyList = np.random.randint(0, 500, 100) order = 3 Final_List = RadixSort(MyList, order) print('\n', Final_List)
false
dc34b77a678caff2ce7b611f21ed210d55321225
humanwings/learngit
/python/coroutine/testCoroutine_01.py
894
4.25
4
''' 协程(Coroutine)测试 - 生产者和消费者模型 ''' def consumer(): r = '' # print('*' * 10, '1', '*' * 10) while True: # print('*' * 10, '2', '*' * 10) n = yield r if not n: # print('*' * 10, '3', '*' * 10) return # print('[CONSUMER] Consuming %s...' % n) r = '200 OK' def produce(c): # print('*' * 10, '4', '*' * 10) c.send(None) # 相当于 c.next() 不能send非none 因为是第一次调用,没有yield来接收数据 n = 0 # print('*' * 10, '5', '*' * 10) while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) #c.send(0) # 在这里加上send(0),可以出return前的log,但是会发生topIteration,为什么? c.close() c = consumer() produce(c)
false
afdf0666b5d24b145a7fee65bf489fd01c4baa8c
OaklandPeters/til
/til/python/copy_semantics.py
1,348
4.21875
4
# Copy Semantics # ------------------------- # Copy vs deep-copy, and what they do # In short: copy is a pointer, and deep-copy is an entirely seperate data structure. # BUT.... this behavior is inconsistent, because of the way that attribute # setters work in Python. # Thus, mutations of attributes is not shared with copies, but mutations # of items IS shared. # See example #1 VS #2 import copy # Example #1 # Item mutation DOES change copies, but not deep copies original = ["one", "two", ["three", "333"]] shallow = copy.copy(original) deep = copy.deepcopy(original) assert (original == shallow) assert (original == deep) assert (shallow == deep) original[2][0] = "four" assert (original == shallow) assert (original != deep) assert (shallow != deep) # Example #2 # Attribute mutation does not change copies, nor deep copies class Person: def __init__(self, name): self.name = name def __repr__(self): return "{0}({1})".format(self.__class__.__name__, self.name) def __eq__(self, other): return self.name == other.name original = Person("Ulysses") shallow = copy.copy(original) deep = copy.deepcopy(original) assert (original == shallow) assert (original == deep) assert (shallow == deep) original.name = "Grant" assert (original != shallow) assert (original != deep) assert (shallow == deep)
true
761768971347ca71abb29fcbbaccf6ef92d4df86
Varobinson/python101
/tip-calculator.py
998
4.28125
4
#Prompt the user for two things: #The total bill amount #The level of service, which can be one of the following: # good, fair, or bad #Calculate the tip amount and the total amount(bill amount + tip amount). # The tip percentage based on the level of service is based on: #good -> 20% #fair -> 15% # bad -> 10% try: #Ask user for total bill amount total_bill = int(input('What was your total? ')) #convert total to float #prompt user for service quality service = input('What was the service bad, fair, or good? ') #adding split feature #promt user for split amount split = input('How many people will be paying? ') except: print('error') #convert split to int split = int(split) tip = () service = service.lower() if service == 'bad': tip = total_bill * 0.1 elif service == 'fair': tip = total_bill * 0.15 elif service == 'good': tip = total_bill * 0.2 else: print("Cant't help you! ") #added split to total total = total_bill + tip / split print(total)
true
94bdd2d96de22c8911e7c22e46405558785fc25e
chhikara0007/intro-to-programming
/s2-code-your-own-quiz/my_code.py
1,211
4.46875
4
# Investigating adding and appending to lists # If you run the following four lines of codes, what are list1 and list2? list1 = [1,2,3,4] list2 = [1,2,3,4] list1 = list1 + [5] list2.append(5) # to check, you can print them out using the print statements below. print list1 print list2 # What is the difference between these two pieces of code? def proc(mylist): mylist = mylist + [6] def proc2(mylist): mylist.append(6) # Can you explain the results given by the four print statements below? Remove # the hashes # and run the code to check. print list1 proc(list1) print list1 print list2 proc2(list2) print list2 # Python has a special assignment syntax: +=. Here is an example: list3 = [1,2,3,4] list3 += [5] # Does this behave like list1 = list1 + [5] or list2.append(5)? Write a # procedure, proc3 similar to proc and proc2, but for +=. When you've done # that check your conclusion using the print-procedure call-print code as # above. def proc3(mylist): mylist += [5] print list3 proc3(list3) print list3 print list1 print list2 print list3 # What happens when you try: list1 = list1 + [7,8,9] list2.append([7,8,9]) list3 += [7,8,9] print list1 print list2 print list3
true
592e186d9725f23f98eaf990116de6c572757063
Lobo2008/LeetCode
/581_Shortest_Unsorted_ContinuousSubarray.py
1,749
4.25
4
""" Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means <=. """ class Solution: def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ """ 把数组看成折线图,折线图应该是上升或者平行的 两个指针head 和tail,同时从两边开始,当head指针的路劲下降的时候,找到了start,当tail指针的路径上坡了,找到了end,end-start就是长度 """ if len(nums) <= 1: return 0 sortnums = sorted(nums) head, tail = 0, len(nums)-1 headFind, tailFind = False, False while head <= tail: headRs = nums[head] ^ sortnums[head] == 0 tailRs = nums[tail] ^ sortnums[tail] == 0 if not headRs and not tailRs: return tail - head + 1 if headRs: #等于0的时候要继续比下一个 head += 1 if tailRs: tail -= 1 return 0 so = Solution() nums = [2, 6, 4, 8, 10, 9, 15]#5 # nums = [10,9,8,7,6,5] # nums = [] #0 # nums = [1] #0 # nums = [1,10] #0 # nums = [10,1] #2 # nums = [2,1,3,4,5] #2 nums = [2,3,4,5,1] #5 print(so.findUnsortedSubarray(nums))
true
eff175292e48ca133ae5ca276a679821ebae0712
soumilshah1995/Data-Structure-and-Algorithm-and-Meta-class
/DataStructure/Deque/DEQChallenge.py
1,505
4.15625
4
""" DEQUE Abstract Data Type DEQUE = Double ended Queue High level its combination of stack and queue you can insert item from front and back You can remove items from front and back we can use a list for this example. we will use methods >----- addfront >----- add rear >----- remove front >----- remove rear we want to check Size, isempty QUEUE - FIFO STACK - LIFO DEQUE - can use both LIFO or FIFO any items you can store in list can be stored in DEQUE Most common Questions is Palindrone using DEQUE Datastructure """ class Deque(object): def __init__(self): self.items = [] def add_front(self, item): self.items.insert(0, item) def add_rear(self, item): self.items.append(item) def remove_front(self): return self.items.pop(0) def remove_rear(self): return self.items.pop() def size(self): return len(self.items) def isempty(self): if(self.items) == []: return True else: return False def peek_front(self): return self.items[0] def peek_rear(self): return self.items[-1] def main(data): deque = Deque() for character in data: deque.add_rear(character) while deque.size() >= 2: front_item = deque.remove_front() rear_item = deque.remove_rear() if rear_item != front_item: return False return True if __name__ == "__main__": print(main("nitin")) print(main("car"))
true
5d37cc5141b7f47ec6991ffa4800055fef50eab8
soumilshah1995/Data-Structure-and-Algorithm-and-Meta-class
/DataStructure/Queue/Queue.py
786
4.125
4
class Queue(object): def __init__(self): self.item = [] def enqueue(self, item): self.item.insert(0, item) def dequeue(self): if self.item: self.item.pop() else: return None def peek(self): if self.item: return self.item[-1] def isempty(self): if self.item == []: return True else: return False def size(self): return len(self.item) if __name__ == "__main__": queue = Queue() queue.enqueue(item=1) queue.enqueue(item=2) print("Size\t{}".format(queue.size())) print("Peek\t{}".format(queue.peek())) queue.dequeue() print("Size\t{}".format(queue.size())) print("Peek\t{}".format(queue.peek()))
false
c4765e62289e7318c56271e9f27942544b572842
Oldby141/learning
/day6/继承.py
1,397
4.375
4
#!_*_coding:utf-8_*_ # class People:#经典类 class People(object):#新式类写法 Object 是基类 def __init__(self,name,age): self.name = name self.age = age self.friends = [] print("Run in People") def eat(self): print("%s is eating...."%self.name) def talk(self): print("%s is talking...." % self.name) def sleep(self): print("%s is sleeping...." % self.name) class Relation(object): def __init__(self,name,age): print("Run in Relation")# 多继承先左后右 def make_friend(self,obj): print("%s is making friends with %s"%(self.name,obj.name)) #self.friends.append(obj.name) self.friends.append(obj) class Man(Relation,People): def __init__(self,name,age,money): #People.__init__(self,name,age) super(Man,self).__init__(name,age)#新式类写法 self.money = money print("出生的钱数目:%s"%self.money) def p(self): print("%s "%self.name) def sleep(self): People.sleep(self) print("man is sleeping") class Woman(People,Relation): def get_birth(self): print("%s get birth"%self.name) m1 = Man("byf",23,10) # print(m1.name) # m1.sleep() w1 = Woman("gg",23) # w1.get_birth() #m1.make_friend(w1) #print(m1.friends) #print(m1.friends[0].name) w1.name = "GG" #print(m1.friends[0].name)
false
f1b55b29f5091414848893f10f636c509ce57ce7
WU731642061/LeetCode-Exercise
/python/code_189.py
1,986
4.375
4
#!/usr/bin/env python3 """ link: https://leetcode-cn.com/problems/rotate-array/ 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 """ def rotate1(nums, k): """ 第一种思路是利用数组拼接,向右移动N位其实就是将[-n:]位数组拼接到[:-n]数组的前面 需要注意的是k可能会大于数组本身的长度,那么每移动len(nums)位,数组与原数组重合, 所以只需要计算 k % len(nums)后需要移动的结果 """ length = len(nums) n = k % length if n == 0: return nums[:] = nums[-n:] + nums[:-n] def rotate2(nums, k): """ 第二种思路是通过头部插入的方式,实现向右平移的效果 即向右平移一位就是将数组尾部的数据插入到头部中去 这里有两种实现思路,一种是使用list.insert(index, obj)方法插入头部 另一种是将数组翻转,然后通过list.pop(0)和append()的效果实现平移,最后将数组再次reserve() 关于python中数组方法的时间复杂度,可以参考一下这篇文章:https://blog.csdn.net/u011318721/article/details/79378280 通过上篇文章可以知道,通过insert方法实现平移的思路的时间复杂度为 n * (n + 1) = O(n^2) 通过翻转+pop+insert方法实现平移的思路的时间复杂度为 2n + n * (n + 1) = O(n^2) """ length = len(nums) n = k % length if n == 0: return for i in range(n): nums.insert(0, nums.pop()) # 因为这两种做法思路相近,只是调用的方法不同,所以写在一个方法中 # length = len(nums) # n = k % length # if n == 0: # return # # 2n指的是数组需要翻转两次 # nums.reverse() # for i in range(n): # nums.append(nums.pop(0)) # nums.reverse() """ TODO: 暂时就想到这两种方法,题目说可以有3种以上的解,以后若是有想到,继续补充 """
false
56b78459da8cd4ca3b2bc16de38822105f02c82c
WU731642061/LeetCode-Exercise
/python/code_234.py
2,578
4.15625
4
#!/usr/bin/env python3 """ link: https://leetcode-cn.com/problems/palindrome-linked-list/ 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题? """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def isPalindrome(head: ListNode) -> bool: """ 还是先最简单的思路吧,通过list来处理,取出所有的value,然后翻转,就可以检查是否是回文了 但是这里不满足O(1)的空间复杂度 """ value = [] while head: value.append(head.val) head = head.next return value == value[::-1] def isPalindrome2(head: ListNode) -> bool: """ 还是那句话,这样就失去了链表题目考察我们本身的意义了,要用链表打败链表 我们先不考虑进阶的要求,每种思路都去尝试一下,只有在不断优化的过程中,才能体会到算法的美妙 思路:加入我们不考虑时间复杂度,我们该怎么做 1. 拿到链表的长度 2. 从head开始依次比较 3. 每一项比较,我们就去遍历一次链表,0对应len-1,1对应len-2.... 4. 返回结果 """ def getNode(head, n): node = head for i in range(n-1): node = node.next return node length = 0 cur = head while cur: length += 1 cur = cur.next cur = head for i in range(length//2): # 1,2,3,4,5,4,3,2,1 r = getNode(head, length-i) if cur.val != r.val: return False cur = cur.next return True # 结果就是妥妥的超时了,但是不考虑时间情况下的话,这种方法应该是可行的 def isPalindrome3(head: ListNode) -> bool: """ 这种思路是把链表变成双向链表 先遍历一遍,创建pre属性 然后拿head和last进行一一比较 """ pre = None cur = head last = None while cur: cur.pre = pre pre = cur cur = cur.next if cur == None: last = pre while True: if head == last: break if head.val != last.val: return False else: head = head.next last = last.pre return True # 我在答案里看到还有一种思路也很有趣,先遍历一遍,获得整个链表的长度,然后翻转其中的一半(length//2),同时取到一半时(length//2+1)的链表节点,同时开始遍历 # 这里我就不写出解法了,如果有缘人看到这,可是尝试着自己写一下
false
2b803b5c53b0fc9cc03049f7b8eb61f39d38125d
thSheen/pythonaz
/Basic/Variables.py
479
4.125
4
greeting = "Hello" Greeting = "World" _NAME = "Thiago" Thiago34 = "What" t123 = "Wonderful" print(greeting + ' ' + _NAME) print(Greeting + ' ' + Thiago34 + ' ' + t123) a = 12 b = 3 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) # // to whole numbers, it's important use it to prevent future errors # Example : for i in range(1, a//b): print(i) # It doesn't work if just use one / # Wrong : print(a + b / 3 -4 * 12) # Right : print((((a + b)/3)-4)*12)
false
b777cc4d1682a6a3c1e5a450c282062c4a0514da
jrobind/python-playground
/games/guessing_game.py
755
4.21875
4
# Random number CLI game - to run, input a number to CLI, and a random number between # zero and the one provided will be generated. The user must guess the correct number. import random base_num = raw_input('Please input a number: ') def get_guess(base_num, repeat): if (repeat == True): return raw_input('Wrong! Guess again: ') else: return raw_input('Please guess a number between 0 and ' + base_num + '. ') if (base_num == ''): print('Please provide a number: ') else: random_num = random.randint(0, int(base_num)) guess = int(get_guess(base_num, False)) # use a while loop while (random_num != guess): guess = int(get_guess(base_num, True)) print('Well done! You guessed correct.')
true
e88333ce7bd95d7fb73a07247079ae4f5cb12d11
graciofilipe/differential_equations
/udacity_cs222/final_problems/geo_stat_orb.py
2,907
4.375
4
# PROBLEM 3 # # A rocket orbits the earth at an altitude of 200 km, not firing its engine. When # it crosses the negative part of the x-axis for the first time, it turns on its # engine to increase its speed by the amount given in the variable called boost and # then releases a satellite. This satellite will ascend to the radius of # geostationary orbit. Once that altitude is reached, the satellite briefly fires # its own engine to to enter geostationary orbit. First, find the radius and speed # of the initial circular orbit. Then make the the rocket fire its engine at the # proper time. Lastly, enter the value of boost that will send the satellite # into geostationary orbit. # import math import numpy as np from scipy.integrate import solve_ivp # These are used to keep track of the data we want to plot h_array = [] error_array = [] period = 24. * 3600. # s earth_mass = 5.97e24 # kg earth_radius = 6.378e6 # m (at equator) gravitational_constant = 6.67e-11 # m3 / kg s2 total_time = 9. * 3600. # s marker_time = 0.25 * 3600. # s # Task 1: Use Section 2.2 and 2.3 to determine the speed of the inital circular orbit. initial_radius = earth_radius + 200*1000 initial_speed = np.sqrt(earth_mass*gravitational_constant/initial_radius) final_radius = 42164e3 boost_time = initial_radius*math.pi/initial_speed # Task 3: Which is the appropriate value for the boost in velocity? 2.453, 24.53, 245.3 or 2453. m/s? # Change boost to the correct value. boost = 245.3 # m / s ic = [initial_radius, 0, 0, initial_speed] def x_prime(t, x): vector_to_earth = -np.array([x[0], x[1]]) # earth located at origin a = gravitational_constant * earth_mass / np.linalg.norm(vector_to_earth) ** 3 * vector_to_earth speed_x, speed_y = x[2], x[3] vec = [speed_x, speed_y, a[0], a[1]] return vec def integrate_until(ti, tf, ic, x_prime_fun): tval = np.linspace(ti, tf, 111) sol = solve_ivp(x_prime_fun, t_span=(ti, tf), t_eval=tval, y0=ic, vectorized=False, rtol=1e-6, atol=1e-6) return sol ic1 = [initial_radius, 0, 0, initial_speed] sol1 = integrate_until(ti=0, tf=boost_time , ic=ic1, x_prime_fun=x_prime) ic2 = sol1.y[:, 110] v = ic2[2], ic2[3] new_v = v + boost * np.array(v/np.linalg.norm(v)) ic2[2], ic2[3] = new_v[0], new_v[1] sol2 = integrate_until(ti=boost_time , tf=total_time, ic=ic2, x_prime_fun=x_prime) import plotly.graph_objs as go from plotly.offline import plot data = [go.Scatter(x=[earth_radius*math.cos(i) for i in np.linspace(0, 2*math.pi, 10000)], y=[earth_radius*math.sin(i) for i in np.linspace(0, 2*math.pi, 10000)], name='earth'), go.Scatter(x=sol1.y[0], y=sol1.y[1], name='pre boost'), go.Scatter(x=sol2.y[0], y=sol2.y[1], name='post boost')] plot(data)
true
ddc0bf0fdf77f46bf646a5ee2654d391e031647d
rojiani/algorithms-in-python
/dynamic-programming/fibonacci/fib_top_down_c.py
978
4.21875
4
""" Fibonacci dynamic programming - top-down (memoization) approach Using Python's 'memo' decorator Other ways to implement memoization in Python: see Mastering Object-Oriented Python, p. 150 (lru_cache) """ def fibonacci(n): # driver return fib(n, {}) def fib(n, memo= {}): if n == 0 or n == 1: return n try: return memo[n] except KeyError: memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n] print("Testing") tests = [(0, 0), (1, 1), (2, 1), (3, 2), (4, 3), (5, 5), (6, 8), (7, 13), \ (8, 21), (9, 34), (10, 55), (25, 75025), (50, 12586269025), \ (100, 354224848179261915075)] for test in tests: result = fibonacci(test[0]) if result == test[1]: print("PASS: %d" % result) else: print("FAIL: %d" % result) import timeit p=300 print("fibonacci (bottom-up)") print("%.8f" % (timeit.timeit("fibonacci(p)", setup = "from __main__ import fibonacci, p", number=1)))
false
75c14cfafe64264b72186017643b6c3b3dacb42f
Malak-Abdallah/Intro_to_python
/main.py
866
4.3125
4
# comments are written in this way! # codes written here are solutions for solving problems from Hacker Rank. # ------------------------------------------- # Jenan Queen if __name__ == '__main__': print("Hello there!! \nThis code to practise some basics in python. \n ") str = "Hello world" print(str[2:]) # TASK 1: # If n is odd, print Weird # If n is even and in the inclusive range of 2 to 5, print Not Weird # If n is even and in the inclusive range of 6 to 20, print Weird # If n is even and greater than 20, print Not Weird # 1<= n <= 100 print("Enter an integer greater then zero and less or equal 100 ") n = int(input().strip()) if (n % 2) != 0: print("Weird") elif n % 2 == 0: if n in range(2, 6) or n > 20: print("Not Weird") else: print("Weird")
true