blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9f9383d221cd4cdd5b8f8e3a3deb87664fed8f29
peterj35/algorithmfun
/queue/hotPotato.py
1,810
4.3125
4
# Based on the children's game Hot Potato, using a Queue... # Toss the potato 1-10 times and whoever is holding the potato is eliminated # The last remaining person is the winner. from queue import Queue import random def hotPotato(namelist): # Instantiate a queue and insert everyone's names into it simqueue = Queue() for name in namelist: simqueue.enqueue(name) # Store 'elimination statements' into a dict elim_dict = {0: "'s hands burnt off! Now they have no hands, only stumps.", 1: " drops the potato, for no good reason.", 2: " gets sick from the smell of burning human flesh.", 3: " is hit in the face with the scalding potato, and screams in agony.", 4: " has had enough of this sick game."} # While queue is larger than 1 while simqueue.size() > 1: # Determine how many times to toss the potato tosses = random.randint(1,10) if tosses == 1: print("Tossing " + str(tosses) + " time...") else: print("Tossing " + str(tosses) + " times...") # Move a person from the beg of the queue to the end of the queue, to simulate a toss for i in range(tosses): simqueue.enqueue(simqueue.dequeue()) print(simqueue) # Comment out for cleaner output # After the tosses, person holding potato is eliminated # Randomly select an elimination statement from the elim_dict elim_code = random.randint(0,4) print(str(simqueue.peek()) + elim_dict[elim_code]) simqueue.dequeue() # Return the 1 person leftover return (str(simqueue.dequeue()) + " is the winner! He gets to keep the potato.") print(hotPotato(["Bill","David","Susan","Jane","Kent","Adam", "Robert"]))
true
0201db5f38ecd981ea63f5d47028a7703eb45629
WeslleyBorges/PythonExercises
/vetor_ordem_inversa.py
296
4.125
4
vetor = [] for x in range(0, 10): vetor.append(int(input('Insira um número na posição {0}: ' .format(x)))) print() print('Vetor invertido: ') print('Posição por posição: ') for x in range(len(vetor) - 1, -1, -1): print(vetor[x]) print('De rabo a cabo: ') print(vetor.reverse())
false
f7bdce170b9971d30285063faad21d376eec4007
pythonwithalex/Spring2015
/week2/debug.py
662
4.4375
4
#!/usr/bin/env python ''' random_string(N) --> random string of length N ''' import random # notes on the funcs we use: # random.randrange -> gives you a random integer in range(M,N-1) # chr -> turns a number into an ASCII character # Assignment: this function works pretty well, but it isn't perfect, nor very safe # 1) see if you can figure out why by testing various input on it # 2) finally, add code prevent unexpected errors def random_string(length): random_string = '' while length: random_string += chr(random.randrange(97,123)) length -= 1 return random_string print 'a random string of length 8: {}'.format(random_string(8))
true
5363d4b2e57ac31ef0fc5d1f584d3515e4d092ad
AlekseyPanas/ProjectEulerSolutions
/P4.py
649
4.3125
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(num): return str(num)[::-1] == str(num) num1 = 999 num2 = 999 ran = 900 # 998001 largest_palindrome = 0 vals = (0, 0) while num1 >= ran: while num2 > ran: if is_palindrome(num2 * num1) and (num2 * num1) > largest_palindrome: largest_palindrome = num2 * num1 vals = (num1, num2) num2 -= 1 num2 = 999 num1 -= 1 print(largest_palindrome) print(vals)
true
b8141e7c72d9ef441137a97c108bec0f126bb8b0
KhalidMelouka/Rock-paper-scissors
/r-p-s.py
2,120
4.3125
4
from random import randint print(""" welcome to rock, paper, scissors. You'll be facing your own computer. if you want to quit, just write <quit>. Enjoy playing. """) machine_input = ["rock", "paper", "scissors"] rand_choice = machine_input[randint(0, len(machine_input)-1)] keep_play = True user_score = 0 computer_score = 0 while keep_play: rand_choice = machine_input[randint(0, len(machine_input)-1)] choice = input("rock, paper, scissors: ").lower() if choice == rand_choice: print(f"both {choice}. try again") print(f"user: {user_score} -- computer: {computer_score}") elif choice == "rock" and rand_choice == "paper": print(f"you chose {choice} and computer chose {rand_choice}. Computer wins") computer_score += 1 print(f"user: {user_score} -- computer: {computer_score}") elif choice == "rock" and rand_choice == "scissors": print(f"you chose {choice} and computer chose {rand_choice}. You win") user_score += 1 print(f"user: {user_score} -- computer: {computer_score}") elif choice == "paper" and rand_choice == "rock": print(f"you chose {choice} and computer chose {rand_choice}. You win!") user_score += 1 print(f"user: {user_score} -- computer: {computer_score}") elif choice == "paper" and rand_choice == "scissors": print(f"you chose {choice} and computer chose {rand_choice}. Computer wins!") computer_score += 1 print(f"user: {user_score} -- computer: {computer_score}") elif choice == "scissors" and rand_choice == "rock": print(f"you chose {choice} and computer chose {rand_choice}. Computer wins!") computer_score += 1 print(f"user: {user_score} -- computer: {computer_score}") elif choice == "scissors" and rand_choice == "paper": print(f"you chose {choice} and computer chose {rand_choice}. You win!") user_score += 1 print(f"user: {user_score} -- computer: {computer_score}") elif choice == "quit": print("thank you for playing") keep_play = False
true
55ead38559c87d76a86c6e76e857fdf63bd8c8a4
neaGaze/CodingPractice
/src/solutions/graph/MostStonesRemoved.py
2,971
4.21875
4
""" ### GOOGLE MOST ASKED QUESTION ### Most Stones Removed with Same Row or Column: On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone. Now, a move consists of removing a stone that shares a column or row with another stone on the grid. What is the largest possible number of moves we can make? Example 1: Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Example 2: Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Example 3: Input: stones = [[0,0]] Output: 0 Note: 1 <= stones.length <= 1000 0 <= stones[i][j] < 10000 Solution: Approach 1: Depth-First Search Algorithm To count connected components of the above graph, we will use depth-first search. For every stone not yet visited, we will visit it and any stone in the same connected component. Our depth-first search traverses each node in the component. For each component, the answer changes by -1 + component.size. class Solution(object): def removeStones(self, stones): graph = collections.defaultdict(list) for i, x in enumerate(stones): for j in xrange(i): y = stones[j] if x[0]==y[0] or x[1]==y[1]: graph[i].append(j) graph[j].append(i) N = len(stones) ans = 0 seen = [False] * N for i in xrange(N): if not seen[i]: stack = [i] seen[i] = True while stack: ans += 1 node = stack.pop() for nei in graph[node]: if not seen[nei]: stack.append(nei) seen[nei] = True ans -= 1 return ans Complexity Analysis Time Complexity: O(N^2), where NN is the length of stones. Space Complexity: O(N^2) Approach 2: Union-Find Algorithm Let's connect row i to column j, which will be represented by j+10000. The answer is the number of components after making all the connections. Note that for brevity, our DSU implementation does not use union-by-rank. This makes the asymptotic time complexity larger. class DSU: def __init__(self, N): self.p = range(N) def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): xr = self.find(x) yr = self.find(y) self.p[xr] = yr class Solution(object): def removeStones(self, stones): N = len(stones) dsu = DSU(20000) for x, y in stones: dsu.union(x, y + 10000) return N - len({dsu.find(x) for x, y in stones}) Complexity Analysis Time Complexity: O(NlogN), where NN is the length of stones. (If we used union-by-rank, this can be O(N∗α(N)), where \alphaα is the Inverse-Ackermann function.) Space Complexity: O(N) """
true
8908e2706391b604a6928fecdf52f534ea0ffd70
neaGaze/CodingPractice
/src/solutions/arrayandstring/StrobogrammaticNumber.py
1,037
4.3125
4
""" A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. Example 1: Input: "69" Output: true Example 2: Input: "88" Output: true Example 3: Input: "962" Output: false Solution: class Solution: def isStrobogrammatic(self, num: str) -> bool: if(int(num)!=0 and num[0]=='0'): return False return self.isStrobogrammaticHelper(num) def isStrobogrammaticHelper(self, num: str) -> bool: if(len(num)==0): return True if(len(num)==1): if(int(num) in {0,1,8}): return True else: return False set = {(0,0),(1,1),(8,8),(6,9),(9,6)} l = len(num) return (int(num[0]),int(num[l-1]))in set and self.isStrobogrammaticHelper(num[1:l-1]) """ class Solution: def isStrobogrammatic(self, num: str) -> bool:
true
2d34110aab33c9c0c5d49d047a19c4560cb8607b
macv-hub/Challenges
/Session_3.py
1,045
4.1875
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% #CATCH UP CHALLENGE num_1 = int(input("Enter a number over 100: ")) num_2 = int(input("Enter a number under 10: ")) result = num_1//num_2 print("{0} goes in {1} {2} times".format(num_2,num_1,result)) # %% #IS IT RAINING? raining = input("Is it raining? ") raining = str.lower(raining) if raining == "yes": windy = input("Is it windy? ") windy = str.lower(windy) if windy == "yes": print("it's too windy for an umbrella") else: print("take an umbrella") else: print("Enjoy your day") # %% # ENTER A NUMBER LOOP num_1 = int(input("enter a number: ")) num_2 = int(input("enter another number: ")) result = num_1+num_2 add_number = input("Do you want to add another number? [yes/no] ") while add_number == "yes": num_3 = int(input("enter the number: ")) result = result + num_3 add_number = input("Do you want to add another number? [yes/no] ") else: print("The total is " + str(result))
true
0be45f2e851cf5c8aee39fe0a33e4a2ae8a13e8a
PetrovNikA/python_5
/lesson5_task5.py
764
4.15625
4
# Задание 5. # Создать (программно) текстовый файл, записать в него программно набор чисел, разделённых пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить её на экран. with open('lesson5_task5.txt', 'w', encoding='utf-8') as f: nums = input('Введите целые числа через пробел: ') f.write('Введенные числа: ' + nums + '\n') nums = map(int, nums.split()) # without list sum_nums = sum(nums) f.write('Сумма чисел: ' + str(sum_nums)) print('Сумма чисел записанных в файл: ', sum_nums)
false
ed3550362f2aba019b39c32badac45f40bcfcf26
anjaana1/techvidya-weekend-python-12PM
/python-conditionals.py
2,934
4.3125
4
# Conditionals in Python # if,elif,else # >,>=,<,<=,==,!= -> Comparision Operators # If Condition # Syntax: # if (condition == True): # block of if condition # age = 28 # if age > 18: # print("You are eligible to vote") # print("if condition ended") # if-else condition # Syntax: # if (condition == True): # block of if # else: # block of else # age = int(input("Enter your age :")) # if age > 18: # print("You are eligible to vote") # else: # print("You are not eligible") # num1 = 30 # num2 = 20 # if num1 > num2: # print(str(num1) + " is greater than " + str(num2)) # else: # print(str(num1) + " is less than " + str(num2)) # if-elif-else # syntax : # if (condition == True): # block of if # elif (condition == True): # block of this elif # elif (condition == True) # block of this elif # else: # block of else # age = int(input("Enter your age : ")) # age < 18 and age > 0 OR 0 < age < 18 # # if age == 18: # print("You are eligible to vote from this year") # elif age > 18: # print("You are perfectly eligible to vote") # elif 0 < age < 18: # print("Sorry, You are not eligible") # else: # print("Wrong Input") # Nested if # if cond: # block of codes # if cond: # block of codes # else: # block of codes # else: # block of codes # x = 5 # if x > 10: # print("Greater than 10,") # if x > 20: # print("also greater than 20") # else: # print("less than 20") # else: # pass # Pass Keyword # if codn: # pass # # Short Hand If - Else # x = 11 # if x > 10: # print("Greater than 10") # else: # print("Smaller than 10") # # print("Greater than 10") if x > 10 else print("Smaller than 10") # age = int(input("Enter your age : ")) # if age == 18: # print("You are eligible to vote from this year") # elif age > 18: # print("You are perfectly eligible to vote") # elif 0 < age < 18: # print("Sorry, You are not eligible") # else: # print("Wrong Input") # print("You are eligible to vote from this year") if age == 18 else print("You are perfectly eligible to vote") \ # if age > 18 else print("Sorry, You are not eligible") if 0 < age < 18 else print("Wrong Input") # Assignment # Write a program to print whether a number is positive, negative or zero of a user input.(Long and short-hand) # Write a python program to convert temperature from celcius to fahrenheit, and fahrenheit to celcius. # (c/5=f-32/9) # Write a program to guess a number between 1 to 10. # Using If-Else with And/Or # a = 200 # b = 33 # c = 500 # if a > b and a > c: # print("a is greater than b and c") # elif b > a and b > c: # print("b is greater than a and c") # elif c > a and c > b: # print("c is greater than a and b") # else: # print("Wrong Input") # a = 200 # b = 33 # c = 500 # if a > b or a > c: # print("At least one condition is True")
false
e143b80ab28b6172938e526781d1f7e3d1a67185
chenyuefang/python-0426
/Part 1/day05/params_test.py
2,417
4.34375
4
def power(x): return x * x print(power(2)) def power(x, n): p = 1 while n > 0: p *= x n -= 1 return p print(power(2, 3)) def power(x, n=2): # 默认参数 p = 1 while n > 0: p *= x n -= 1 return p print(power(2)) # 默认参数 n 没写,默认为2 def fn_default(x, y=1, z=2): return x + y - z print(fn_default(0, 1)) # 1 为 y=1 调用,默认参数可按照顺序,不必写参数名 print(fn_default(1, z=1)) # 默认参数不按照顺序调用,需要写明参数名 # 可变参数 # 位置参数在前,默认参数在后; 把变化小的参数作为默认参数; 默认参数必须只想不变的对象 # 可变类型作为默认参数 array=【】 第二个print(fn_append()) 得到 ['END' , 'END'] def fn_append(array=None): if array is None: array = [] array.append('END') # 追加元素到最后 return array print(fn_append([1, 2, 3])) print(fn_append()) # ['END'] print(fn_append()) # ['END'] print(max(1, 2, 3, 4)) """ void method(int... x) """ # * + 参数名 ;参数个数可变;可变参数被组装为tuple def fn_sum(*numbers): print(numbers) s = 0 for n in numbers: s += n return s print(fn_sum(1, 2, 3, 4, 5)) # print(fn_sum()) num = [1, 2, 3, 4, 5] print(fn_sum(num[0], num[1], num[2], num[3], num[4])) # 关键字参数 def fn_keywords(email, password, **kw): print(email, password) if 'gende' in kw: # todo pass if 'married' in kw: # todo pass fn_keywords('tom@tom.com', 123, gende='male', married=False) # 命名关键字参数【 *, + 参数名】 def fn_named_keywords(email, password, *, age, married=False, **kw): print(email, password, age, married, kw) fn_named_keywords('jerry@tom.com', 'abc', age=18) # married 默认为 False fn_named_keywords('jerry@tom.com', 'abc', age=18, married=True) fn_named_keywords('jerry@tom.com', 'abc', age=18, married=True, gende='male') def fn_named_keywords(email, password, *args, age, married=False, **kw): print(email, password, args, age, married, kw) fn_named_keywords('email...', 'password...', 1, 2, 3, 'abc', age=19, gende='female') # 参数顺序 def fn_test(a, b=1, *c, d, **e): # d:命名关键字参数 print(a, b, c, d, e) fn_test(1, 2, 3, 4, 5, d=6) # 1 2[修改b的默认值] (3,4,5)[*c的值] 6[必须写出参数名] {}
false
0a8e0c5382061d8f54116b57ce6ce572ed5e86e5
nenaoj227/Ojukwu_Pythagorean
/ojukwu_pythagorean.py
345
4.125
4
x = raw_input ("What is your name?") print ("Welcome, " + x) from math import sqrt #Defining variables and taking input from user A = raw_input ("Enter 1st slide:") B = raw_input ("Enter 2nd slide:") # ASQU = int(A) * int(A) BSQU = int(B) * int(B) AandB = int(ASQU)+int(BSQU) answer = sqrt(AandB) print "The length of side C is" + str(answer)
true
4b6c6465c0262f058949e1d297048320a0968615
tacostahern/ITM-313
/Homework/4-12-2020/HW_Source_code.py
1,191
4.375
4
''' This program will contain a class called pet, with data attributes for name, animal type, and age. It will have an __init__ method, and setter and getter methods for the data attributes. Author: Tony Acosta Hernandez Course: ITM 313 ''' class Pet: #Construct a pet object def __init__(self, name, animal_type, age): self.__name, self.__animal_type, self.__age = name, animal_type, age def set_name(self, name): self.__name = name def set_animal_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get_age(self): return self.__age name = input("Please enter the name of your pet: ") #pet1.set_name(name) animal_type = input("Please enter the type of animal your pet is: ") #pet1.set_animal_type(animal_type) age = eval(input("Please enter the age of your pet: ")) #pet1.set_age(age) pet1 = Pet(name, animal_type, age) print("Your pet's name is", pet1.get_name()) print("Your pet is a", pet1.get_animal_type()) print("Your pet is", pet1.get_age(), "year old")
true
2c2297fa524a47c1e1dd10ce11ae0de15cd07659
Monkey-X/monkey_Python
/mysite/mysite/text2.py
1,088
4.15625
4
""" Python 的分支结构 使用缩进的方式来设置代码的层次结构 """ from random import randint username = input('请输入用户名:') password = input('请输入口令:') if username == 'admin' and password == '123456': print('身份验证成功!') else: print('身份验证失败!') print('-------------------------------------') x = float(input('x = ')) if x > 1: y = 3 * x -5 elif x >= -1: y = x + 2 else: y = 5 * x +3 print("y = %f" % y) print('-----------------------------------------') value = float(input('请输入长度:')) unit = input('请输入单位:') if unit == 'in' or unit == '英寸': print('%f英寸 = %f 厘米' % (value,value*2.54)) elif unit == 'cm' or unit == '厘米': print('%f厘米 = %f英寸' % (value,value/2.54)) else: print('请输入有效的单位') print('-----------------------------------------') """ 获取随机数 """ face = randint(1,6) if face ==1: result='aaaa' elif face ==2: result='bbbb' elif face ==3: result = 'ccc' else: result ='dddd' print(face)
false
7787a1ed4e8b95bf811896c33a959f52eac0ca48
kahnadam/UdemyPython3
/bouncer.py
361
4.3125
4
# ask for age age = input("How old are you? ") #make sure they entered an age if age: #convert age input to integer age = int(age) if age >= 21: print("You can enter and can drink!") elif age >= 18: print("You can enter but you'll be marked as underage") else: print("You cannot come in") #prompt to enter an age else: print("Please enter an age!")
true
a788752fd4863104af23923bbbd551a64f571d89
LAnastasiia/knapsack_problem
/knapsack_matrix.py
2,705
4.4375
4
def knapsack(arr, weight): """ This function implements solving for the Knapsack problem using dynamic programming approach to efficiently fit elements with maximum value but suitable weight into a knapsack. :param arr: array (list) of lists [value, weight] :param weight: total weight of knapsack, which can not be exceeded by any fitted element :return: array (list) of indexes of fitted element (indexation from the input array arr) """ mtrx_len = weight+1 prev = [0] * mtrx_len # List for already fitted elements. prev_pathes = dict([(w, []) for w in range(weight+1)]) # Dict of pathes of fitted elements. curr = [] # Intialize curr row for further usage. curr_pathes = [] def take_prev(): """ Auxiliary function to add only previously fitted elements to the matrix row. """ curr[w] = prev[w] path = prev_pathes[w] curr_pathes[w].extend(path) def take_element(): """ Auxiliary function to add an element and some fitting previous elements to the matrix row. """ path = prev_pathes[w-element[1]] + [i] curr[w] = r2 curr_pathes[w].extend(path) for i in range(len(arr)): # Search for optimal way to fit each element. curr = [0] * mtrx_len # Nullify current row of matrix to add content. curr_pathes = dict([(w, []) for w in range(weight+1)]) for w in range(weight+1): element = arr[i] # Current element. if w - element[1] < 0: take_prev() else: r1 = prev[w] # Can't take this element. r2 = prev[w - element[1]] + element[0] # Take element + try to fit previous ones. if r2 > r1: take_element() else: take_prev() prev = curr # Update previous row for the next iteration. prev_pathes = curr_pathes # print(">>", curr) # print("--", curr_pathes) optimal_values = curr[-1] return optimal_values, curr_pathes[weight] if __name__ == "__main__": arr = [[7, 5], [8, 4], [9, 3], [10, 2], [1, 10], [3, 15], [8, 10], [6, 4], [5, 3], [7, 3]] # arr = [[7, 5], [8, 4], [9, 3], [10, 2], [1, 10]] print('\n', knapsack(arr, 20))
true
ce39d02c2d249c5bb5c0e730076c0a2b296aab9a
wiraphat2711/workshop2
/string/f-string.py
265
4.15625
4
name = "pai" age = 21 result = f" My name is {name}, and I am {age} " # ใช้ f เเทนเรียก format ใช้ได้กับ python3.6 result2 = " My name is {}, and I am {} ".format(name, age) print("result", result) print("result2", result2)
false
aad40a2879744334741b50774fb8b9a5aa9ac79d
saikrishnareddykatta/Python-DeepLearning
/ICP 2/Source/stringalternative.py
402
4.15625
4
def string_alternative(): string_name = input("Please enter any string: ") print(string_name) # length of the string sl = len(string_name) print(sl) i = 0 # creating a new string new_string = "" while i < sl: if i % 2 == 0: new_string += string_name[i] i = i+1 print(new_string) if __name__ == '__main__': string_alternative()
true
e04a595b944cd45b88aba6f4493624bd40878944
akriticg/Google_Interview_Prep
/01_MIT_insertion_sort.py
351
4.15625
4
def insertion_sort(arr): arr_len = len(arr) for i in range(1, arr_len): temp = arr[i] j = i - 1 while j >= 0 and temp < arr[j]: # reverse < to > in temp < arr[j] for reverse sorting arr[j+1] = arr[j] j -= 1 arr[j+1] = temp print(arr) insertion_sort([12, 11, 13, 5, 6])
false
7db1410b713ec5529db21174f2b97b6b3a357bb2
akriticg/Google_Interview_Prep
/11_GFG_linkedlist_insertion.py
1,799
4.15625
4
''' Given a linked list which is sorted, how will you insert in sorted way Given a sorted linked list and a value to insert, write a function to insert the value in sorted way. Initial Linked List SortedLinked List Linked List after insertion of 9 UpdatedSortedLinked List https://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/ ''' class Node(): def __init__(self, data): self.data = data self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self, newdata): self.data = newdata def setNext(self, newnext): self.next = newnext class LinkedList(): def __init__(self): self.head = None def sortedInsert(self, newnode): if self.head is None: newnode.next = self.head self.head = newnode elif self.head.data >= newnode.getData(): new_node.next = self.head self.head = new_node else: current = self.head while(current.next is not None and current.next.data < new_node.data): current = current.next new_node.next = current.next current.next = new_node def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next # Driver program llist = LinkedList() new_node = Node(5) llist.sortedInsert(new_node) new_node = Node(10) llist.sortedInsert(new_node) new_node = Node(7) llist.sortedInsert(new_node) new_node = Node(3) llist.sortedInsert(new_node) new_node = Node(1) llist.sortedInsert(new_node) new_node = Node(9) llist.sortedInsert(new_node) print("Create Linked List") llist.printList()
true
a1dd093ad5dea0f597e175fcd50c9aa2c82e1534
Melnychuk17/lab8
/8.1.2.py
1,332
4.1875
4
# виведіть на екран транспоновану матрицю 3*3 (початкова матриця задана користувачем). # Мельничук Олени 122В # імпортуємо бібліотеку numpy import numpy as np # зациклюємо while True: # вводимо розмірність матриці n, m = int(input('Enter the number of lines: ')), \ int(input('Enter the number of columns: ')) # перевіряємо чи вона 3 на 3 while n != 3 or m != 3: n, m = int(input('Enter the number of lines: ')), \ int(input('Enter the number of columns: ')) # ініціалізуємо елементи нулем заданого типу даних і вказуємо що це int matrix = np.zeros((n, m), dtype=int) for i in range(n): # елементи в рядку for j in range(m): # елементи в стовпці # заповнюємо і транспонуємо матрицю matrix[i, j] = int(input(f'A[{j + 1},{i + 1}]=')) print('The transposed matrix') print(matrix) # запит на виконання програми ще раз result = input('Want to restart? If yes - 1, no - other: ') if result == '1': continue else: break
false
662d354eb6ca8924a4d63a9faca669f02018f172
CybrKay/List_RandomNumber
/Minimum_From_RandomList.py
583
4.25
4
# create random list and find minimum number from random list import random import string random_list = [] length_elemet = int(input("Enter length of list: ")) # take length of list from user for i in range(length_elemet): random_list.append(random.randint(1, length_elemet)) # append random number to list minimum = random_list[0] for i in range(len(random_list)): if random_list[i] < minimum: # find minimum number from random list minimum = random_list[i] print("The Random List is: ", random_list) print("Minimum From Random List is: " , minimum)
true
d3e1055f9d35835fed17996e059025ee047aac0b
garethquirke/advancedpy
/listcomprehension.py
1,404
4.3125
4
''' List Comprehension and Generators --------------------------------- range() is a commonly used generator in python, it generates values in order. These two look quite similar so what is the difference? - a generator creates the values on the fly, the values are created dynamically - the amount of memory used is alot lower since it takes more time to create the list - comprehension places the entire list into memory - so it is faster but the penalty is memory use when to use generators or comprehension? - Big list of values? generators ''' # Generator xyz = (i for i in range(50000000)) print(list(xyz)[:5]) # Comprehension xyz = [i for i in range(50000000)] print(xyz[:5]) # generator example inputs = [4,7,9,11,3,5,8] def divide(num): if num % 5 == 0: return True else: return False mylist = (i for i in inputs if divide(i)) print(list(mylist)) # here each element is cycled through the function, it's not copied in memory # notice how it needs to be parsed into a list since it is a generator object initially # Comprehension example mylist = [i for i in inputs if divide(i)] print(mylist) # Generator expression (x*2 for x in range(256)) for i in range(5): for ii in range(3): print(i,ii) # List comprehension other examples [x*2 for x in range(256)] [print(i,ii) for ii in range(3)] [[print(i,ii) for ii in range(3)] for i in range(5)]
true
6f3209f3b8050ed2a5d64e58e021194146552c53
machenxing/my-algorithm-training
/python/q-series/Q8.6.py
2,466
4.25
4
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' Towers of Hanoi: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted inascendingorder of size from top to bottom (i.e. each disk sits on top of an even larger one). You have the following constraints: (1) Only one disk can be moved at a time. (2) A disk is slid off the top of one tower onto another tower. (3) A disk cannot be placed on top of a smaller disk. Write a program to move the disks from the frst tower to the last using Stacks ''' import sys class Multistacks: def __init__(self, stacksize): self.numstacks = 3 self.array = [0] * (self.numstacks * stacksize) self.sizes = [0] * self.numstacks self.stacksize = stacksize def Push(self, item, stacknum): if self.Isfull(stacknum): raise Exception('%s is full' % stacknum) self.sizes[stacknum] += 1 self.array[self.IndexOfTop(stacknum)] = item def Pop(self, stacknum): if self.Isempty(stacknum): raise Exception('%s is empty' % stacknum) item = self.array[self.IndexOfTop(stacknum)] self.array[self.IndexOfTop(stacknum)] = 0 self.sizes[stacknum] -= 1 return item def Isempty(self, stacknum): return self.sizes[stacknum] == 0 def Isfull(self, stacknum): return self.sizes[stacknum] == self.stacksize def IndexOfTop(self, stacknum): offset = self.stacksize * stacknum return offset + self.sizes[stacknum] - 1 def Size(self, stacknum): return self.sizes[stacknum] def Tower(N): newstack = Multistacks(N) for i in range(N, 0, -1): newstack.Push(i, 0) return newstack def operate(N, start, buff, end, stack): if N == 1: stack.Push(stack.Pop(start), end) else: operate(N - 1, start, end, buff, stack) operate(1, start, buff, end, stack) operate(N - 1, buff, start, end, stack) def printTower(newStack, stacknum): if not newStack.Isempty(stacknum): for i in range(newStack.stacksize): print ''.join('-' for i in range(newStack.array[newStack.IndexOfTop(stacknum) - i])) if __name__ == '__main__': N = 5 tower = Tower(N) print 'Tower in 0' printTower(tower, 0) operate(N, 0, 1, 2, tower) print 'Tower in 2' printTower(tower, 2)
true
add2f225455e99d57443893db6a73f9239b849e8
machenxing/my-algorithm-training
/python/q-series/Q8.2.py
1,720
4.34375
4
''' Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits"such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right ''' ''' solution 1 ''' def getPath(maze): if len(maze)==0 or maze==None: return None path=[] if hasPath(maze,len(maze)-1,len(maze[0])-1,path): return path return None def hasPath(maze,row,col,path): if row<0 or col<0 or not maze[row][col]: return False isAtorigin=(row==0 ) and (col ==0) if isAtorigin or hasPath(maze,row-1,col,path) or hasPath(maze,row, col-1,path): point=(row,col) path.append(point) return True return False ''' solution 2 ''' def getPathwithMemory(maze): if maze==None or len(maze)==0: return None path=[] failedpoint=[] if hasPathwithMemory(maze,len(maze)-1,len(maze[0])-1,path,failedpoint): return path return None def hasPathwithMemory(maze, row, col, path, failedPoints): if row<0 or col<0 or not maze[row][col]: return False point=(row,col) if point in failedPoints: return False isAtorigin = (row == 0) and (col == 0) if isAtorigin or hasPathwithMemory(maze,row-1,col,path,failedPoints) or hasPathwithMemory(maze,row,col-1,path,failedPoints): path.append(point) return True failedPoints.append(point) return False if __name__ == '__main__': maze=[[True,True,False],[False,True,True],[False,False,True]] print getPath(maze=maze) print getPathwithMemory(maze=maze)
true
04575cc6b399c951f7e5a33fc9408b6fbb9cc188
machenxing/my-algorithm-training
/python/q-series/Q8.1.py
1,233
4.1875
4
''' Triple Step: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. ''' ''' Time Limit Exceeded ''' def TripleHop(n): if n < 0: return 0 if n == 0: return 1 if n == 1: return 1 return TripleHop(n - 1) + TripleHop(n - 2) + TripleHop(n - 3) def TripleHop2(n): if n < 0: return 0 if n == 0 or n == 1: return 1 if n == 2: return 2 if n == 3: return 4 result = [1, 2, 4] if n > 3: for i in range(n - 3): result.append(result[-1] + result[-2] + result[-3]) return result[-1] if __name__ == '__main__': print TripleHop(1) print TripleHop(2) print TripleHop(3) print TripleHop(4) print TripleHop(5) print TripleHop(6) print TripleHop(7) print TripleHop(8) print TripleHop(9) print TripleHop(10) print TripleHop2(1) print TripleHop2(2) print TripleHop2(3) print TripleHop2(4) print TripleHop2(5) print TripleHop2(6) print TripleHop2(7) print TripleHop2(8) print TripleHop2(9) print TripleHop2(10)
true
54ca1f85396111afc005ed600a15eb66b465e349
amitsaxena9225/XPATH
/jayanti/venv/function.py
617
4.25
4
#i=[1,2,3,4,5,6,7] #print(i) my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) '''0 -object ,1\ ,2\ ,3\ ,4,\ 5,6,7,8,9,10 object/iterable(0) ------>iter() --0------>iterator(object)----->next()----1 object/iterable(1) ------>iter() --1------>iterator(object)----->next()----2 object/iterable(1) ------>iter() --1------>iterator(object)----->next()----9 object/iterable(1) ------>iter() --1------>iterator(object)----->next()---- 0,9'''
false
e6da34831a48a98c7ab7bfb73575cccba22e88c4
amyjberg/algorithms
/python/merge-sort.py
1,596
4.25
4
# merge sort algorithm: # divide into subarrays of one element # merge every two subarrays together so they stay sorted # continue merging every two subarrays until we just have one sorted array def mergeSorted(listA, listB): pointerA = 0 pointerB = 0 merged = [] while pointerA < len(listA) and pointerB < len(listB): # we break out of the loop once one pointer finishes its list if listA[pointerA] < listB[pointerB]: merged.append(listA[pointerA]) # modifies original list pointerA += 1 elif listB[pointerB] < listA[pointerA]: merged.append(listB[pointerB]) pointerB += 1 else: # they are equal, so we can add and increment both merged = merged + [listA[pointerA], listB[pointerB]] pointerA += 1 pointerB += 1 # when we break out of the while loop, we might have some extra unmerged elements in one of the arrays if pointerA < len(listA): # we have leftover A elements to append return merged + listA[pointerA:] elif pointerB < len(listB): return merged + listB[pointerB:] else: # we finished both return merged def split(list): mid = Math.floor(len(list) / 2) leftHalf = list[0:mid] rightHalf = list[mid:] return [leftHalf, rightHalf] def mergeSort(list): if len(list) == 1 | len(list) == 0: return list else: halves = split(list) left = halves[0] right = halves[1] # recursive call on each half, so each half will get split into half until we get to our base case with length 1, when we will start merging them return merge(mergeSort(left), mergeSort(right))
true
f3b416c2d7f4191776123cd5a8181df749c6ec08
kellyfitmore/random-python
/gcf.py
607
4.1875
4
#Stephen Duncanson #This program finds the greatest common factor of two integers #[0] is larger number, [1] is smaller number #0 % 1 = remainder #When remainder = 0, [1] = gcf numbers = [0,0] numbers[0] = int(input("Enter the larger number: ")) numbers[1] = int(input("Enter the smaller number: ")) remainder = numbers[0] % numbers[1] while remainder != 0: numbers[0] = numbers[1] numbers[1] = remainder remainder = numbers[0] % numbers[1] print("The gcf is", numbers[1]) #ANOTHER SOLUTION Break up facotes into list and use a for loop, for facrots in list if #in other factors list then gcf?
true
c26728e415c8134342ab7a5b9307b4e2e869a007
zerocod3r/InterviewQuestions
/Tree Data Structure/invert_the_binary_tree.py
872
4.3125
4
# Given a binary tree A, invert the binary tree and return it. # Inverting refers to making left child as the right child and vice versa. # Example Input # Input 1: # 1 # / \ # 2 3 # Input 2: # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # Example Output # Output 1: # 1 # / \ # 3 2 # Output 2: # 1 # / \ # 3 2 # / \ / \ # 7 6 5 4 # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def invertTreeUtil(A): if A == None: return else: invertTreeUtil(A.left) invertTreeUtil(A.right) temp = A.left A.left = A.right A.right = temp class Solution: # @param A : root node of tree # @return the root node in the tree def invertTree(self, A): invertTreeUtil(A) return A
true
087c6f209bc3db9ca6ecd2685cadeadb00d1d090
paolobejarano/Algorithms_in_Python
/exhaustive_root_square.py
465
4.375
4
#This program uses exahustive enumeration to find an aproximation of the square root of any given number larger than 1. x = int(input("Enter a number: ")) epsilon = 0.01 step = epsilon**2 numGuesses = 0 answer = 0.0 while abs(answer**2 - x) >= epsilon and answer <= x: answer += step numGuesses += 1 print('numGuesses = ', numGuesses) if abs(answer**2 - x) >= epsilon: print('Failed on square root of ', x) else: print(answer, 'is close to square root of', x)
true
b04b636f552623d443374655ce5e2397debd6ec0
lvaka/Python
/Practice/Censor.py
601
4.21875
4
def censor(text, word): ##censors the word out of block of text. Does not account for punctuation wordlist = [] bleep = "" for letter in word: ##Creates the censored word bleep += "*" wordlist = text.split() ##Splits text into a list for search in range(len(wordlist)): ##Searches the wordlist for word to censor if wordlist[search] == word: ##if it finds the word, replace wordlist[search] = bleep return " ".join(wordlist) ##Joins the list back together into a string print (censor("hahahahahaha erere dope cope", "dope"))
true
9d7ab9c430845c986a93f3a7f9d263b2dce04c54
KristaProkop/web_dev_examples
/python/abc_order.py
1,314
4.25
4
# # Assume s is a string of lower case characters. # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print # Longest substring in alphabetical order is: beggh # In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print # Longest substring in alphabetical order is: abc # Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head. s = "bqukpkalqifcdsqosdzltmf" substring = '' iterator = 0 mylist = [''] for index in range(iterator, len(s)): for count in range(iterator, len(s)-1): if s[count] <= s[count+1]: substring = substring + s[iterator] iterator+=1 elif s[count] > s[count+1]: substring = substring + s[iterator] if len(substring) > len(mylist[0]): mylist = [substring] iterator = count+1 substring = '' break print("Longest substring in alphabetical order is: "+ mylist[0])
true
c4bb33858b547873b5cac64b902eeccfc13a1e0b
KristaProkop/web_dev_examples
/python/arr_equality.py
1,004
4.1875
4
# Given an array of integers, find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1. # For example: # given the array {1,2,3,4,3,2,1} return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6. # given the array {1,100,50,-51,1,1} return the index 1, because at the 1st position of the array, the sum of left side of the index ({1}) and the sum of the right side of the index ({50,-51,1,1}) both equal 1. arr = [1,2,3,4,5,6] #arr = [1,2,3,4,3,2,1] def find_even_index(arr): for i, x in enumerate(arr): left_sum, right_sum = sum(arr[0:i]), sum(arr[i+1:]) if left_sum == right_sum: return i return -1 # def find_even_index(arr): # return [ (i, x) for i, x in enumerate(arr) if (sum(arr[0:i]) == sum(arr[i+1:])) ] print find_even_index(arr)
true
ff49aa6bf31ff0b76ecf86a8af0e88ec2d01ed61
rcantonio/assignment
/quadratic.py
832
4.28125
4
''' Assignment 3: Quadratic ''' print ("Welcome to the Program. Please enter the value of A, B, C, and X at the corresponding prompts.") a = int(input("What is the value of A? ")) b = int(input("What is the value of B? ")) c = int(input("What is the value of C? ")) x = int(input("What is the value of X? ")) ''' So the following lines of code are only meant to prevent the program from outputting "+-" on the quadratic equation when the user inputs a negative number. ''' quadratic="The following quadratic was entered: " + str(a) + "X^2" if ( b >= 0): quadratic += ("+" + str(b) + "X") else: quadratic += (str(b) + "X") if (c >= 0): quadratic += ("+" + str(c)) else: quadratic += (str(c)) print (quadratic) print("The value of the quadratic is: " + str((a*(x*x)) + (b*x) + c))
true
1476df2a5546336d67712c9155c66ee7e5ce738e
marcoaugustoandrade/python-lista-1
/19_calculo_numeros.py
239
4.125
4
n1 = int(input('Informe um número inteiro: ')) n2 = int(input('Informe outro número inteiro: ')) n3 = float(input('Informe um número real: ')) print("%d" % ((n1 * 2) + (n2 / 2))) print("%.2f" % (3 * n1 + n3)) print("%.2f" % (n3 ** 3))
false
bf56f8f688f754de50016c0f70bea9f62d103a83
mrudula-pb/Python_Code
/LeetCode/Reverse_String0202.py
1,096
4.375
4
# Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place # with O(1) extra memory. # You may assume all the characters consist of printable ascii characters. # # Example 1: # # Input: ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] # Example 2: # # Input: ["H","a","n","n","a","h"] # Output: ["h","a","n","n","a","H"] class Solution: def reverseString(self, Input): # Approach 1 # print(reversed(Input)) # prints list_reverseiterator object # for item in reversed(Input): # print(item) # Approach 2 # for item in Input[::-1]: # print(item) # Approach 3 length = int(len(Input)/2) i = 0 for item in range(length): swap = Input[item] Input[item] = Input[-1-i] Input[-1-i] = swap i += 1 return Input solution = Solution() Input = ["h","e","l","l","o"] solution.reverseString(Input)
true
99163ce4b87b5926b66705c7bcc4fae2fda1a521
mrudula-pb/Python_Code
/Udacity/Project2/Reverse_String.py
721
4.4375
4
def string_reverser(our_string): """ Reverse the input string Args: our_string(string): String to be reversed Returns: string: The reversed string """ # TODO: Write your solution here length = len(our_string) new_string = "" i = 0 for item in range(length): new_string += our_string[length - 1 - i] # print(new_string) i += 1 return new_string print("Pass" if ('retaw' == string_reverser('water')) else "Fail") print ("Pass" if ('!noitalupinam gnirts gnicitcarP' == string_reverser('Practicing string manipulation!')) else "Fail") print ("Pass" if ('3432 :si edoc esuoh ehT' == string_reverser('The house code is: 2343')) else "Fail")
true
d54a102501bba5dc2fb8c4adea137ca84d4cd519
mrudula-pb/Python_Code
/Udacity/Project2/Tree/Pre_Order_Reversal.py
1,023
4.21875
4
# this code makes the tree that we'll traverse class Node: def __init__(self, value=None): self.value = value self.left = None self.right = None def set_value(self, value): self.value = value def get_value(self): return self.value def set_left_child(self, left): self.left = left def set_right_child(self, right): self.right = right def get_left_child(self): return self.left def get_right_child(self): return self.right class Tree: def __init__(self, value): self.root = Node(value) def get_root(self): return self.root tree = Tree("APPLE") print(tree.get_root().value) tree.get_root().set_left_child(Node("BANANA")) print(tree.get_root().get_left_child().value) tree.get_root().get_left_child().set_left_child(Node("DATES")) print(tree.get_root().get_left_child().get_left_child().value) tree.get_root().set_right_child(Node('CHERRY')) print(tree.get_root().get_right_child().value)
false
c0f31a1bb656b1d808a67db28a2f0c27db698653
OnionXDD/Python-study
/pycook/ch2/4_text_match.py
1,574
4.40625
4
"""2.4. Matching and Searching for Text Patterns 问题: 文本匹配 解决方法: str.find(), str.endswith(), str.startswith() re """ # text = 'yeah, but no, but yeah, but no, but yeah' # print(text == 'yeah') # print(text.startswith('yeah')) # print(text.endswith('no')) # print(text.find('no')) text1 = '11/27/2012' text2 = 'Nov 27, 2012' import re # if re.match(r'\d+/\d+/\d+',text1): # print('yes') # else: # print('no') # # if re.match(r'\d+/\d+/\d', text2): # print('yes') # else: # print('no') datepat1 = re.compile(r'\d+/\d+/\d+') # 使用单个括号,匹配一个完整语句 integrated_match = datepat1.match(text1) print(integrated_match.group(0)) datepat2 = re.compile(r'(\d+)/(\d+)/(\d+)') # 使用多个括号,分别匹配每个括号中的内容,并用一个groups安置 divided_match = datepat2.match(text1) print('the date is ',divided_match.group(0), divided_match.group(1), divided_match.group(2), divided_match.group(3)) month, day , year = divided_match.groups() text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' all_match = datepat2.findall(text) print('findall',all_match) for month, day, year in all_match: print('{}-{}-{}'.format(year, month, day)) for m in datepat2.finditer(text): print(m.groups()) ''' notice 一般来说使用多个括号就是把整个字符串按括号分开 此时的group(0)表示整体,1、2、3表示每个个体 如果你不用r' '可能需要在' '使用//来定义反斜杠负号 findall 返回一个元组列表, finditer返回迭代器 '''
false
266d6ebe7f899793978b74ff94c18916e114799d
7ayushgupta/ESC101-Project-Track
/chat-app/Documentation/initial-study/GraphingData.py
1,384
4.15625
4
# code for executing query using input data import sqlite3 # creates a database in RAM con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("create table person (name, age, id)") print ("Enter 5 students names:") who = [raw_input() for i in range(5)] print ("Enter their ages respectively:") age = [int(raw_input()) for i in range(5)] print ("Enter their ids respectively:") p_id = [int(raw_input()) for i in range(5)] n = len(who) for i in range(n): # This is the q-mark style: cur.execute("insert into person values (?, ?, ?)", (who[i], age[i], p_id[i])) # And this is the named style: cur.execute("select * from person") # Fetches all entries from table print cur.fetchall() import matplotlib.pyplot as plt def graph_data(p_id,age): # plotting the points plt.plot(p_id, age, color='yellow', linestyle='dashed', linewidth = 3, marker='*', markerfacecolor='blue', markersize=12) # naming the x axis plt.xlabel('Persons Id') # naming the y axis plt.ylabel('Ages') # plt.plot(p_id,age) plt.show() print ("Enter 5 students names:") who = [raw_input() for i in range(5)] print ("Enter their ages respectively:") age = [int(raw_input()) for i in range(5)] print ("Enter their ids respectively:") p_id = [int(raw_input()) for i in range(5)] # calling graph function graph_data(p_id,age)
true
ad57a20a4c79510d392c5ee7bab418f07243906a
Hayk258/homework
/homework28.py
1,191
4.375
4
'''1. Create a python function factorial and import this file in another file and print factorial.''' # def factorial(n): # num = 1 # for i in range(2,n + 1): # num *= i # print(num) '''Write a Python function to calculate surface volume and area of a cylinder(Գլան). V=πr^2h and A=2πrh+2πr^2 ''' # def glan(cylinder,glan1): # pi=22/7 # height = float(input('Height of cylinder: ')) # radian = float(input('Radius of cylinder: ')) # volum = pi * radian * radian * height # sur_area = ((2*pi*radian) * height) + ((pi*radian**2)*2) # print('Volume is:',volum) # print("Surface Area is: ",sur_area) # glan(1,5) '''Write a Python function to calculate surface volume and area of a sphere. V = 4/3*π*r3 and A = 4*π*r2''' # def volumee(radian): # pi=22/7 # sur_area = 4 * pi * radian **2 # volume = (4/3) * (pi * radian ** 3) # print("Surface Area is: ", sur_area) # print("Volume is: ", volume) '''Write a Python function to print all primes smaller than or equal to a specified number. Call function:numbers(9) Output: (2, 3, 5, 7) ''' def function(n): for i in range(2,10): for j in range(2,i): if i %j == 0: break else: print(i)
true
24cb377a0f345095de125b47ff13a000b91f098d
alexapod/Stepic_1
/Stepic_2.4.2.py
1,011
4.28125
4
""" 2.4 Строки и символы Есть строка s = "abcdefghijk". В поле ответа через пробел запишите строки (без кавычек), полученные в результате следующих операций: # s = 'abcdefghijk' s[3:6] s[:6] s[3:] s[::-1] s[-3:] s[:-6] s[-1:-10:-2] Попробуйте найти ответ к этой задаче, не используя интерпретатор Python. Если без интерпретатора решить не получается, разберитесь, почему выводятся именно такие строки в каждом из вариантов. Итоговый формат ответа должен выглядеть следующим образом: abcd efg hijklmnop qrst uvw xy z """ s = 'abcdefghijk' print(s[3:6], end=" ") print(s[:6], end=' ') print(s[3:], end=' ') print(s[::-1], end=' ') print(s[-3:], end=' ') print(s[:-6], end=' ') print(s[-1:-10:-2])
false
ba93eec9ffeb2115d443b85956159702ac44def8
bacdoxuan/Regular-Expressions-in-Python
/check_regex.py
571
4.5625
5
"""How to check if a pattern is valid regex or not.""" import re def check_regex(): """Using re.complie to check if an input string a valid regex or not. Input: n: number of string you want to test the next n lines are your inputs. Each input wil return True if your input is a valid regex pattern, or False if it's not. """ for _ in range(int(input())): try: re.compile(input()) except Exception: print('False') else: print('True') if __name__ == '__main__': check_regex()
true
c622a62d50e625b69be675aa14142d10c11ed371
larryquinto/STG-Python-Challenges
/challenge4/fibonacci_sequence.py
489
4.3125
4
# Function for nth Fibonacci number with user input n = (int(input("Enter A Whole Number Greater Than Zero For The Fibonacci Sequence, Please. Then, Press Enter: "))) def fibonacci(n): if n <= 0: print("Sorry! Please enter a number greater than zero.") # First Fibonacci number is 0 elif n == 1: return 0 # Second Fibonacci number is 1 elif n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) # print(fibonacci(n))
true
fed797088021098e30237e8a35c4c839c04cc307
nikpil/Python
/HW2.py
451
4.125
4
time = int(input('введите время в секундах ')) hours = time // 3600 # узнаем сколько часов total_seconds = time % 3600 # узнаем сколько еще осталось секунд minutes = total_seconds // 60 # узнаем сколько минут seconds = total_seconds % 60 # узнаем оставшиеся секунды print(time,(f"секунд - это {hours}:{minutes}:{seconds}"))
false
c385e68ef5949cb98702760dc6da95f56513b442
KhalilC/RedditPython
/highlowguess.py
1,755
4.15625
4
# high low guessing game # computer randomly selects a number and user attempts to guess it # each guess tells the user if too high or low import random tries = 0 def computer_guess(): random_number = random.randint(0,100) return random_number def intro(): print """Welcome to the computer guessing game! Can you guess the random number? After each attempt I will tell you if you are too high or too low. Once you have guessed the correct number, I will also tell you your total number of guesses.""" def user_guess(): guess = raw_input('\nPlease enter a guess: ') while not isinstance(guess, int): try: guess = int(guess) return guess except: guess = raw_input('Only numbers please! Try again: ') def compare_guess(user, computer): global tries if user > computer: tries += 1 return "Lower" elif user < computer: tries += 1 return "Higher" else: tries += 1 return "Congrats you got it right! It took you %i tries" % tries def play_again(): answer = '' while answer not in ['y','n']: answer = raw_input('Do you want to play again?(y/n) ').lower() if answer == 'y': main() else: print "Thanks for playing! Goodbye!" def main(): intro() computer_g = computer_guess() user_g = user_guess() if user_g == computer_g: print 'Congrats you got it right on the first try' else: print(compare_guess(user_g, computer_g)) while user_g != computer_g: user_g = user_guess() print(compare_guess(user_g, computer_g)) play_again() main()
true
6a6a9f69ab9ee1c7fbad415f7c870ab58ef0638d
yushixngheng/tutorial
/python/example/yichang.py
1,576
4.1875
4
#Python异常的处理 #使用try...except语句,假如try出现了某种异常,则执行except下面的语句 try: print i except NameError: #这里一定要指明异常类型 i = 9 i += 10 print "刚才i没定义,处理异常之后,i的值为:" + str(i) #处理多种异常 try: print i+j except NameError: i=j=0 print "刚刚i和j没有进行初始化数据,现在我们将其都初始化位0,结果是:" print i+j except TypeError: print "刚刚i和j类型对应不上,我们转换一下类型即可处理异常,处理后:结果是" \ +str(i)+str(j) #异常的引发 #1/用raise引发一个系统的错误类 #i = 8 #print i #if i>7: # print 9 # raise NameError # print 10 #2/自定义一个异常并用raise引发 class RhhError(Exception):#按照命名规范,以Error结尾, #并且自定义异常需要继承exception类 def __init__(self): Exception.__init__(self) try: i = 8 if i > 7: raise RhhError except RhhError, a: print "RhhError:错了就是错了" #3/自定义一个多参数的异常并用raise引发 class HhhError(Exception): def __init__(self, x, y): Exception.__init__(self, x, y) self.x = x self.y = y try: x = 3 y = 1 if x > 2 or x + y > 7: raise HhhError(x, y) except HhhError: print "HhhError:x必须小于2且x+y小于等于7,现在的x是"+str(x)+"现在的y是" +str(y)
false
21ea14b59cd3805f26b74050f1db6a335efe25bc
jack1993ire/Assignment-3-
/magicdate.py
502
4.4375
4
# This program is used to tell you about a magic date # Magic means the month times the day is equal to the year # asking user to enter month, day and year month = int(input("Enter month (in numerical form) : ")) day = int(input("Enter day (in numerical form) : ")) year = int(input("Enter year (last two digits) : ")) # if month times day is equal to year then the date is magic otherwise date is not magic if month * day == year: print("Date is magic.") else: print("Date is not magic.")
true
c076bf5a759216b4f06efc09b9a46a61378ff0f3
CoffeeCodeAndCreatine/theBasicsOfComputerScience
/concepts/traversal/bfs.py
1,841
4.25
4
class Node: def __init__(self, key): self.data = key self.left = None self.right = None def print_level_order_recursive(root_node): node_height = calc_node_height(root_node) for i in range(1, node_height + 1): print_given_level(root_node, i) def print_level_order_iterative(root_node): if root_node is None: return queue = [] queue.append(root_node) while len(queue) > 0: print(queue[0].data) root_node = queue.pop(0) if root_node.left is not None: queue.append(root_node.left) if root_node.right is not None: queue.append(root_node.right) def print_given_level(root_node, level): if root_node is None: return if level == 1: print(str(root_node.data)) elif level > 1: print_given_level(root_node.left, level - 1) print_given_level(root_node.right, level - 1) def calc_node_height(node): if node is None: return 0 else: left_height = calc_node_height(node.left) right_height = calc_node_height(node.right) if left_height > right_height: return left_height + 1 else: return right_height + 1 def create_sample_tree(): """ sample tree follows the form 1 -|- | | 2 3 -|- | | 4 5 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) return root def main(): print("creating sample tree") root = create_sample_tree() print("Running examples of BFS with recursion") print_level_order_recursive(root) print("Running examples of BFS with iteration") print_level_order_iterative(root) if __name__ == "__main__": main()
true
1f106f86e4142556078e2695c7d59c30003fc789
gutkinnicolasg/Crypto
/PasswordValidator.py
2,663
4.25
4
#!/usr/bin/python3 # Password Validator # by Guillaume Gutkin-Nicolas # Global variable list that contains all the allowed special characters whitelist = ['!','@','#','$','%','^','&','*','-','_','+','=','?','>','<','.',','] # Global variable list that contains all the words that aren't allowed blacklist = ['password', 'secureset'] # checkWhite function def checkWhite(x): for i in whitelist: if x == i: return True return False # rule1 function def rule1(password): if len(password) >= 8: return True return False # rule2 function def rule2(password): for i in password: if i.isupper(): return True return False # rule3 function def rule3(password): for i in password: if i.islower(): return True return False # rule4 function def rule4(password): for i in password: if i.isdigit(): return True return False # rule5 function def rule5(password): for i in password: if checkWhite(i): return True return False # rule6 function def rule6(password): for i in blacklist: if i == password.lower(): return True return False # getWord function def getWord(password): word = "" for i in password: if i.isalpha(): word += i return word # checkRules function def checkRules(password): if rule1(password) != True: print("Password isn't long enough!\n") return False elif rule2(password) != True: print("Password doesn't have an uppercase letter!\n") return False elif rule3(password) != True: print("Password doesn't have a lowercase letter!\n") return False elif rule4(password) != True: print("Password doesn't have a number!\n") return False elif rule5(password) != True: print("Password doesn't have a special character!\n") return False elif rule6(getWord(password)) == True: print("Word is part of the forbidden list!\n") return False return True # Main function if __name__=="__main__": print("Welcome to the Password Validator!\n") print("Rule 1: Minimum length of 8") print("Rule 2: Includes Uppercase") print("Rule 3: Includes Lowercase") print("Rule 4: Includes Number") print("Rule 5: Includes Special Character: !@#$%^&*-_+=?><.,") print("Rule 6: Doesn't include these words: password, secureset\n") while True: password = input("Please enter a password: ") if checkRules(password) == True: print("Password Accepted...") break
false
dbb09a01beb4d3ae59a4a9f714d3e79fccdf5006
HFStudios/python-application
/Backup/trig.py
2,564
4.125
4
import math #Strings to print out as results scalene = "Scalene Triangle" equilateral = "Equilateral Triangle" right = "Right Triangle" notTri = "Not a Triangle" isosceles = "Isosceles Triangle" #Runs if user gives side lengths instead of points def givenLengths(side1, side2, side3): #Makes it so that the lengths can be put in any order and still get the right results l1 = max(side1, side2, side3) l3 = min(side1, side2, side3) l2 = (side1 + side2 + side3) - l1 - l3 #Finds out what type of triangle it is if (((l2 + l3) > l1) and ((l1 + l2) > l3) and ((l1 + l3) > l2)): if ((l1 ** 2) == (l2 ** 2) + (l3 ** 2)): return right elif (l1 == l2 == l3): return equilateral elif ((l1 != l2) and (l1 != l3) and (l3 != l2)): return scalene elif ((l1 == l2) or (l1 == l3) or (l2 == l3)): return isosceles else: return notTri else: return notTri #Runs if user gives points instead of side lengths def givenPoints(x1, y1, x2, y2, x3, y3): #Gets length of sides, plugs into givenLengths() to get triangle type dist1 = math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2)) dist2 = math.sqrt(((x3 - x2) ** 2) + ((y3 - y2) ** 2)) dist3 = math.sqrt(((x3 - x1) ** 2) + ((y3 - y1) ** 2)) triType = givenLengths(dist1, dist2, dist3) return(dist1, dist2, dist3, triType) #Runs terminal version of program def main(): #Find out if user wants to use points or lengths of sides while True: getInput = input("Find the triangle with lengths (1) or points (2)? ") if(getInput == "lengths" or getInput == "1"): wanted = 1 break elif(getInput == "points" or getInput == "2"): wanted = 2 break else: print("Choose a real selection: ") #Ask details about side lenths if (wanted == 1): side1 = float(input("What is side 1? ")) side2 = float(input("What is side 2? ")) side3 = float(input("What is side 3? ")) print(givenLengths(side1, side2, side3)) #Details if wants to use points else: x1 = float(input("What is x1? ")) y1 = float(input("What is y1? ")) x2 = float(input("What is x2? ")) y2 = float(input("What is y2? ")) x3 = float(input("What is x3? ")) y3 = float(input("What is y3? ")) print(givenPoints(x1, y1, x2, y2, x3, y3)) #If file is run as standalone, run main() function if __name__ == "__main__": main()
true
55138f9455847fdc2164532f57c67b610bd2ebb3
zketrina/-Python-Lesson-3
/task3.py
519
4.1875
4
# Реализовать функцию my_func(), # которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def my_func (num_1,num_2,num_3): num_1 = int(num_1) num_2 = int(num_2) num_3 = int(num_3) return sum(sorted([num_1,num_2,num_3])[1:]) print(my_func(input("Введите число:"),input("Введите число:"),input("Введите число:")))
false
05345f7b13c21d463adb9154dc3d6f22ab7c419f
cheeyeo/python_oop
/data_structures/set_ops.py
394
4.125
4
# Operations on sets # alternate way of declaring a set first_artists = { "Sarah Brightman", "Guns N' Roses", "Opeth", "Vixy and Tony", } second_artists = {"Nickelback", "Guns N' Roses", "Savage Garden"} print("All: ", first_artists.union(second_artists)) print("Common between two sets: ", first_artists.intersection(second_artists)) print("In either set but not both: ", first_artists.symmetric_difference(second_artists))
true
876fd38cfb47fc2edf763ea0baeb8c512097dc46
JakeWags/Random-Python-For-Friends
/GeoCalc.py
806
4.25
4
# Calculates geometric shapes' attributes. import math def calculate(shape): if shape == "Square": sideLength = int(input("Side length: ")) print("Perimeter: " + str(sideLength * 4) + ", Area: " + str(sideLength * sideLength)) elif shape == "Equal Triangle": base = int(input("Base: ")) print("Perimeter: " + str(base * 3) + ", Area: " + str(base * base)) elif shape == "Circle": radius = int(input("Radius: ")) print("Circumference: " + str(2 * math.pi * radius) + ", Area: " + str(math.pi * radius * radius)) shapes = ["Square", "Equal Triangle", "Circle"] shapeChoice = input("Choose one of the following options: " + str(shapes) + ":\n") for shape in shapes: if shapeChoice == shape: calculate(shape)
true
573d4f25206cb22cb2be70f8e643fb7a395ee171
sabreezy11/Object-Orientated-Programming-OOP-
/accounts.py
1,071
4.3125
4
class Account: """Simple account class with balance""" def __init__(self, name, balance): #__init__ is used to initialize a class self.name = name self.balance = balance print("Account created for " + self.name) def deposit(self, amount): if amount > 0: self.balance += amount #adding 'amount' to 'balance' self.show_balance() def withdraw(self, amount): if 0 < amount <= self.balance: self.balance -= amount #deducting 'amount' from 'balance' else: print("You can't withdraw more than your account balance.") self.show_balance() def show_balance(self): print("Balance is {}".format(self.balance)) if __name__ == '__main__': sabrina = Account("Sabrina", 0) sabrina.show_balance() sabrina.deposit(1000) # sabrina.show_balance() ##this is now implemented in 'deposit' method sabrina.withdraw(1500) # sabrina.show_balance() ##this is now implemented in 'withdraw' method
true
b83e6df38f00256825092eba3fa9c3930f34337a
Giorc93/PythonCourse
/FirstSectExer/if-elif-else.py
430
4.25
4
# Use input to set two numbers, crate a function that returns the highest number def highestNum(): numOne = input('Insert first number: ') numTwo = input('Insert second number: ') if numOne > numTwo: message = "The highest number is " + numOne elif numTwo > numOne: message = "The highest number is " + numTwo else: message = "The numbers are equal" print(message) highestNum()
true
b4164cf79cb8bf5477b51d14ffe1e81a75d45f7d
Giorc93/PythonCourse
/Exceptions/exception2.py
451
4.1875
4
def checkAge(age): if age < 0: # Creating the exception raise TypeError('The age is not valid. Should be greater than 0') if age < 20: return "Too young" if age < 40: return 'Young' if age < 65: return 'Mature' if age < 100: 'Take care of yourself' print(checkAge(-9)) # After showing the error the program will stop. Should use the try and catch block to keep the program runing
true
dbcce701bca340dec19f65bfb56430994e48fb92
lasha09/luisa.github.com
/challenge.py
400
4.21875
4
#imports the ability to get a random number (we will learn more about this later!) from random import * #Create the list of words you want to choose from. name = ["amber","jelly","elanor","paola", "imani", "estella","ms.c","ms.elizabeth", "sam"] namelist= "" for x in range (2): #Generates a random number x=randint(0, len(name)-1) namelist +=name[x] + " " print(namelist)
true
6f28103bc085d99cb06b2dbcc238deb3aef63720
swools/python_work
/Chapter 9/users.py
1,443
4.125
4
class User: """ Store information about each user """ def __init__(self, first_name, last_name, age, location): self.first_name = first_name.title() self.last_name = last_name.title() self.age = age self.location = location.title() self.full_name = f"{self.first_name} {self.last_name}" self.login_attempts = 0 def describe_user(self): print( f"\nFirst Name: {self.first_name}\nLast Name: {self.last_name}\nAge: {self.age}\nLocation: {self.location}") def greet_user(self): print(f"Welcome, {self.full_name}") def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 class Privileges: """Store list of a users privileges""" def __init__(self): self.privileges = ['can add post', 'can delete post', 'can ban user'] def show_privileges(self): for privilege in self.privileges: print(f"{privilege}") class Admin(User): def __init__(self, first_name, last_name, age, location): """Initialize attributes of the parent class""" super().__init__(first_name, last_name, age, location) self.privileges = Privileges() # admin = Admin('steve', 'wool', 28, 'new jersey') # print(f"\n{admin.full_name} is an admin and has the following privileges") # admin.privileges.show_privileges()
true
a9f9de6abec3ccc2ada95576975aba2e94809e7a
anangferdi/rf-demo
/learn_python.py
2,739
4.5
4
### You can find more detail on https://www.programiz.com/python-programming/tutorial ### Just print it print("hai") ### Variables #We do not need to define variable type in Python. a = 5 print("a =", a) a = "Test" print("a =", a) ### Operators x = 14 y = 4 # Add two operands print('x + y =', x+y) # Output: x + y = 18 # Subtract right operand from the left print('x - y =', x-y) # Output: x - y = 10 # Multiply two operands print('x * y =', x*y) # Output: x * y = 56 # Divide left operand by the right one print('x / y =', x/y) # Output: x / y = 3.5 # Floor division (quotient) print('x // y =', x//y) # Output: x // y = 3 # Remainder of the division of left operand by the right print('x % y =', x%y) # Output: x % y = 2 # Left operand raised to the power of right (x^y) print('x ** y =', x**y) # Output: x ** y = 38416 ### Get input from user # string_input = input("Enter your name : ") # print("Welcome", string_input) ### Python data structure ##List """ A list is created by placing all the items (elements) inside a square bracket [] separated by commas. It can have any number of items and they may be of different types (integer, float, string etc.) """ # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed data types my_list = [1, "Hello", 3.4] #Here's how you can access elements of a list. language = ["French", "German", "English", "Polish"] # Accessing first element print(language[0]) # Accessing fourth element print(language[3]) ### Dictionaries """ Dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. """ # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} person = {'name':'Jack', 'age': 26, 'salary': 4534.2} print(person['age']) # Output: 26 # Changing age to 36 person['age'] = 36 print(person) #adding item to dictionary person['gender'] = "Male" print(person) ### Python if else statement num = -1 if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") ### while loop n = 3 # initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # update counter print("The sum is", sum) ### For loop numbers = [6, 5, 3, 8, 4, 2] sum = 0 # iterate over the list for val in numbers: sum = sum+val print("The sum is", sum) ### Function def print_lines(): print("I am line1.") print("I am line2.") # function call print_lines() # add param on function def add_numbers(a, b): sum = a + b return sum result = add_numbers(4, 5) print(result)
true
60c2a0ca76702757573ff74bce9b219240f420e1
jazbassi1/pythonpractice
/hangmanGame.py
919
4.125
4
import random from words1 import words import string def get_valid_word(words): word = random.choice(words) # random selection from words list while '-' in word or ' ' in word: word = random.choice(words) return word.upper() def hangman(): word = get_valid_word(words) word_letters = set(word) # letters within the word alphabet = set(string.ascii_uppercase) used_letters = set() #what the user has guessed # get user input user_letter = input("Guess a letter: ").upper() if user_letter in alphabet - used_letters: used_letters.add(user_letter) if user_letter in word_letters: word_letters.remove(user_letter) elif user_letter in used_letters: print("You have already used that character. Please try again ") else: print("Invalid Character. Please try again ") hangman()
true
277d199897309827249c0f6dc0ae3ea0b3dc7008
doba23/Python_academy_Engeto
/2_lesson/11. destination.py
2,171
4.125
4
# Greet the client print('=' * 80) print('''Welcome to the DESTINATIO, place where people plan their trips''') print('=' * 80) # Offer destinations print('We can offer you the following destinations:') print('-' * 80) print(''' 1 - Prague | 1000 2 - Wien | 1100 3 - Brno | 2000 4 - Svitavy | 1500 5 - Zlin | 2300 6 - Ostrava | 3400 ''') print('-' * 80) # Get input from user about destination selection = int(input('Please enter the destination number to select: ')) # Assign variables appropriate data DESTINATIONS = ['Prague', 'Wien', 'Brno', 'Svitavy', 'Zlin', 'Ostrava'] PRICES = [1000, 1100, 2000, 1500, 2300, 3400] DISCOUNT_25 = ['Svitavy', 'Ostrava'] # Check, whether entered valid input # Get data from variables based on user's input destination = DESTINATIONS[selection - 1] if destination in DISCOUNT_25: print('Lucky you! You have just earned 25% discount for your destination -', destination) price = PRICES[selection - 1] # Calculate the price and check whether discount applicable for the selected destination # Introduce registration # Get input from user about personal data name = input('NAME: ') print('=' * 40) surname = input('SURNAME: ') print('=' * 40) birth_year = input('YEAR of BIRTH: ') print('=' * 40) email = input('EMAIL: ') print('=' * 40) password = input('PASSWORD: ') print('=' * 80) # if some of condition is not met, invalid variable is set to 1 invalid = 0 # Check if the user is older than 15 years old birth_year = int(birth_year) if birth_year > 2004: print('you are too young') invalid = 1 # Check if email contains @ symbol if not '@' in email: print('e-mail address is invalid') invalid = 1 # Check if password # - is at least 8 chars long, # - doesn't begin and end with a number # - and contains both letters and numbers if len(password) < 8: print ('password must be at least 8 characters long') invalid = 1 # Thank user by the input name and inform him/her about the reservation made
true
bbfe9028d9103975989501c48bd698a6ed4c2c56
doba23/Python_academy_Engeto
/6_lesson/32.py
451
4.15625
4
start = int (input ('START:')) stop = int(input ('STOP:')) divisor = int (input ('DIVISOR:')) # start = 3 # stop = 9 # divisor = 3 numbers = [] if not divisor: print('Cannot divide by zero') else: for i in range (start, stop+1): # print (i) if not i % divisor: numbers.append(i) else: continue print ('Numbers in range(',start,',',stop, ') divisible by', divisor, ':') print (numbers)
false
be50cdeba5749c0590c446f0477c131ae1c197b6
raghumina/Intermediate_level_python
/OOPs_1.py
1,368
4.25
4
# Classes and Objects in python # Object Oriented Programming is a way of computer programming # using the idea of “objects” to represents data and methods. # A class is a collection of objects or you can say it is a blueprint of objects defining # the common attributes and behavior. # Now the question arises, how do you do that? # Now lets create a class ''' class student : def func(self): print("hello") obj = student() print(obj.func()) ''' # In easy words class is a template # Objects are the instances of the classes # OOPs follows the concepts of DRY that is do not repeat class Student(): pass tom = Student() tom.name = "Tom" tom.sec = "A" tom.standard = 6 tom.roll_no = 22 print(tom.standard) # Lets create another class # # class Employee: status = "alive" # this is like global variable for all the objects in a class pass employee1 = Employee # these are the objects employee1.name = "Sasuke" employee1.rank = "genin" employee1.kills = 100 employee1.power_level = 1000 employee1.fav_move = ["chidori", "susano", "fireball"] employee2 = Employee employee2.name = "Naruto" employee2.rank = "genin" employee2.kills = 0 employee2.power_level = 1200 employee2.fav_move = ["rasengen", "shadowclone", "rasengen"] print(employee2.status) # or we can change the agloba variable for a specific class like
true
a84151f85a5a2478c89d69b2c300e925b977ef2c
raghumina/Intermediate_level_python
/Enumurate_function.py
639
4.59375
5
# Enumurate function # - Enumerate() in Python Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. # This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method. # print(enumerate.__doc__) # to know about it # LETS START list1 = ["messi", "suarez", "mrtinez", "nwymaer"] # condition is that remove odd players "suarez " and neymar i = 1 for players in list1: if i % 2 is not 0: print(players) i += 1 # doing it by using enumurate #for index, name in enumerate(list1): # if i%2 == 0: # print(name)
true
a626b31c4514f16234eab2d3b7eefe39bc81dd1c
Deependrakumarrout/Python-project
/Python project/if else notatin in python.py
441
4.375
4
num1=int(input("Enter a number for num1:")) num2=int(input("Enter a number for num2:")) if num1 >num2: print("Num1 is greater then num2") else: print("Num2 is greater then num1") #we can write as well num1=int(input("Enter a number for num1:")) num2=int(input("Enter a number for num2:")) print("Num1 is greater then num2")if num1 >num2 else print("Num2 is greater then num1") #if should get readable always put it down
true
e927c240d7f5e5b22a84e0728d0e708aa7fc4055
dheerajkjha/PythonBasics_TAU
/venv/dictionaries.py
1,514
4.6875
5
# Initializing a dictionary # Key Value pairs stuff = {"food": 15, "energy": 100, "enemies": 3} #. get() method - returns tha value of the key passed as an argument print(stuff.get("energy")) # .items() method - returns all the key value pairs of the dictionary in order print(stuff.items()) # .keys() method - returns all the keys of the dictionary print(stuff.keys()) # .popitem() - Removes the last key-value pair from the dictionary stuff.popitem() print(stuff) # {'food': 15, 'energy': 100} # .setdefault() method - Retrieves the value for a specific key # or add a new key and default value into the dictionary print(stuff.setdefault("food")) # 15 # .setdefault() method - Also allows us to set a default value when # the key is not in the dictionary print(stuff.setdefault("friends", 1213)) # 1213 print(stuff) # {'food': 15, 'energy': 100, 'friends': 1213} # .update() method - updates the called dictionary dic_one = {"Friends": 4, "Enemeies": 10,} dic_two = {"rocks": 10, "arrows":22, "guns": 222} dic_one.update(dic_two) print(dic_one) # {'Friends': 4, 'Enemeies': 10, 'rocks': 10, 'arrows': 22, 'guns': 222} dic_one.update(dic_one) print(dic_one) # {'Friends': 4, 'Enemeies': 10, 'rocks': 10, 'arrows': 22, 'guns': 222} dic_one.update(Friends = 44, Enemeies = 123) print(dic_one) # {'Friends': 44, 'Enemeies': 123, 'rocks': 10, 'arrows': 22, 'guns': 222} dic_one.update(Bombs = 122) print(dic_one) # {'Friends': 44, 'Enemeies': 123, 'rocks': 10, 'arrows': 22, 'guns': 222, 'Bombs': 122}
true
091138592c3979c9f752ba1d5882425df1ac0822
chirayu-sanghvi/ScriptingLanguageLab
/2a.py
337
4.125
4
#write a program to read in a list of elements. #create a new list that holds all the elemetns minus the duplicates (use function) def remove_duplicates(numbers): newlist = [] for number in numbers: if number not in newlist: newlist.append(number) print(newlist); return newlist; remove_duplicates([1,2,3,4,5,5,5,6,3,2])
true
7fd1254845b176b70bdc2a73b2f4d5e14129d0e7
infinite-Joy/programming-languages
/python-projects/algo_and_ds/copy_list_with_random_pointer_leetcode138.py
1,830
4.375
4
""" https://www.careercup.com/question?id=5412018236424192 Given a linked list where apart from the next pointer, every node also has a pointer named random which can point to any other node in the linked list. Make a copy of the linked list. 1 - 2 - 3 - 4 random 1 - 3, 2 - 4 algo 1 2 3 4 | / | / | / | 1 2 3 4 change the pointers to similar to above b = a.random a.next.random = a.random.next now change the next pointers head = head.next a.next.next = a.next.next.next node = node.next time complexity: O(n) space complexity: O(1) """ # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random class Solution: def copyRandomList(self, head: 'Node') -> 'Node': # make the copy node = head while node: copynode = Node(node.val) nnode = node.next node.next = copynode copynode.next = nnode node = nnode # specify the random nodes node = head while node: random_node = node.random if random_node: node.next.random = random_node.next else: node.next.random = None node = node.next.next # rectify the next nodes to point to the actual nodes if head: head1 = head.next node = head while node: node1 = node.next nnode = node1.next if nnode: node1.next = nnode.next node = nnode else: node1.next = None node = None return head1
true
8a23601a1ccf9e4d8d42726d075ac205521bda39
infinite-Joy/programming-languages
/python-projects/2017April/dice.py
740
4.3125
4
""" Imagine you are playing a board game. You roll a 6-faced dice and move forward the same number of spaces that you rolled. If the finishing point is “n” spaces away from the starting point, please implement a program that calculates how many possible ways there are to arrive exactly at the finishing point. """ from itertools import islice, cycle from sys import argv try: range = xrange except NameError: pass def fiblike(tail): for x in tail: yield x for i in cycle(range(len(tail))): tail[i] = x = sum(tail) yield x for arg in argv[1:]: number = int(arg) fib = fiblike([1] + [2 ** i for i in range(5)]) items = list(islice(fib, number)) print(items[-1])
true
32e2ac6b7f98ad05161e3ac210f860c1e98108de
infinite-Joy/programming-languages
/python-projects/algo_and_ds/group_anagrams_using_trie_leetcode49.py
2,826
4.21875
4
""" group anagrams leet code 49 https://leetcode.com/problems/group-anagrams/ so what we can do is that, sort all the strings in the arr. and then create a trie and when building the trie we can see if they are already present in the trie if present then this is an anagram else build the trie """ from typing import List class TrieNode: def __init__(self): self.children = {} self.end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, string, groups, identifier): node = self.root match = True for ch in string: if ch in node.children: node = node.children[ch] else: match = False nnode = TrieNode() node.children[ch] = nnode node = nnode if match is True and node.end is True: # anagram found groups[string].append(identifier) if match is False: # went on some other route, new group groups[string] = [identifier] # remaining conds are somewhere in the middle node.end = True class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: if len(strs) <= 1: return [strs] strings = strs strings = ["".join(sorted(s)) for s in strings] groups = {} trie = Trie() for idx, string in enumerate(strings): if string == "": if "empty_string" not in groups: groups["empty_string"] = [] groups["empty_string"].append(idx) else: trie.insert(string, groups, idx) print(groups) return [[strs[i] for i in group] for base, group in groups.items()] # test case strs = ["eat","tea","tan","ate","nat","bat"] s = Solution() #print(s.groupAnagrams(strs)) strs = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"] s = Solution() print(s.groupAnagrams(strs)) # a simpler solution can probably be done using hashmaps # put the strings into the hashmap and just see if the they are the same from collections import defaultdict class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: if len(strs) <= 1: return [strs] strings = strs strings = ["".join(sorted(s)) for s in strings] groups = defaultdict(list) for idx, string in enumerate(strings): if string == "": groups["empty_string"].append(idx) else: groups[string].append(idx) return [[strs[i] for i in group] for base, group in groups.items()] strs = ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"] s = Solution() print(s.groupAnagrams(strs))
true
ca3bc00455a3bb4d9abaf09430e3b6cfb7b75416
infinite-Joy/programming-languages
/python-projects/algo_and_ds/canonical_path.py
1,448
4.375
4
""" Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. In a UNIX-style file system, a period refers to the current directory. Furthermore, a double period .. moves the directory up a level. Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path. time complexity: O(n) space complexity: O(n) ====================================================================== we can input a stack and if there is a new thing then we will push this into the stack and then pop out of the stack. """ def canonical_path(full_path): path = full_path.split("/") canonical_path = [] for item in path: if item: if item == ".": pass elif item == "..": if canonical_path: canonical_path.pop() else: canonical_path.append(item) canonical_path = "/".join(canonical_path) return "/" + canonical_path print(canonical_path("/home/")) print(canonical_path("/../")) print(canonical_path("/home//foo/")) print(canonical_path("/a/./b/../../c/")) print(canonical_path("/a/../../b/../c//.//")) print(canonical_path("/a//b////c/d//././/.."))
true
60aeb4a915f7ea9d5662ba1a42936f2bd9f7a27c
infinite-Joy/programming-languages
/python-projects/algo_and_ds/longest_happy_string.py
1,660
4.15625
4
""" the priority queue makes most sense in this case so i can bring in the largest element and bring in two elements. and bring in 2 elements and then we can take the second largest and take 2 for each operation we will be doing logn operations hence time complexity is O(nlgn) space complexity is O(n) ============================ """ import heapq as q def add(occ, ele, builder): if occ<=-2: builder += "{}{}".format(ele, ele) occ += 2 elif occ==-1: builder += "{}".format(ele) occ += 1 return occ, builder def longest_happy_string(abc): print(abc) i = 0 queue = [] for k, v in abc.items(): if v > 0: q.heappush(queue, (-v, i, k)) i += 1 print(queue) builder = "" while len(queue)>1: import time; time.sleep(1) print(queue, builder) #__import__('pdb').set_trace() #first time occu1, i, elem1 = q.heappop(queue) occu1, builder = add(occu1, elem1, builder) # second time occu2, j, elem2 = q.heappop(queue) occu2, builder = add(occu2, elem2, builder) if occu1 < 0: q.heappush(queue, (occu1, i, elem1)) if occu2 < 0: q.heappush(queue, (occu2, j, elem2)) if len(queue) > 0: if builder[-1] == queue[0][2] and builder[-1] != builder[-2]: builder += queue[0] elif builder[-1] != queue[0][2]: if queue[0][0] <= -2: builder = builder + queue[0][2] + queue[0][2] else: builder = builder + queue[0][2] return builder print(longest_happy_string(dict(a=1, b=1, c=7))) print("*"*20) print(longest_happy_string(dict(a = 2, b = 2, c = 1))) print("*"*20) print(longest_happy_string(dict(a = 7, b = 1, c = 0)))
true
c87088fc0a9dbdf3085753eb9ee851054d3420cd
SiriusCraft/SiriusPlanet.Alpha
/py3_leetcode_practice/RemoveNthNodeFromEndofList.py
1,652
4.25
4
""" These tips seems to be useful... TL;DR 1. 越界:容易造成内存访问错误,比如调用了NULL->next。尤其对于空链表的特殊情况。 2. 更新head的特殊处理 3. 删除节点时没有保留下一个移动位置的指针(多用于reverse linked list)。 4. 移动位置存在+-1的偏差。 5. 链表题多用指针操作。注意指针作为函数参数时是pass by value: f(ListNode *p),还是pass by reference:f(ListNode *&p) 常用技巧: 1. Dummy head:简化改变、删除头指针的处理。 2. 前后双指针:多用于链表反转。 """ # Definition for singly-linked list. from DataStructure.ListNode import ListNode from DataStructure.LinkedList import LinkedList class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if head == None: return [] count_down = n dummy = ListNode(0) dummy.next = head pointer1 = pointer2 = dummy pointer2_previous = dummy while pointer1.next: count_down -= 1 if count_down < 1: pointer2_previous = pointer2 pointer2 = pointer2.next pointer1 = pointer1.next pointer2_previous.next = pointer2.next return dummy.next if __name__ == '__main__': l = LinkedList(LinkedList(ListNode(1)).generate_test_list(1)) s = Solution() head = s.removeNthFromEnd(l.head, 1) LinkedList(head).print_list()
false
0a8ce2f13594572bdd67e593d435f7dc89149730
Jormogundr/Project-Lovelace
/Exponential growth.py
511
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 17 15:05:33 2021 @author: Nate """ # Input: Initial value , growth rate , time step , and number of iterations. # Output: The numerical solution. def exponential_growth(x0, k, dt, N): arr = [] arr.append(x0) for n in range(0, N): xn_next = arr[n] + k*arr[n]*dt arr.append(xn_next) return arr if __name__ == '__main__': x0 = 5 k = 1 dt = 0.6 N = 3 x = exponential_growth(x0, k, dt, N) print(x)
true
01699f17f9f1e9ed60dc48ebd08104fe5ae85e18
srisrinu1/Coursera
/Python files and dictionaries/week3/assignment-1.5.py
417
4.15625
4
''' Write a function, length, that takes in a list as the input. If the length of the list is greater than or equal to 5, return “Longer than 5”. If the length is less than 5, return “Less than 5”. ''' def length(num_list): if len(num_list)>=5: return("Longer than 5") return("Less than 5") if __name__=="__main__": num_list=list(map(int,input().split())) print(length(num_list))
true
80ebbf79a1bc0f5171336e6597e484e6212b5025
rexelit58/python
/1.Basics/9.String_methods.py
384
4.40625
4
course='Python for Beginners'; print(course.upper()); print(course.lower()); print(course.find('n')); print(course.find('E'));#returns -1 if character not found #searching the word print(course.find("Beginners")); #find and replace print(course.replace("Beginners","Absolute beginners")); #check character or set of characters existing print('Python' in course);#return TRUE OR FALSE
true
96de32d84da1cfd05dc3b64ecb38914d1cd16e44
rexelit58/python
/1.Basics/41.classes.py
329
4.21875
4
#we use classes to define a new type and that type can have methods in body of the class. #They can have attibutes which can be set from anywhere from the program class Point: def move(self): print("move") def draw(self): print("draw") point1=Point() point1.x=10 point1.y=20 print(point1.x) point1.draw()
true
bbccfc0f1ef8419ced33a4d06a0882d31e0aa59a
rexelit58/python
/1.Basics/27.list_methods.py
716
4.40625
4
numbers=[5,3,5,6,7] #inserting the element at end of the list numbers.append(20) print(numbers) #inserting in specific index numbers.insert(2,12) print(numbers) #removing the element numbers.remove(20) print(numbers) #removing all the elements in the list #numbers.clear() #print(numbers) #removing the last item in the list numbers.pop() print(numbers) #getting the index of the value print(numbers.index(3)) #checking the value existence print(50 in numbers) #counting the number of existense of the element print(numbers.count(5)) #sorting the list numbers.sort() print(numbers) #sorting the list in descending order numbers.reverse() print(numbers) #copying the list numbers2=numbers.copy() print(numbers2)
true
a9bca0ae458d6bbfce23c14444cfdf6f690af6a8
shrikantchine/algorithm-practice
/hashing/common_element.py
662
4.3125
4
""" Given three increasingly sorted arrays A, B, C of sizes N1, N2, and N3 respectively, you need to print all common elements in these arrays. Note: Please avoid printing the same common element more than once. """ from collections import defaultdict def common_element(A, B, C): hash_A = defaultdict(int) hash_B = defaultdict(int) result = set() for i in A: hash_A[i] = 1 for i in B: hash_B[i] = 1 for i in C: if hash_A[i] == 1 and hash_B[i] == 1: result.add(i) return result A =[1, 5, 10, 20, 40, 80] B = [6, 7, 20, 80, 100] C = [3, 4, 15, 20, 30, 70, 80, 120] print(common_element(A, B, C))
true
484f8898d28f70ef0dc4b632b240aed884dbc753
AreRex14/netprog-assignment
/assignment2.py
1,401
4.28125
4
import requests #import json print("######Welcome to foreign exchange rate, currency conversion######") print("The base rate is by default is Euro.") #Below statements only to demonstrate when to use import json, it is used only for #accessing json to present it in more readable way #you can remove the import json comment and comments below and see it in action #url = 'https://exchangeratesapi.io/api/latest' #response = requests.get(url) #data = json.dumps(json.loads(response.text), indent=4) #print(data) #Statements below will executed good without importing json amt = int(input("Enter amount: ")) while amt != 0: src = input("Source currency: ") out = input("Output currency: ") #To convert to uppercase src = src.upper() out = out.upper() def currencyExchange(): #Take base rate as parameter params = {'base' : src} url = 'https://exchangeratesapi.io/api/latest?' #This will append to the url as request parameter response = requests.get(url, params=params).json() #just need to access the field required and add the out parameter as one of the json field, out value is string so no problem result = str(response['rates'][out] * amt) print('Total money after conversion = ',out,' ',result) currencyExchange() print('Thank you for using this service. Insert 0 to exit') amt = int(input("Enter another amount: ")) print("Thank you for using the service.")
true
e19066644098eca4020e3be9498b0a50fd0ee767
AreRex14/netprog-assignment
/assignment4.py
604
4.15625
4
""" ASSIGNMENT 4 ARIF ZUHAIRI BIN MOHD BASRI 16BT02033 LECTURER: EN KHAIRIL ASHRAF BIN ELIAS A list of servers. The servers should be sorted by the domains's priorities as specified in their DNS MX records. """ # python 3 import dns.resolver def MX_lookup(host): answers = dns.resolver.query(host, 'MX') servers = [] for rdata in answers: servers.append((rdata.preference, rdata.exchange)) servers = sorted(servers, key=lambda server: server[0]) return servers if __name__ == '__main__': host = input("Enter a domain name to look up: ") mail_servers = MX_lookup(host) for s in mail_servers: print(s[1])
true
f6639ed19242b3224c05dd1c6eb757e759ee8200
AveryHuo/PeefyLeetCode
/src/Python/284.PeekingIterator.py
1,563
4.1875
4
class Iterator: def __init__(self, nums): """ Initializes an iterator object to the beginning of a list. :type nums: List[int] """ pass def hasNext(self): """ Returns true if the iteration has more elements. :rtype: bool """ pass def next(self): """ Returns the next element in the iteration. :rtype: int """ pass class PeekingIterator: def __init__(self, iterator): """ Initialize your data structure here. :type iterator: Iterator """ self.cur = 0 self.res = [] while iterator.hasNext(): self.res.append(iterator.next()) def peek(self): """ Returns the next element in the iteration without advancing the iterator. :rtype: int """ if len(self.res) == 0 or self.cur >= len(self.res): return -100000 return self.res[self.cur] def next(self): """ :rtype: int """ re = -100000 if self.cur < len(self.res): re = self.res[self.cur] self.cur += 1 return re def hasNext(self): """ :rtype: bool """ re = False if self.cur < len(self.res): re = True return re if __name__ == "__main__": nums = [1, 2, 3] iter = PeekingIterator(Iterator(nums)) while iter.hasNext(): val = iter.peek() iter.next()
true
58c5a232d944c6530932158dfcea730d4a85ed45
jamesliao2016/HCDR2018
/LT2018/top_problems/5_BST/5_1_Breadth-first Search/102. Binary Tree Level Order Traversal.py
2,552
4.21875
4
#!/usr/bin/env python2 # coding:utf-8 ''' Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] tmp = [root] while root and tmp: res.append([i.val for i in tmp]) tmp0 = [[i.left,i.right] for i in tmp] tmp = [i for j in tmp0 for i in j if i] return res if __name__ == '__main__': data_input = [1, 2, 3, 3, 4, 4, 3] def treefun(x): # print(len(x)) root = TreeNode(x[0]) front = 0 i = 0 list_node = [root] while i < len(x)-1: base_node = list_node[front] i += 1 front += 1 base_node.left = TreeNode(x[i]) list_node.append(base_node.left) i += 1 base_node.right = TreeNode(x[i]) list_node.append(base_node.right) return root x_test = treefun(data_input) y_output = Solution() print(Solution().levelOrder(x_test)) ''' Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] # 25 APR, 2019 res = [] tmp = [root] while tmp and root: res.append([i.val for i in tmp]) ir = [[i.left,i.right] for i in tmp] tmp = [leaf for i in ir for leaf in i if leaf] return res # 30 DEC res,tmp = [], [root] while root and tmp: res.append([i.val for i in tmp]) lr = [[i.left,i.right] for i in tmp] tmp = [leaf for i in lr for leaf in i if leaf] return res # 29 DEC res,tmp = [],[root] while root and tmp: res.append([i.val for i in tmp]) lr = [[i.left,i.right] for i in tmp] tmp = [leaf for lr_tmp in lr for leaf in lr_tmp if leaf] return res # 5 dec, 2018 def helper(root,res): res.append(root.val) res.append(helper(root.left,res)+helper(root.right,res)) res = [] return helper(root,res) '''
true
8fa24e636b4db82df07f8095a097c0f9feb85c01
vjudge/python-study
/training/basic-grammars/tuple.py
962
4.5625
5
# 元组 print('------ 元组 ------') tuple1 = () # 如果元组只有一个元素,那么这个元素后面要加逗号。否则将被认为是基础类型 tuple2 = (12,) tuple3 = (1, 2, 3) tuple4 = (3.14, 5.96, 1897, 2020, 'a', 3 + 4j) # 创建元组,可以没有括号,元素之间用逗号分隔开即可 tuple5 = 4, 5, 6 # 正数第2个元素 print('tuple4[1]: ', tuple4[1]) # 倒数第2个元素 print('tuple4[-2]: ', tuple4[-2]) # 列表反转 # [::-1] 生成逆向索引(负号表示逆向),步长为 1 的切片 def reverse(lst): return lst[::-1] print(reverse((1, 2, 3, 4, 5))) # 列表元组长度大小 # 由于列表是动态的,所以它需要存储指针,来指向对应的元素 # 由于列表可变,所以需要额外存储已经分配的长度大小 lst = [1, 2, 3] print('lst.sizeof: ', lst.__sizeof__()) # lst.sizeof: 104 tuple5 = (1, 2, 3) print('tuple5.sizeof: ', tuple5.__sizeof__()) # tuple5.sizeof: 48
false
93323d485aaca5dde5cb605dddf9afc27d601ca2
bd52622020/appSpaceJavier
/spare_taks_not_assigned/a3/Q1_Palindrome_checker.py
380
4.5
4
#Write a Python function that checks whether a passed string is palindrome or not. print("Welcome to palindrome checker"); string = input("Introduce your string: "); string_list = list(string) string_reverse = string_list[::-1] if "".join(string_list) == "".join(string_reverse): print("These strings are palindromes") else: print("These string are NOT palindromes")
true
4ee0e7fac5acbc1ecda0ce858776f03fbc3b60f7
bd52622020/appSpaceJavier
/Tasks/Task8_Python_WarmUp/A8_Dictionary_key_exists.py
267
4.25
4
# Write a Python script to check whether a given key already exists in a dictionary. key = 9 d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} if key in d.keys(): print("This key exists in the dictionary.") else: print("This key NOT exists in the dictionary")
true
aab9f285f0acfec25d2af4dce4a16105c0141e73
JSerwatka/Idea-Bag-2
/02_Text/text_10.py
321
4.21875
4
# In Order def check_if_sorted(string: str) -> str: words = string.split() for element in words: if element == "".join(sorted(element)): print(element + " - in order", end = " ") else: print(element + " - not in order", end = " ") check_if_sorted("biopsy billowy chef")
false
86b6cbb31cca195d607755a5720c0ab196caeeeb
janetxinli/rosalind
/subs.py
716
4.125
4
#!/usr/bin/env python3 """ Finding a motif in DNA Usage: ./subs.py [input file] """ import sys from tools import check_input def substring_location(string, sub): """Given a string and a substring, return all locations of the substring within the string as a list.""" locations = "" for i in range(len(string)-len(sub)+2): if string[i:i+len(sub)].upper() == sub.upper(): locations += str(i+1) + " " return locations.strip() def main(): """Find substrings.""" check_input(sys.argv[0]) with open(sys.argv[1]) as infile: lines = infile.readlines() print(substring_location(lines[0].strip(), lines[1].strip())) if __name__ == "__main__": main()
true
d187534718e872052ca7e8ceacb94e9e1d6d7249
boldenth/correlation
/correlation/io/conversions.py
777
4.1875
4
import math def singular(word): """ removes trailing s from a string """ if word[-1] == 's': word = word[:-1] # seconds as base unit _si_time = {"second" : 1.0, "minute" : 60.0, "hour" : 3600.0, "day" : 86400.0, "week" : 604800.0, "year" : 31622400.0, "decade" : 316224000.0, "century" : 3162240000.0, } _si_len = {"mm" : 0.001, "cm" : 0.01, "dm" : 0.1, "m" : 1.0, "km" : 1000.0, "in" : 0.0254, } def convert_si(val, from_unit, to_unit): return val * _si_time[from_unit]/_si_time[to_unit] #testing if __name__ == "__main__": print(convert_si(5, "week", "minute"))
false
6c6f0a6c6004a789e985b5877aecf6ad05ac60f2
cfcdavidchan/python_practice
/DataCamp/Regular_Expression/repetitions.py
663
4.40625
4
import re # + - Checks for one or more characters to its left. pattern = r'Co+' sequence = "Cooookie" print (re.search(pattern, sequence).group()) # * - Checks for zero or more characters to its left pattern = r'Ca*' sequence = "Ceke" print (re.search(pattern, sequence).group()) # ? - Checks for exactly zero or one character to its left pattern = r'Colou?r' sequence = "Colour" print (re.search(pattern, sequence).group()) # {x} - Repeat exactly x number of times. # {x,} - Repeat at least x times or more. # {x, y} - Repeat at least x times but no more than y times. pattern = r'\d{0,2}' sequence = '0987654321' print (re.search(pattern, sequence).group())
true
f9781941a944c6d9b6f16db3e7c74c95a599faca
hassmedia/udacity-intro-to-programming
/basic-while-loop.py
226
4.125
4
''' Basic while loop in python. ''' # while loop with counter i = 0 while i < 10: print i i = i + 1 # function for while loop until input def print_numbers(a): n = 1 while n <= a: print n n = n + 1 print_numbers(3)
true
100e9337393be4cdb6b233c15cc61ba8120f0912
hassmedia/udacity-intro-to-programming
/profanity-filter/profanity_filter.py
838
4.15625
4
import urllib ''' This is a 'profanity filter' program for checking text files for bad words. ''' # function for opening and reading a text file def read_text(): quotes = open("file_curse.txt") # change to 'file_safe.txt' for testing safe respons contents_of_file = quotes.read() # check and print 'contents_of_file' quotes.close() check_profanity(contents_of_file) # function for checking file for bad words using 'www.wdyl.com/profanity' def check_profanity(text_to_check): connection = urllib.urlopen("http://www.wdyl.com/profanity?q=" + text_to_check) output = connection.read() # print output connection.close() if "true" in output: print "Profanity Alert!" elif "false" in output: print "This document has no curse words!" else: print "Could not scan the document properly." # initialise program read_text()
true
8b71aff18807cc38cfaa02a3cfbe47713f3cf94d
chriswebb09/OneHundredProjects
/Text/count_vowels.py
376
4.15625
4
#!/usr/bin/env python* # -*- coding: UTF-8 -*- def count_vowels(string): vowels = ["a", "e", "i", "o", "u"] count = 0 for letter in string: if letter in vowels: count += 1 return count if __name__ == '__main__': user_string = raw_input("Input string to check : ") check_string = count_vowels(user_string) print(check_string)
false
29f934d2d9053824349bca6858b828c5f06e01fb
eignatyev/python-algorithms-practice
/src/strings.py
1,722
4.125
4
""" Given a string S, the task is to output a string with the first letter of every word in the string """ def get_first_letters_as_string(string): ''' Returns first letters of every word as a string with no whitespaces Constraints: input string contains words separated with single whitespaces Parameters: string (str): a string of words separated with single whitespaces Returns: (str) ''' if not isinstance(string, str): raise TypeError('"string" parameter is not of str type') return ''.join([w[0] for w in string.split()]) """ Given a string, verify if brackets in this string are properly nested and balanced """ def is_brackets_balanced(string): ''' Returns True if brackets in the string are properly nested and balanced, otherwise - False Parameters: string (str): a string with or without 3 types of brackets - {}, [], () Returns: (bool) ''' if not isinstance(string, str): raise TypeError('"string" parameter is not of str type') open_brackets = ['(', '[', '{'] close_brackets = [')', ']', '}'] open_brackets_history = [] for c in string: if c in open_brackets: open_brackets_history.append(c) elif c in close_brackets: if not open_brackets_history or any([ c == ')' and open_brackets_history[-1] != '(', c == ']' and open_brackets_history[-1] != '[', c == '}' and open_brackets_history[-1] != '{' ]): return False else: open_brackets_history.pop() return not open_brackets_history
true
eba911e19f76d9e14387ca0597b2edb127b3e160
ISagesse/python_Hangman-Game
/main.py
1,204
4.40625
4
import random import hangman_words import hangman_art #Randomly choose a word from the word_list and assign it to a variable called chosen_word. chosen_word = random.choice(hangman_words.word_list) #player lives lives = 6 #import game logo print(hangman_art.logo) #create a blank space display = [] word_length = len(chosen_word) for _ in range(word_length): display += "_" end_of_game = False while not end_of_game: guess = input("Please enter a letter: ").lower() if guess in display: print(f"You've already guessed that letter -{guess}- ") #Check if the letter the user guessed is one of the letters in the chosen_word. for position in range(word_length): letter = chosen_word[position] if letter == guess: display[position] = letter #check to see if the guessing words is match if not - 1 lives if guess not in chosen_word: print(f"wrong letter -{guess}- please try again ") lives -= 1 if lives == 0: end_of_game = True print("You lose") #Join all the elements in the list and turn it into a String. print(f''.join(display)) if "_" not in display: end_of_game = True print("You win") print(hangman_art.stages[lives])
true
56bff32df938c5d7bf77a0504da95f7020d3d8f8
HeartingU/PythonEx
/pyEx/10/generator.py
1,054
4.1875
4
""" 生成器 是自定义的迭代器 """ # 函数中包含yield,调用函数不会执行体代码,会得到一个返回值,返回值是生成器对象 def func(): print('====1====') # return yield 1 print('====2====') print('====3====') g = func() print(g) print(g is g.__iter__().__iter__()) res1 = next(g) print(res1) def func1(): print('====1====') # return yield 1 print('====2====') yield 2 print('====3====') g = func1() print(g) print(g is g.__iter__().__iter__()) # 触发函数的执行,碰到yield停下来,并将yield后的值当作本次next的结果返回 res1 = next(g) print(res1) res2 = next(g) print(res2) # 生成器一般与for连用 for i in g: print(i) # 生成器:斐波那契数列,n为数量的个数 def run(n): i, a, b = 0, 1, 1 while i < n: yield a a, b = b, a + b i += 1 my_run = run(10) print(my_run) # print(list(my_run)) for i in my_run: print(i)
false
8d097c34962f365c846ff4dea26660ef806e3fd6
HeartingU/PythonEx
/pyEx/4/if.py
1,719
4.3125
4
""" if 判断 if 条件: 代码体 else: 代码体 """ # tag = True tag = 1 == 3 if tag: print('条件满足') else: print('条件不满足') ''' 逻辑运算符: and or not and:连接左右两个条件,只有两个条件都成立的情况下会返回true or: 只要有一个条件成立则返回true not: 返回相反的条件 not的优先级是最高的,就是把紧跟其后的那个条件去反, not与其后面的条件不可分割 如果语句既有and又有or,那么先用括号把and的左右两个条件括起来然后进行运算 ''' name = 'dahai' num = 20 # and print(18 < num < 26 and name == 'dahai') print(num > 18 and 1 > 3) # or print(1 > 3 or num > 18) # not print(not 1 > 3) # if加上逻辑判断 cls = 'human' sex = 'female' age = 18 if cls == 'human' and sex == 'female' and 16 < age < 22: print('开始表白') else: print('表白失败') # 三目运算(只能对if else): 一行代码写if else a = 6 print('满足条件') if a > 5 else print('不满足条件') # elif,多分支:但凡有一个条件成立,就不会往下判断了 # if的优先级最高,其次是elif,最后是else score = 80 if score >= 90: print('优秀') elif score >= 80: print('良好') elif score >= 70: print('普通') else: print('很差') # if嵌套:外面的if和里面的if要同时满足才能执行里面的if if cls == 'human' and sex == 'female' and 16 < age < 22: print('开始表白') is_success = '我愿意' if is_success == '我愿意': print('在一起') else: print('我逗你玩呢') else: print('表白失败')
false
7cec964e3cad4660cb06b47eb4f2cd2139e59370
torrapipes/Python
/CodewarsKata/8kyu/reverseListOrder.py
741
4.40625
4
# In this kata I have to create a function that takes in a list and returns a list with the reverse order. def reverseListOrder(list): return list.reverse() if __name__ == "__main__": # test case 1 assert reverseListOrder(["tail", "body", "head"]) == ["head","body","tail"] # test case 2 assert reverseListOrder(["bot", "mid", "top"]) == ["top","mid","bot"] # Solution 2: # def reverseListOrder(list): # temp = lista[0] # lista[0] = lista[2] # lista[2] = temp # Solution 3: # def reverseListOrder(list): # return list[::-1] # Solution 4: # def reverseListOrder(list): # newList=[] # newList.append(list[2]) # newList.append(list[1]) # newList.append(list[0]) # return newList
true