blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
daf3963c8db4316e3e208fcbb8492c298dab7c06
Jackson-Sherman/Misc
/python/modules/abstract_data.py
1,683
4.15625
4
class Stack: def __init__(self): self.data = [] self.length = 0 def empty(self): """ returns a boolean. True if Stack is empty, False otherwise """ return bool(self.length == 0) def push(self, value): self.data = [value] + self.data self.length += 1 return self def pop(self): if not self.empty(): output = self.data[0] self.data = self.data[1:] self.length -= 1 return output def __str__(self): return "⦗" + str(self.data)[1:-1] + "⦘" class Queue: def __init__(self): self.data = [] self.length = 0 def empty(self): """ returns a boolean. True if Stack is empty, False otherwise """ return bool(self.length == 0) def push(self, value): self.data += [value] self.length += 1 return self def pop(self): if not self.empty(): output = self.data[0] self.data = self.data[1:] self.length -= 1 return output def __str__(self): return "⦗" + str(self.data)[1:-1] + "⦘" # It works! # if __name__ == "__main__": # print("\n"+"="*8+"\n") # x = Stack() # print(x) # print("\n"+"="*8+"\n") # print("push(5)") # x.push(5) # print(x) # print("\n"+"="*8+"\n") # print("push(3)") # x.push(3) # print(x) # print("\n"+"="*8+"\n") # print("pop()") # print(x.pop()) # print(x) # print("\n"+"="*8+"\n") # print("pop()") # print(x.pop()) # print(x) # print("\n"+"="*8+"\n")
true
84c3c3861c303c9687d8d4109218b50f250e4bc6
maro000/hacker_rank_training
/input/hacker_rank_input.py
1,318
4.125
4
s1 = input() #文字列で取得し、 print(s1) #文字列のまま出力 s1 = input().strip() #strip()で前後の空白を取り除く i1 = int(input()) #文字列で取得し、int()に入れ整数として扱う #入力:str1 str2 s = input().split() #str1 str2をsplit()で分割して取得し、sに値を入れる、split(','),split('/')はぞれぞれ,/で複数要素を分割 print(s) #出力:['str1', 'str2'] print(s[0]) #出力:str1 print(s[1]) #出力:str2 #入力:int1 int2 i = list(map(int, input().split())) #int1 int2を取得し、iに値を入れる。イテレータをlist化している。 print(i[0]) #出力:int1 print(i[1]) #出力:int2 #入力: # str1 # str2 # str3 s = [input() for i in range(3)] #繰り返し print(s) #出力['str1', 'str2', 'str3'] #入力: # N # str1 # str2 # str3 # . # . # . # strN N = int(input()) #1行目のNを取得する s = [input() for i in range(N)] #N回input()を繰り返す print(s) #出力:['str1', 'str2', 'str3', 'strN'] N, M = map(int, input().split()) P = [input().split() for i in range(M)] print(type(P), P) # <class 'list'> [['1', '32'], ['2', '63'], ['1', '12']] N, M = map(int,input().split()) P = [list(map(int,input().split())) for i in range(M)] print(type(P), P) #<class 'list'> [[1, 32], [2, 63], [1, 12]]
false
ec252bc51236ba28c5b682f9b16dbe6442d2878e
bangalorebyte-DS-PT-FEB/OOPS-and-FP-exercies
/user_db.py
1,751
4.125
4
""" Create a user database (login, password, and last login timestamp) class (see problems 7-5 and 9-12) that manages a system requiring users to log in before access to resources is allowed. This database class manages its users, loading any previously saved user information on instantiation and providing accessor functions to add or update database information. If updated, the database will save the new information to disk as part of its deallocation (see __del__()).""" #data to be store # - username # - password # - last_login import time import sys db = {} class User_db: def __init__(self,username,password,last_login): self.username = username self.password = password self.last_login = last_login def show_user_credential(self): print("Username:",self.username) print("password:",self.password) print("login time:",self.last_login) def new_user(self): username = input("Hi,please enter your desired username: ") while True: if (username) in db: prompt = 'name taken, try another: ' continue else: break password = input('password: ') db[username] = password def old_user(self): username = input('username: ') password = input('password: ') passwd = db.get(username) if passwd == password: print ('welcome back', username) else: print ('login incorrect') def show_menu(self): prompt = input('(N)ew User Login\n(E)xisting User Login\n(Q)uit\nEnter choice: ') if prompt == 'n' : User_db.new_user(self) if prompt == 'e': User_db.old_user(self) if prompt == 'q': sys.exit() uday = User_db("Uday","password",time.time()) uday.show_menu() print(db) """if __name__ == '__main__': uday = User_db("Uday","gurinder",time.time()) uday.show_menu() print(db)"""
true
f21519165f7d7e8a8152e1358cf516398b57c208
raul-gomes/curso_python
/len_abs_sum_round_zip.py
1,179
4.15625
4
""" len() e sum() - LEN serve para mostrar o taminho de um iteravel e SUM serve para somar os iteraveis """ print('----- SUM -----') print(sum([1, 2, 3, 4, 5], 56)) """ abs() - Retorna um valor absoluto de um numero inteiro ou real. """ print('\n\n----- ABS() -----') print(abs(-5)) print(abs(5)) print(abs(3.47)) print(abs(-3.47)) """ round() - retorna um valor arredondado """ print('\n\n----- ROUND() -----') print(round(10.2)) print(round(10.5)) print(round(10.6)) print(round(1.2121212121, 2)) print(round(1.2199999, 2)) """ zip() - cria um iteravel (zip object) que agrega elemento de cada um dos iteraveis passados com entradas em pares """ print('\n\n----- ZIP() -----') lista1 = [1, 2, 3] lista2 = [4, 5, 6, 7, 8] zip1 = zip(lista1, lista2) print(type(zip1)) print(list(zip1)) zip1 = zip(lista1, reversed(lista2)) print(dict(zip1)) zip1 = zip(lista2, reversed(lista1)) print(dict(zip1)) lista3 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] print(list(zip(*lista3))) prova1 = [80, 91, 78] prova2 = [98, 89, 53] alunos = ['Maria', 'Pedro', 'Carla'] final = {dado[0]: max(dado[1], dado[2]) for dado in zip(alunos, prova1, prova2)} print(final)
false
fcc74c97b0925ede8423c29db6307e2faf60f2d2
aakash-26/array-operations
/max min element.py
393
4.25
4
""" Find the maximum and minimum element in an array (without sorting) """ print("\n ---------- Find the maximum and minimum element in an array (without sorting) ---------") a = [1,32,6,4,78,9,21,5] mn = a[0] mx = a[0] for i in a: if i > mx: mx = i elif i < mn: mn = i else: pass print("\n minimum element : ", mn) print("\n maximum element : ", mx)
false
eaa877d29b5b69838d5b5e1b69d912c48ef95dca
Amo10/Computer-Science-2014-2015
/Pico CTF/Pico CTF 2014/python_alg/power.py
555
4.53125
5
# power.py - demonstrates raising numbers to integer powers # by successive squaring. def power(x, y): """"Takes a real number x and an integer y and returns x^y.""" z = 1 while y != 0: if y % 2 == 0: x *= x y //= 2 else: z *= x y -= 1 return z # main print(" *** exponentiation by successive squaring ***") print("This program will raise x to the power of y\n(as long as y is a whole number!)") a = float(input("x: ")) b = int(input("y: ")) print("Result: ", power(a, b))
true
af6ba4780fc810015593acf9259df7707b7cd190
Amo10/Computer-Science-2014-2015
/Pico CTF/Pico CTF 2014/python_alg/min_max.py
506
4.34375
4
# min_max.py # Demonstrates algorithms for minimum and maximum. def my_min(x, y): """"Takes two numbers and returns the smallest.""" return (x + y - abs(x - y)) / 2 def my_max(x, y): """Takes two numbers and returns the largest.""" return (x + y + abs(x - y)) / 2 # main if __name__ == "__main__": print("*** Minimum and Maximum ***") a = float(input("a: ")) b = float(input("b: ")) print("Maximum of a & b: ", my_max(a, b)) print("Minimum of a & b: ", my_min(a, b))
true
10b1dedf3a9ad1048eb0a37039cacc26cf5effc0
xiam220/UdemyCourses
/Python/StringIndexing.py
1,420
4.125
4
numbers = '01234567' print(numbers[0]) #return 0th index #Output: 0 #numbers[0:i] #return 0th to ith index (not including ith position) print(numbers[0:2]) #Output: 01 #numbers[start:stop:stepover] #return elements from start to stop, stepping over ever stepover print(numbers[0:8:2]) #return elements from 0 to 8, stepping over every 2nd #Output: 0246 print(numbers[1:]) #start at 1 and print all the way to the end #Output: 1234567 print(numbers[:5]) #start at 0 and stops at 5 #Output: 01234 print(numbers[::1]) #start at 0, stop at 8, step over by 1 #Output: 01234567 print(numbers[-1]) #start at the end #Output: 7 print(numbers[-2]) #Output: 6 print(numbers[::-1]) #Output: 76543210 """ String are immutable, meaning they cannot be changed For example, numbers = '01234567' You can modify the variable type: numbers = 100 print(numbers) #Output: 100 However, you can't change the String itself: numbers[0] = '8' print(numbers) #Output: Traceback (most recent call last): ... > The only way to modify the String is to change the variable completely: numbers = '81234567' print(numbers[0]) #Output: 8 """
true
dd83894b3f2df69a1e22d7634a2bafc9666c4fbc
johnsonice/Python
/1_PythonBootcamp/4_objects.py
2,106
4.46875
4
################################### #####Object orientate Programming # ################################### ################### # create an object ################### class Circle(object): #class Object Attribute pi = 3.14 #object properties def __init__(self,radius=1): #set the default to be 1 self.radius = radius self.perimeter = self.get_perimeter() print 'New circle created' #methods def area(self): return self.radius**2 * Circle.pi #pi is a class object att def set_radius(self, new_radius): """ set radius to new value """ self.radius= new_radius self.perimeter = self.get_perimeter() #when radius changes, perimeter changes as well def get_radius(self): return self.radius def get_perimeter(self): return 2*Circle.pi*self.radius # now call properties c = Circle(radius=100) c.area() #call area method c.set_radius(20) #change the radius c.get_radius() c.perimeter ############ ##inherient ############ class Animal(object): def __init__(self): print "New Animal created" def whoAmI(self): print "I am an animal" def eat(self): print "Eating" class Dog(Animal): def __init__(self): Animal.__init__(self) print "Dog created" def whoAmI(self): print 'Dog' def bark(self): print "woof!" d=Dog() d.whoAmI() #base class method get overwriten d.eat() #can call inherient method ############ ##special class ############ class Book(object): def __init__(self,title,author,pages): print "A book has been created!" self.title = title self.author = author self.pages = pages def __str__(self): return "Title: %s, Author: %s, pages %s" %(self.title,self.author,self.pages) def __len__(self): return self.pages def __del__(self): print "A book is gone!" b=Book('Python','Jose',100) print b #it will print content in __str__ print len(b) #return length of the pages del b #will print book is gone
true
08fac3801d0771655921cd9548b84e58f8a1a54b
flowpig/daily_demos
/leetcode/q4.py
1,293
4.125
4
""" There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 """ class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ m = len(nums1) n = len(nums2) temp = [] i = 0 j = 0 while i < m and j <n: if nums1[i] <= nums2[j]: temp.append(nums1[i]) i += 1 else: temp.append(nums2[j]) j += 1 if i < m: temp.extend(nums1[i:]) if j < n: temp.extend(nums2[j:]) print(temp) r = int((m + n - 1) / 2) if (m + n) % 2 == 0: return (temp[r] + temp[r+1])/2 return temp[r] if __name__ == '__main__': nums1 = [1, 3] nums2 = [2, 4] obj = Solution() print(obj.findMedianSortedArrays(nums1, nums2))
true
5c2a242bed0aa9b94b1e6bb9990c800b28176518
Caylin911/caylinpackage
/mypackage/sorting.py
1,242
4.3125
4
def bubble_sort(items): '''Return array of items, sorted in ascending order''' length = len(items) - 1 for i in range(length): for j in range(length - i): if items[j] > items[j + 1]: items[j], items[j + 1] = items[j + 1], items[j] return items def merge_sort(items): '''Return array of items, sorted in ascending order''' my_list = [] if len(items) < 2: return items middle = int(len(items)/2) r = merge_sort(items[:middle]) l = merge_sort(items[middle:]) while (len(l)>0) and (len(r)>0): if l[0] > r[0]: my_list.append(r[0]) r.pop(0) else: my_list.append(l[0]) l.pop(0) return my_list+l+r def quick_sort(items): '''Return array of items, sorted in ascending order''' i = 0 if len(items) > 1: begin = items[0] for j in range(len(items)-1): if items[j+1] < begin: items[j+1],items[i+1] = items[i+1], items[j+1] i += 1 items[0],items[i] = items[i],items[0] l = quick_sort(items[:i]) r = quick_sort(items[i+1:]) l.append(items[i]) return l + r else: return items
true
cf239f024031add73ccbd5a9aae076350c5f711e
rishi301296/projects
/Time.py
743
4.21875
4
#Time class is for making objects of time class Time: def __init__(self, hh, mm, ss): #time constructor to initialize hour, minute, seconds self.hh=hh self.mm=mm self.ss=ss def get_hour(self): #return hour return self.hh def get_minute(self): #return minute return self.mm def get_second(self): #return seconds return self.ss def show_time(self): #to show time return [self.hh, self.mm, self.ss] @classmethod def from_string(cls, t): #static method to initialize a time object from a space separated string t=map(int, t.split(':')) return cls(t[0],t[1],t[2])
true
439e00141e654c36e6f90057d24711b5c03534fe
BrunoASNascimento/others_py
/FormaVazia.py
326
4.125
4
coluna = int(input("digite a largura: ")) linha = int(input("digite a altura: ")) x = coluna y = linha while (linha > 0): while (coluna > 0): if(linha == 1 or coluna == 1 or linha == y or coluna == x): print ("#", end = "") else: print (" ", end = "") coluna = coluna - 1 linha = linha - 1 print () coluna = x
false
2230fe5f7d8eba6ce2350cf4f2556ac837ca9052
MohamedGamalElSherbiny/Algorithms_Workshop
/Search Algorithms.py
2,030
4.40625
4
# Binary Search Algorithm: def binary_search(array, target_value): """ Finds the index of an item in an array using binary search algorithm Parameters: ---------- array : list List of elements target_value: object The item to search for in the array Returns: -------- If found: String containing the number of iterations. String containing the index of the element. Else: String """ minimum = 0 maximum = len(array) - 1 guess_total = 0 while maximum >= minimum: guess = (maximum + minimum) // 2 guess_total += 1 if array[guess] == target_value: print("Number of guesses is {}".format(guess_total)) return "Item {} is in the list, at index: {}.".format(target_value, guess) elif array[guess] < target_value: minimum = guess + 1 else: maximum = guess - 1 return "Item {} is not in the list.".format(target_value) # Linear Search Algorithm: def linear_search(array, target_value): """ Finds the index of an item in an array using linear search algorithm Parameters: ---------- array : list List of elements target_value: object The item to search for in the array Returns: -------- If found: String containing the number of iterations. String containing the index of the element. Else: String """ guess_total = 0 for i in range(len(array)): guess_total += 1 if array[i] == target_value: print("Number of guesses is {}".format(guess_total)) return "Item {} is in the list, at index: {}.".format(target_value, i) return "Item {} is not in the list.".format(target_value) lst = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] print(binary_search(lst, 73)) print(linear_search(lst, 73))
true
be3ff7e4f324d5cb3528944647956b76bceb9556
Phantom586/My_Codes
/Coding/Competitive_Coding/CodeForces/0 - 1300/Team.py
1,902
4.21875
4
# One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. # Participants are usually offered several problems during programming contests. Long before the start the friends # decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends # won't write the problem's solution. # This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. # Help the friends find the number of problems for which they will write a solution. # Input # The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines # contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is # sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the # third number shows Tonya's view. The numbers on the lines are separated by spaces. # Output # Print a single integer — the number of problems the friends will implement on the contest. # Examples # input # 3 # 1 1 0 # 1 1 1 # 1 0 0 # output # 2 # input # 2 # 1 0 0 # 0 1 1 # output # 1 # Note # In the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know # how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure # about the solution for the third problem, but that isn't enough, so the friends won't take it. # In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the # solution. n = int(input()) sol = 0 for _ in range(n): thought = list(map(int, input().split())) if thought.count(1) >= 2: sol += 1 print(sol)
true
92dab6ef42c95da9fc755a6a675d382e5a1829fd
Phantom586/My_Codes
/Coding/Competitive_Coding/CodeWars/CamelCaseMethod.py
611
4.125
4
# Write simple .camelCase method (camel_case function in PHP, CamelCase in C# or camelCase in Java) for strings. # All words must have their first letter capitalized without spaces. # For instance: # camelcase("hello case") => HelloCase # camelcase("camel case word") => CamelCaseWord # def camel_case(string): # str = '' # for i in string.split(): # a = list(i) # a[0] = a[0].upper() # str += ''.join(a) # print(str) # Improved Solution def camel_case(string): print(string.title().replace(" ", "")) camel_case("camel case method") camel_case(" camel case word")
true
21695b6750c74065b3ecd5901ecdd58d74daf809
Phantom586/My_Codes
/Coding/Python_Prgs/TextWrap.py
563
4.375
4
# importing the Textwrap Library. import textwrap def wrap(string, max_width): # Using the wrap method to obtain a list of characters of a specific length. str = textwrap.wrap(string, max_width) # Printing the elements of the list. for i in str: print(i) return '' if __name__ == '__main__': # Using Unpacking to Input a String and a Width. string, max_width = input(), int(input()) # Calling the wrap function and retrieving the return value in the result variable. result = wrap(string, max_width) print(result)
true
58ef0ee0984797a6a4f891f4c5e17eaa0a50cc93
michaelfederic/repo
/Guess_game_05_26.py
1,227
4.125
4
import random comp = random.randint(1,1001) count = 10 def compute(guess,comp): if guess == comp: print("Correct") else: a = abs(guess - comp) #print("You are",a,"off from my number!") if a > 2 and a <=5: print("hot hot, you're burning") if a > 5 and a <=10: print("hot hot") if a > 10 and a <=50: print("hotter") if a > 50 and a <=100: print("cold") if a > 100: print("way off buddy!") print("Welcome! This is my Guessing Game!\nYou get 10 chances to guess my number between 1,1000!\nI'll give you a few hints!\nGuess my number: ") while True: count-=1 try: guess = int(input("> ")) except: print("Enter numbers only!") break if guess == comp: print("Correct",comp,"was my number!") break print("You have",count,"guesses left!") if count ==0 and guess != comp: print("Sorry you ran out of guesses!") print("My number was",comp) break if guess > comp: print("Guess lower!") compute(guess,comp) if guess < comp: compute(guess,comp) print("Guess higher!")
true
976066571eedb7e888d47c5934a0f3dafd3c1baa
micromass/Noah
/Nicolas LA/linearcombination.py
590
4.15625
4
#This program verifies whether one vector in R^3 is a linear combination of combination of two other vectors def is_linear_combination(v1, v2, v3): try: scalar_3 = (v1[1]*v2[0] - v2[1]*v1[0])/(v3[1]*v2[0]-v3[0]*v2[1]) scalar_2 =(v1[0]/v2[0]) - (v3[0]/v2[0])*scalar_3 print(f"The first vector is a combination of the other two and the scalars are {scalar_2} {scalar_3}") except ZeroDivisionError: print("The first vector is not a combination of the other two") v1 = [-2 , 0 , 3] v2 = [1 , 3 , 0] v3 = [2 , 4 , -1] is_linear_combination(v1,v2,v3)
true
e9ab9ba51f1da17a7dff4e59e00239336d511001
L0uisJ0shua/CS443-Software-Security-Tools
/flip.py
594
4.15625
4
#!/usr/bin/python3 # Credits to @benjaminwongweien (https://github.com/benjaminwongweien) ### Use this to flip your memory address. Used to quickly flip memory adddresses that we want to write into during debugging ### Very useful for Little Endian Systems def flip(arg): if arg[:2] != "0x": return False arg = arg[2:] while len(arg) < 8: arg = "0" + arg return "".join([r"\x"+arg[x:x+2] for x in range(0,len(arg),2)][::-1]) def main(*args): for x in args: print(flip(x)) if __name__ == "__main__": import sys main(*sys.argv[1:])
true
349ec537d6bf7843fb77b3652edb304c51250430
elmira3857/python-1
/test2.py
997
4.25
4
""" var='spem' if var=='spam': print('spam') var2='girl' if var2=='girl': print("Girl") elif var=='boy': print("Boy") else: print("hello") #------------------------ numbers=range(0,10) for number in numbers: if number<3: print(number) else: break else: print("Loop exited normally") #------------------------- number=5 while number>0: print(number) number-= #------------------------- shopinglist=['eggs','ham','bacon'] try: print(shopinglist[3]) except IndexError as e: print('Exception:' + str(e) + 'has occured') else: print('no Exceptions occured') finally: print('I will always execute no matter what') #---------------------------------- """ shopinglist=['eggs','ham','bacon'] try: print(shopinglist[2]) except IndexError as e: print('Exception:' + str(e) + 'has occured') else: print('no Exceptions occured') finally: print('I will always execute no matter what')
true
b8ee1f7b91d83d2211116bcd0482bb18b9affa83
CharlieWeld/OOP
/Lab 1/perimeter.py
359
4.28125
4
#This program gets the length and width of a rectangle and #calculates the area and the perimeter length = int(input("Enter the lenght of the rectangle: ")) width = int(input("Enter the width of the rectangle: ")) area = length * width perimeter = 2*length + 2*width print("The area of the rectangle is", area, "and the perimeter is", perimeter)
true
19bd3d4accb115f97457b942a34da5ec37983874
CharlieWeld/OOP
/Lab 1/bookstore.py
552
4.125
4
#bookstore.py #calculate the wholesale price of books #get the cover price from the user cover_price = float(input("Enter cover price of book: ")) discount = int(input("Enter the percentage discount on books: ")) #divide the discount by 100 to get it in decimal form discount /= 100 number_books = int(input("Enter the number of books: ")) shipping_cost = 3 + (0.75 * (number_books-1)) wholesale_cost = number_books*(cover_price*(1-discount)) + shipping_cost print("The wholesale cost of the books are", "%.2f" % wholesale_cost)
true
80e1c7de78b26673e21701c60449dff073b66412
Safalta111/myproject1
/list.py
1,357
4.1875
4
#List(ordered,mutable,duplicate member is allowed,[]) #create a list # list1 = [1, 2, 3, 4] # list2 = ["one", "two", "three", "four"] # print("list1:", list1) # print("list2:", list2) # """ # dynamic creation of list # """ # list=eval(input("enter the list")) # print(list) #with list finction # s="safalta" # l=list(s) # print(l) # #or # s=list(range(2,10,2)) # print(s) #split function in list a="hi please come to my room" s=a.split() print(s) # #Add element in list # list1.append(10) # print("Value after append into list:", list1) # '''add value using index (index,value)''' # list1.insert(0, 12) # print("Value after insert into list", list1) # list1.extend(list2) # print("new value after extend", list1) # # #Find length of list # print("length of list1", len(list1)) # print("length of list1", len(list2)) # ''' find index using value ''' # a = list1.index("one") # print("Index of num:", a) # print("Value for index[-1]:",list1[-1]) # # #Remove value from list # list3 = [20, 23, 25, 28, 29, 56, 67] # print("list value:", list3) # list3.remove(25) #removes the first matching value, not a specific index # print("list",list3) # del list3[2] #removes the item at a specific index # print("list:", list3) # list3.clear() # print("list:", list3) # # power= [] # list = [5,10,15,20] # for i in list: # power.append(i**2) # print(power) #
true
661410d814f4db8370113553fa1ca7095fab60c3
riddhisharma2000/RTU-DigitalLibrary
/Python_Programs/Catalan_number.py
571
4.15625
4
# CATALAN NUMBER: #Question link : # https://www.geeksforgeeks.org/program-nth-catalan-number/ # This is the code to find nth catalan number in the most efficient way using Dynamic Programming def catalan_number(n): dp = [0 for i in range(n+1)] # SInce 0th and 1st catalan number are 1. dp[0],dp[1] = 1,1 # To find ith catalan number for i in range(2,len(dp)): cur = 0 for j in range(0,i): cur += dp[j]*dp[i-j-1] dp[i] = cur return dp[-1] print(catalan_number(5)) # This code is contributed by Kauhalendra Pandey
false
6dd7ea26a6cf21f3b8505e50fd9e604220741f49
alltimeJoe216/cs-module-project-algorithms
/sliding_window_max/sliding_window_max.py
902
4.25
4
''' Input: a List of integers as well as an integer `k` representing the size of the sliding window Returns: a List of integers ''' def sliding_window_max(nums, k): # setup result array #set up pointers for beginning and end fo nums #move pointers until end is at end of nums #loop through values in window finding larget #add max to result #incremnt start and end result = [] start = 0 end = k while end <= len(nums): max_num = nums[start] for i in range(start + 1, end): if nums[i] > max_num: max_num = nums[i] result.append(max_num) start += 1 end += 1 return result if __name__ == '__main__': # Use the main function here to test out your implementation arr = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
true
ae1ef5170aefea95006dd2b8aacb4b4727a69ced
ven0mrb/cti110
/P3T1_AreasOfRectangles_RobertBush.py
806
4.21875
4
# A brief description of the project # 1-28-2019 # CTI-110 P3T1 - Areas of Rectangles # Robert Bush # # Input the length and width of rectangle 1. # Input the length and wwidth of rectangle 2. # Calculate the area of rectangle 1. # Calculate the area of rectangle 2. # l= length w= width # # Rectangle 1 l1 = int(input('Enter the length of rectangle 1:')) w1 = int(input('Enter the width of rectangle 1:')) # Rectangle 2 l2 = int(input('Enter the length of rectangle 2:')) w2 = int(input('Enter the width of rectangle 2:')) # Calculate area * rectangle (a= area) a1 = l1 * w1 a2 = l2 * w2 # Determine which has the greater area. if a1 > a2: print('Rectangle 1 has the greater area.') elif a2 > a1: print('Rectangle 2 has the greater area.') else: print('Both have the same area.')
true
7f06640506a445122208b609188579d6d8a8b391
mshamanth23/pythonpractice
/set4.py
237
4.1875
4
#Python Program that Displays, which Letters are Present in Both the Strings s1=set(input("Enter first string:")) s2=set(input("Enter second string:")) a=s1.intersection(s2) print("The common letters are:") for i in a: print(i)
true
6eddffb6de7169baafb453bd48c770cfad68c71e
papahippo/oddments
/to_and_fro.py
2,962
4.125
4
#/usr/bin/python # -*- coding: utf-8 -*- """ Created on Mon Sep 28 17:59:40 2015 in answer to the question on Linked-in: LIST REORDER HI GUYES I AM A VERY BRGINNER IN PYTHON AND I HAVE A SMALL QUESTION : IF I HAVE A LIST OF STRINGS AND I WANT TO REARRANGE IT BY TAKING THE VERY Ist ELEMENT THEN THE VERY LAST ONE , THEN THE SECOND FROM THE BEGINNING AND THE SECOND FROM THE END AND SO ON .. WOULD YOU PLEASE GUIDE ME THANKS @author: Larry Myerscough (aka papahippo) """ def to_and_fro(ss): """ 'sort' a sequence (e.g. a list) of strings by taking 1st, then last, then 2nd, then last-but-one and so on. """ # The following statement is arguably unnecessary but has two advantages: # 1. It ensures that the function still works if e.g. a tuple is passed # rather than a list; we need to be able to 'pop' elements. # 2. It avoids destroying the caller's list. The caller could work around # such a 'feature' but it would nonetheless be bad style in my book. # ss = list(ss) ss_new = [] # start our answer as an empty list while ss: # i.e. until there's no more left to take ss_new.append(ss.pop(0)) # take one from start: if ss: # at least one left so now take one from end: ss_new.append(ss.pop()) # or more explicit but equivalent: ss_new.append(ss.pop(-1)) return ss_new # Above this line is the actual function. # -------------------------------------------------------------- # Below this line is all test code. if __name__ == '__main__': # I want to test with an empty list and with non-empty lists with odd and # even lengths in order to believe 'to_and_fro' really works ok: # for list_size, reason in ((0, 'empty'), (4, 'even-sized'), (7, 'odd-sized')): # I also want to test my claim that 'to_and_fro' works equally well for # lists and tuples. # for use_tuple in (False, True): # construct strings with easily recognizable order: # sequence_type_name = ('list', 'tuple')[use_tuple] orig_seq = [" case '%s' using %s - string #%d" %(reason, sequence_type_name, i+1) for i in xrange(list_size)] # if one didn't need the original strings anymore, onecould assign # e.g seq = to_and_fro(seq); but we want to test that it is # possible to leave the original sequence unscathed. # if use_tuple: orig_seq = tuple(orig_seq) sorted_seq = to_and_fro(orig_seq) print ("\n\ncase %s (using %ss of strings)" % (reason, sequence_type_name)) for (which, when) in ((orig_seq, "original"), (sorted_seq, "to_and_fro sorted")): print ("\n %s" % when) print ("\n".join(which))
true
b1a22b3c9a143dee79c972b6e1d50a030d13192e
CarolinaGonzalezS/Semana6
/prueba1.py
227
4.1875
4
# PROGRAMA INGRESOS DE NUMERo def ingresoNumeros(): num =1 cont=0 resp =0 while num>0: num=int(input("Ingrese un numero: ")) resp= resp + num cont=cont+1 print("El promedio es: " + str(resp/cont)) ingresoNumeros()
false
cdd0cb64ab4b78d6035147aa31c1c032865ae1de
alpharol/algorithm_python3
/leetcode/0201-0300/0232.用栈实现队列.py
1,809
4.28125
4
#https://leetcode-cn.com/problems/implement-queue-using-stacks/ """ 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。 示例: MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false 说明: 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。 """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.a = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self.a.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ b = self.a[0] self.a.pop(0) return b def peek(self) -> int: """ Get the front element. """ return self.a[0] def empty(self) -> bool: """ Returns whether the queue is empty. """ if len(self.a) == 0: return True else: return False if __name__ == "__main__": queue = MyQueue() queue.push(1) queue.push(2) print(queue.peek()) print(queue.pop()) print(queue.empty())
false
8ce03176b64801a8a5e82b7e3e1a1556546fc5c6
dnewbie25/App-Academy-Python-Version
/Intro to programming with Python/Arrays.py
1,479
4.15625
4
# Called Lists names = ['John', 'Maria', 'Sarah', 'David', 'Leonard', 'Stephen'] print(names[0]) print(names[:3]) # [0, 3) print(names[2:]) # from index 2, Srah, to the end print(names[2:6]) # [2, 6), that's why it works, inclusive-exclusive print(names[2:6]) #Sarah, David, it is inclusive-exclusive [2, 4) print(names[1:-2]) # ['Maria', 'Sarah', 'David'] print(names[:]) #prints all # Some list methods numbers = [1,2,3,4,5,6,7,8,0,7,7] numbers.append(10) # adds at the end print(numbers) numbers.insert(3, 3.5) # adds the value 4.5 at index 3 [1,2,3,3.5,4] print(numbers.pop()) #removes and return the last element, in this case the 10 we added before print(numbers.index(5)) #return the element at index 5, in this case 5 because we added 3.5 before at idnex 3, so the rest of elements were moved to the right print(5 in numbers) #True if it finds the element print(numbers.count(7)) # the seven is repeated 3 times numbers.sort() # sorts print(numbers) numbers.reverse() #sorted backwards print(numbers) numbers2 = numbers.copy() # copy the entire list, this time it wil copy the list reversed because it was the last modification to it numbers.append(50) print(numbers) print(numbers2) # doesn't returns the 50 as the last element because the copy was made before appending 50 unique_nums = [] for item in numbers: if item not in unique_nums: unique_nums.append(item) # adds the element if it's not in unique_nums unique_nums.sort() print(unique_nums)
true
5f684fa6a5df8e1ff6ad811c665c614637540003
dnewbie25/App-Academy-Python-Version
/Dictionaries_Hash.py
756
4.65625
5
# Dictionary is the same as a Hash in Ruby customer = { 'name': 'John Smith', 'age': 30, 'is_verified': True, } print(customer['name']) customer['birthday'] = 'January 30th' print(customer) keys = customer.keys() print(keys) # dict_keys(['name', 'age', 'is_verified', 'birthday']) values = customer.values() print(values) # dict_values(['John Smith', 30, True, 'January 30th']) for key in customer: print(key) for value in customer: print(customer[value]) # or you can also use for key in customer.keys(): print(key) for value in customer.values(): print(value) # and you can use them at the sime time the same way as in Ruby for key, value in customer.items(): # remember to add items() print(f'This is the key:{key} - value:{value}')
true
a25c385fba88231b1e7e35f4917a640360d7302e
dnewbie25/App-Academy-Python-Version
/Intro to programming with Python/Loops Exercises/count_vowels.py
281
4.21875
4
def count_vowels(word): vowels = 'aeiou' count = 0 for char in word: for vowel in vowels: if char == vowel: count += 1 return count print(count_vowels("bootcamp")) # => 3 print(count_vowels("apple") ) # => 2 print(count_vowels("pizza") ) # => 2
false
4aeba8c27ee664d0589fff040b46f20bd63e1a71
estherica/wonderland
/tests/test1_defim.py
1,365
4.1875
4
import time def marketing_menu(): print("---------------------------------------------------------------------\nWelcome to the app for calculating your social media marketing budget\n---------------------------------------------------------------------") num = int(input("Please, enter your budget in dollars... ")) time.sleep(1) print("\nYour total budget is " + str(num) + "$ that is " + str(num * 3.4) + " NIS.") num1 = int(input("\nHow many days would you like your Facebook campaign to last? ")) time.sleep(1) num2 = int(input("\nHow many days would you like your Instagram campaign to last? ")) time.sleep(1) budget = (num1 * 100) + (num2 * 50) budget_nis = budget * 3.4 budget_tax = budget_nis + (budget_nis / 100 * 17) print("\nYour purchase price is " + str(budget) + "$ that is " + str(budget_nis) + " NIS.") time.sleep(1) print("Your purchase price with tax is " + str(budget_tax) + " NIS") if budget_tax > num * 3.4: time.sleep(1) print("\nThere is not enough money on your account to pay for the service. \nPlease add another " + str(budget_tax - (num * 3.4)) + " NIS.") else: time.sleep(1) print("\nSuccessful. The balance in your account is " + str((num * 3.4) - budget_tax)) time.sleep(1) print("----------------------\nThank you and goodbye!")
true
ffb9828fba7c94d5e00702418f12d1a2a8cfcd48
morjac05/Computer-Science-Foundations
/hw1.py
1,292
4.28125
4
# Name: Jacob # Evergreen Login: morjac05 # Computer Science Foundations # Programming as a Way of Life # Homework 1 # You may do your work by editing this file, or by typing code at the # command line and copying it into the appropriate part of this file when # you are done. When you are done, running this file should compute and # print the answers to all the problems. import math # makes the math.sqrt function available ### ### Problem 1 ### print "Problem 1 solution follows:" print 'x**2-5.86x+8.5408' x={((5.86 + math.sqrt((-5.86)**2-(4*8.5408)))/(2*1)), ((5.86-math.sqrt((-5.86)**2-(4*8.5408)))/(2*1))} print 'x=' print x ### ### Problem 2 ### print "Problem 2 solution follows:" import hw1_test print 'a=', hw1_test.a print 'b=', hw1_test.b print 'c=', hw1_test.c print 'd=', hw1_test.d print 'e=', hw1_test.e print 'f=', hw1_test.f ### ### Problem 3 ### print "Problem 3 solution follows:" print ((hw1_test.a and hw1_test.b) or (not hw1_test.c) and not (hw1_test.d or hw1_test.e or hw1_test.f)) ### ### Collaboration ### # I work alone. # Like Batman. # (I'm Batman.) # Proofreading credit to David Burke (burdav22) # (He's not Batman.) # He didn't actually change anything or have any comments or suggestions, # I just asked him to look at it.
true
d56631ed714bd7948eada00e289997e401eaa1ac
TheCDC/Project-Euler
/euler/solutions/euler_024.py
1,482
4.125
4
""" Project Euler Problem 24 ======================== A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from typing import List def pack(digits: List[int], radixes: List[int]) -> int: """Take a list of numerals and accompanying radixes. Returns magnitude of the number they represent.""" n = 0 for digit, radix in zip(digits, radixes): n = n * radix + digit return n def unpack(n: int, radixes: List[int]) -> List[int]: """Take a magnitude and a list of radixes. Returns the digits of the mixed-radix number.""" digits = [] for r in reversed(radixes): digits.insert(0, n % r) n = n // r return digits def nth_permutation(tokens: List, index: int, radixes: List[int]): choice_indices = unpack(index, radixes) ts = list(tokens) # copy list of tokens out = [ts.pop(i) for i in choice_indices] return out if __name__ == "__main__": # print(unpack(999999, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1])) print( *nth_permutation(list(range(10)), 999999, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]), sep="" )
true
2d4ad7a9686d8e77a5f436f314d83e0aa9818dde
soumyadipghosh432/PythonWorkspace
/2. Variables.py
2,188
4.28125
4
# print('Hello World !') # print("Quoted string") # print('double "quotes" are allowed') # print("Single 'quotes' are also allowed") # print(1 + 2) # print(4*4) ############## ESCAPE CHARACTERS ############## # splitString = "This string in broken\nhere and having a tab \there" # print(splitString) # escape1="This is required to print the \\" # print(escape1) # escape2 = """ Triple quoted strings takes escapes automatically like \ """ # print(escape2) ############# VARIABLES ############### # greeting = "Good Morning !" # name = "User" # print(greeting + name) # name = input("Enter you name : ") # print(greeting + ' ' + name) # a=12 # b=3 # print(a + b) # print(a - b) # print(a * b) # print(a / b) # print(a // b) # print(a % b) # str = 'ABCDEFGHIJK' # print(str) # print(str[0]) # print(str[2]) # print(str[-1]) # print(str[-2]) # print(str[0:5]) # print(str[:4]) # print(str[6:]) # print(str[-5:-2]) # print(str[1:7:2]) #Skip by 2 characters # str='1, 2, 3, 4, 5, 6' # print(str[0::3]) # print(str[1::3]) # # print("hello " * 5) # # str = "weekend" # print("end" in str) #substring # print("monday" in str) age = 24 print("My age is : " + str(age) + " years") print("My age is : %d years" % age) print("My age is : %d %s, %d %s" % (age, "years", 6, "months")) print("My age is : {0} years".format(age)) print("%2d is squared to %4d and cubed to %4d" % (2, 2**2, 2**3)) print("%2d is squared to %4d and cubed to %4d" % (8, 8**2, 8**3)) print("%2d is squared to %4d and cubed to %4d" % (12, 12**2, 12**3)) print("{0:2} is squared to {1:4} and cubed to {2:4}".format(2, 2**2, 2**3)) print("{0:2} is squared to {1:4} and cubed to {2:4}".format(8, 8**2, 8**3)) print("{0:2} is squared to {1:4} and cubed to {2:4}".format(12, 12**2, 12**3)) #Left Alignment print("{0:2} is squared to {1:<4} and cubed to {2:<4}".format(2, 2**2, 2**3)) print("{0:2} is squared to {1:<4} and cubed to {2:<4}".format(8, 8**2, 8**3)) print("{0:2} is squared to {1:<4} and cubed to {2:<4}".format(12, 12**2, 12**3)) print("Value of Pi is : %30f" % (22/7)) print("Value of Pi is : %30.15f" % (22/7)) print("Value of Pi is : %.15f" % (22/7)) print("Value of Pi is : {0:30.15}".format(22/7))
true
67dac8871443b0e70a60e206d0fc653765851ee7
EDEYUAN/pythonRepo
/python_test.py
1,897
4.1875
4
#!/usr/bin/env python # this is the excerise fot chapter 1 for the book core Python programming '''print '--------------this is answer for 2.2 and 2.3----------' print 2/3,2.0/3 print 'hello, this is the first time I am using python ' print 1+2*4 print '--------------this is answer for 2-4--------------' str = raw_input('Plz input a string for this test : ') print 'The string you have input is:',str str = raw_input('Plz input a num for this test : ') print 'The num you have input is:',int(str) print '--------------this is answer for 2-5--------------' i = 0 while i<=10: print i, i = i+1 print '' for item in range(11): print item, print '' print '--------------this is answer for 2-6--------------' inpNum = raw_input('Plz input a num for test case 2-6:') Num = float(inpNum) if Num < 0.0: print 'You have input a negtive num' elif Num > 0.0: print 'You have input a positive num' else: print 'You have input zero' print '--------------this is answer for 2-7--------------' inString = raw_input('Plz input a String for test case 2-7:') Len = len(inString) for i in range(Len): print inString[i] print 'Here comes the end for using for structure to ouput each char' i = 0 while i < Len: print inString[i] i = i + 1 print 'Here comes the end for using while structure to ouput each char' ''' print '--------------this is answer for 2-11--------------' operator = 0 while (operator != 1) and (operator != 2): operator = int(raw_input('Plz choose what the operation first,1 for sum;2 for average:')) if operator == 1: print 'So, you have choose to sum for the num you will input' else: if operator == 2: print 'So, you have choose to get average for the num you will input' else: print 'Invalid command !!.Plz try again !!' print 'Now,Plz input the Num'
true
08959044834c71c6a64323a794069a7250f6ac11
Maidno/Muitos_Exercicios_Python
/aula12.py
519
4.25
4
''' #Condição Simples nome = str(input('Qual é o seu nome ?')) if nome == 'Máidno' and 'maidno' or 'máidno': print('Que nome podereso vocÊ tem!') print('Tenha um bom dia, {}!'.format(nome)) ''' # Estrutura condicional composta nome = str(input('Qual é o seu nome ?')) if nome == 'Máidno': print('Que nome podereso vocÊ tem!') elif nome == 'Karin' or nome == 'Tak' or nome == 'yuk': print('Você e um bot !') else: print('Seu nome e bem normal!') print('Tenha um bom dia, {}!'.format(nome))
false
9443a92dad8a14567b6153dc01d287af076c40fd
JeffLawrence1/Python-OOP-Basics
/mathdojo.py
1,865
4.15625
4
# Assignment: MathDojo # HINT: To do this exercise, you will probably have to use 'return self'. If the method returns itself (an instance of itself), we can chain methods. # PART I # Create a Python class called MathDojo that has the methods add and subtract. Have these 2 functions take at least 1 parameter. # Then create a new instance called md. It should be able to do the following task: # md.add(2).add(2,5).subtract(3,2).result # which should perform 0+2+(2+5)-(3+2) and return 4. # PART II # Modify MathDojo to take at least one integer(s) and/or list(s) as a parameter with any number of values passed into the list. It should now be able to perform the following tasks: # md.add([1], 3,4).add([3,5,7,8], [2,4.3,1.25]).subtract(2, [2,3], [1.1,2.3]).result # should do 0+1+3+4+(3+5+7+8)+(2+4.3+1.25)-2-(2+3)-(1.1+2.3) and return its result. # PART III # Make any needed changes in MathDojo in order to support tuples of values in addition to lists and singletons. class MathDojo(object): def __init__(self): self.results = 0 def add(self, *args): for x in args: if type(x) == list or type(x) == tuple: for y in x: self.results += y else: self.results += x return self def subtract(self, *args): for x in args: if type(x) == list or type(x) == tuple: for y in x: self.results -= y else: self.results -= x return self def result(self): print self.results return self md = MathDojo() md.add(2).add(2,5).subtract(3,2).result() md.add([1], 3,4).add([3,5,7,8], [2,4.3,1.25]).subtract(2, [2,3], [1.1,2.3]).result() md.add([1], 3,4).add([3,5,7,8], (4, 4, 2, 6), [2,4.3,1.25]).subtract(2, [2,3], (6, 2, 4.2), [1.1,2.3]).result()
true
c72ef70e12c822e9d81cccd482fa2a8347cbaafc
inwk6312fall2019/dss-sandeepganti7
/dsstask2.py
1,412
4.1875
4
def stringManipulationPG(file): ''' Goes to the beginning of a Project Gutenberg book and tokenizes text into words, removing punctuation and making lowercase. Returns a list of 'word,value' pairs for each instance of a token output to the file 'output.txt.' Sorts list in preparation for reducing step ''' startBook = False totalWords = 0 fullArray = [] output = '' file = open(file) for line in file.readlines(): if line.find("*** START OF THIS PROJECT GUTENBERG EBOOK") != -1: startBook = True elif line.find("*** END OF THIS PROJECT GUTENBERG EBOOK") != -1: #reached end of ebook, so stop adding lines startBook = False elif startBook and line.find("*** START OF THIS PROJECT GUTENBERG EBOOK") == -1 and len(line) > 1: cleanedLine = line.strip() words = cleanedLine.split() modifiedWords = [] for word in words: word = word.translate(string.maketrans("",""), string.punctuation).lower() if word != "": modifiedWords = modifiedWords + [word] totalWords = totalWords + 1 fullArray = fullArray + modifiedWords for element in sorted(fullArray): output = output + element+",1\n" with open('words.txt', 'w') as f: f.write(output) return 'output.txt'
true
c62cc597b6809f801d3c7fd75e6be2da42eaeacf
inwk6312fall2019/dss-sandeepganti7
/dsstask4.py
919
4.21875
4
def checkForWords(): ''' Compares words in an input document file to a master word list, 'words.txt'. Prints words that are not present ''' file = open("book.txt") allWords = open('words.txt') dictionary = [line.rstrip('\r\n') for line in allWords] for line in file.readlines(): line = line.strip() words = line.split() for word in words: word = word[0:word.find(",")] found = False index = 0 for element in dictionary: if found: break if word == element: found = True break elif word != element and index < len(dictionary)-1: index = index + 1 else: print("The word " + word + " is not in the dictionary") break checkForWords()
true
74f4c1c3046f62ae2d62d9ca943eea14ae8de9cc
ebeilin/python-programming
/unit-1/problem3.py
449
4.21875
4
#how i did it ''' user_entry = input('Enter a word or sentence please:\n') for character in reversed(user_entry): print(character, end="") ''' #strings are immutable ''' my_string = 'This is a sentence' reversed_string = '' for i in range(len(my_string) - 1, -1, -1): reversed_string += my_string[i] print(reversed_string) ''' my_string = 'This is a sentence' for i in range(len(my_string) - 1, -1, -1): print(my_string[i], end='')
true
bc6a0a4659c4a6c221fb22b3b5eae17575a783eb
zachafranz/pythonLib
/hw1pr3.py
1,942
4.46875
4
'''Name: Zach Franz hw1pr3.py (Lab 1, part 3) ''' from math import * def convertFromSeconds(seconds): """ Returns the time in a list with Days, Hours, Minutes, Seconds given an input in seconds. """ days = 0 hours = 0 minutes = 0 day_sec = 60*60*24 # seconds in a day hour_sec = 60*60 # seconds in an hour min_sec = 60 # seconds in a minute # If seconds is greater than the amount od second in a day, calculate the number of whole days, then find the remaining seconds. Repeat for hours and minutes. if seconds >= day_sec: days = floor(seconds/day_sec) seconds = seconds - days*day_sec if seconds >= hour_sec: hours = floor(seconds/hour_sec) seconds = seconds - hours*hour_sec if seconds >= min_sec: minutes = floor(seconds/min_sec) seconds = seconds - minutes*min_sec # Create and return list. aList = [days,hours,minutes,seconds] return aList def readSeconds(seconds): """ Returns a string of hours, days, minutes, and seconds given an input in seconds (integer)""" # Get the Days, Hours, Minutes, and seconds. aList = convertFromSeconds(seconds) # If the unit is singular add singular time unit, otherwise add plural. Add commas for everything except the last unit. if aList[0] == 1: day_str = str(aList[0]) + ' day, ' else: day_str = str(aList[0]) + ' days, ' if aList[1] == 1: hour_str = str(aList[1]) + ' hour, ' else: hour_str = str(aList[1]) + ' hours, ' if aList[2] == 1: min_str = str(aList[2]) + ' minute, ' else: min_str = str(aList[2]) + ' minutes, ' if aList[3] == 1: sec_str = str(aList[3]) + ' second' else: sec_str = str(aList[3]) + ' seconds' # Return concatenated time. return day_str + hour_str + min_str + sec_str
true
dd0563ac55a7354686abbd357aeb912e7189dba0
amountcastlej/For_and_While_Loops
/loops.py
1,416
4.125
4
# For Loops #for x in range(0, 10,1 ): # print(x) #for x in range(0, 10): # print(x) #for x in range(10): # print(x) #for x in range(0, 10, 2): # print(x) #for x in range(5, 1, -3): # print(x) #my_list = ["abc", 123, "xyz"] #for i in range(0, len(my_list)): # print(i, my_list[i]) #my_dict = {"name": "Noelle", "language": "Python"} #for k in my_dict: # print(k) #my_dict = {"name": "Noelle", "language": "Python"} #for k in my_dict: # print(my_dict[k]) #Alternative way to find keys #for key in capitals.keys(): #print(key) #Alternative way to find values #for val in capitals.value(): #print(val) #To find both keys and values #for key, val in my_dict.items(): # print(key, " = ", val) #for count in range(0,5): # print("Looping - ", count) #for val in "string": # if val == "i": # break # print(val) #for val in "string": # if val == "i": # continue # print(val) # While Loops #count = 0 #while count < 5: # print("looping - ", count) # count += 1 #Syntax of While loop #while <expression>: # do something, including progress towards making the expression false, Otherwise we'll never get out of here! #y = 3 #while y > 0: # print(y) # y = y - 1 #else: # print("Final else statement") #y = 3 #while y > 0: # print(y) # y = y - 1 # if y == 0: # break #else: # print("final ese statement")
false
7b20d5b163b48291114ecc6a82fd05aa2a768a45
SYK-08/Practice-Q-s-of-Python
/prac29.py
253
4.125
4
# Python program to add two objects if both objects are an integer type. def check(obj1, obj2): if type(obj1)==int and type(obj2)==int: sum = obj1+obj2 print(sum) else: print("Nothing to do here.") check(138, 34)
true
47ea353086692d2c0e9aa13d36cad73cb6ac9800
SYK-08/Practice-Q-s-of-Python
/prac27.py
260
4.21875
4
# Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20. n1 = int(input("Enter first number:")) n2 = int(input("Enter second number:")) sum = n1+n2 if sum>=15 and sum<=20: print(20) else: print(sum)
true
ed1a6a613f2cfd441a2c0efbae68ebecb27f19b9
AngelaPSerrano/ejerciciosPython
/hoja5/H503/main.py
1,125
4.15625
4
from simulacion import Simulacion simulacion = Simulacion() def comprobarValores(valor): if valor == "O" or valor == "A" or valor == "D": return True else: return False numeroPiezas = int(input("¿Con cuantas piezas vamos a jugar? ")) while numeroPiezas >7 or numeroPiezas <3: print("Número no valido. Solo de 3 a 7.") numeroPiezas = int(input("¿Con cuantas piezas vamos a jugar? ")) simulacion.setNumeroPiezas(numeroPiezas) simulacion.vistaInicial() while simulacion.juegoFinalizado() == False: origen = (input("¿De qué torre cogemos la pieza? ¿O, A, D? ")).upper() while comprobarValores(origen) == False: print("Introduzca un valor válido") origen = input("¿De qué torre cogemos la pieza? ¿O, A, D? ").upper() destino = input("¿En qué torre la dejamos? ").upper() while comprobarValores(destino) == False: print("Introduzca un valor válido") destino = input("¿En qué torre la dejamos? ").upper() simulacion.moverPieza(origen,destino) simulacion.mostrarTorres() print("¡LO CONSEGUISTE!")
false
59501d55476afb58154f0b1d0492c0e0cc9c5d16
N-Rawat/Student-ManagementSystem
/databasebackend.py
1,258
4.375
4
import sqlite3 connection = sqlite3.connect('student.db') print("Database open") table_name = "student_table" student_id = "student_id" student_name = "student_name" student_college = "student_college" student_address = "student_address" student_phone = "student_phone" connection.execute(" CREATE TABLE IF NOT EXISTS " + table_name + " ( " + student_id + " INTEGER PRIMARY KEY AUTOINCREMENT, " + student_name + " TEXT, " + student_college + " TEXT, " + student_address + " TEXT, " + student_phone + " INTEGER);") # SQLITE QUERY: CREATE TABLE IF NOT EXISTS student_table(student_id INTEGER PRIMARY KEY AUTOINCREMENT, # student_name TEXT,student_college TEXT) print("Table created successfully") def display(): cursor = connection.execute("SELECT * FROM " + table_name + " ;") return cursor def insert(name,college,address,phone): connection.execute("INSERT INTO " + table_name + " ( " + student_name + ", " + student_college + ", " + student_address + ", " + student_phone + ") VALUES ('"+name+"','"+college+"','"+address+"',"+phone+")") connection.commit() return True
false
008579d1ccecb5c6d01218ea3b73c9d07b3159f8
markedward82/pythonbootcamp
/ex9.py
607
4.25
4
#printing, printing, printing #assigne week days string to a variable, each day is seperated by space days = "Mon Tue Wed Thu Fri Sat Sun" #assign 8 months to months variable, each month is seperated by \n months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" #display a string and call days variable print("Here are the days:", days) #display a string and call months print("Here are the months:", months) #these three quotes allow to type as much as you want with the same formatting print(""" There is something going on here. With the three double-quotes. We'll be able to type as much as we like. """)
true
ca1b8401f49ed91c6703f95cd249f6a5b30c31ae
markedward82/pythonbootcamp
/ex20.py
872
4.15625
4
#ex20 #functions and files from sys import argv #assign arguements to argv script, input_file = argv #create a function will read the file def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) current_file = open(input_file) #display a string print("First let's print the whole file:\n") #calling function print_all(current_file) #display rewind string print("now let's rewind, kind of like a tape.") rewind(current_file) #display each line string print("Let's print 3 lines.") #assign a variable to 1 current_line = 1 #calling function of print_a_line print_a_line(current_line, current_file) #increment the line to 2 current_line += 1 print_a_line(current_line, current_file) #increment the line to 3 current_line += 1 print_a_line(current_line, current_file)
true
f690a28b0df7921019fd0947f81d4c73e46e0621
MMAGANADEBIA/Programming_Courses
/Python_course/lists.py
2,238
4.34375
4
demo_list = [1, "hello", 1.34, True, [1, 2, 3]] #las listas pueden albergar cualqquier dato o tipo de dato colors = ["red", "green", "blue"] #tambien se puede usar el constructor number_list = list((1, 2, 3, 4)) # se crea una variable igual a constructor list y entre parentesis los objetos print(number_list) print(type(number_list)) r = list(range(1, 101))#rangos de donde a donde para crear determinado elemento print(r) print(type(colors)) print(dir(colors)) #dir nos permite ver los metodos del elemento print(len(colors)) #recuerda que len ve el tamaño de un objeto o en este caso lista print(colors[1]) #para buscar el indice print(colors[-2]) #para buscar indice al reves print('green' in colors) #esta funcion es para imprimir true o false si el string que meti existe in variable print('verde' in colors) print(colors) #imprime la lista colors[1] = 'yellow' #sustituye el indice 1 de la lista colors por yellow print(colors) colors.append('violet') #agrega nuevos elementos a la lista print(colors) #colors.append(('green', 'black')) #append solo agrega uno, puedo agregar mas con una tupla #print(colors) #Comentado por efectos practicos colors.extend(['blue', 'dirt']) #para agregarlos como elementos separados se usa extend y se manda una lista print(colors) colors.insert(1, 'pink') #agrega un elemento en un indice dado print(colors) colors.insert(len(colors), 'second_pink') #inserta en el indice igual al tamaño de la lista, en este caso al final print(colors) colors.pop() #elimina el ultimo elemento print(colors) colors.remove('pink') #elimina el elemento dado print(colors) #colors.clear() #limpia completamente la lista colors #comentado por efectos practicos colors.sort() #sort al igual que en javascript ordena alfabeticamente los elementos de una lista print(colors) colors.sort(reverse=True) #para ordenar de manera inversa se debe de escribir dentro de los parentesis del metodo "reverse" que es lo que se busca y =True para decirle que queremos "activarlo" print(colors) print(colors.index('red')) #.index sirve para encontrar cual es el indice del elemento dado de una lista print(colors.count('blue')) #recordar que nos ayuda a contar cuantas veces se repite un elemento en una lista
false
df1feb5a47f8bc5e7d850939536548b9a048b74b
hossain-araf/mypythonprojects
/guess.py
315
4.1875
4
operation=input("whats your favourite game football or cricket") times= int(input("how many times do you want to play")) if operation=="cricket" and times<=12: print("please play with me ") elif operation=="football" or times>=12: print("i am sorry, i cant play with you now")
true
1f792f09faea6119c12de2358a4aaee745064ab4
WillOsoc/CursoPython
/08_Tuplas.py
598
4.1875
4
#Listas inmutables tupla01=("Will",11,"03",1978,"Will") # Se puede convertir una tupla en una lista, y viceversa lista01=list(tupla01) tupla02=tuple(lista01) nombre,dia,mes,agno,nombre2=tupla01 #desempaquetado. asigna etiqueta a elementos en tupla print(tupla01[2]) print(tupla01) # Imprime toda la lista (no hace falta ":" como en la lista) print(lista01[:]) print(tupla02) print("Will" in tupla02) print(tupla02.count("Will")) print(tupla02.index(1978)) # NO válido en versiones previas print(len(tupla02)) # Cuantos elementos tiene print(len(lista01)) # Cuantos elementos tiene print(agno)
false
f9c496afdeafdbce5cee1e25174697436110d7c0
AlessioVallero/algorithms-coursera
/part1/week2/stack-with-max/stack_with_max.py
2,045
4.5
4
class StackWithMax: """ Create a stack and keep track of the max element on it. """ def __init__(self): """ Init a stack and an helper stack with max tracking """ self.__stack = [] self.__max_stack = [] def push(self, item): """ Push a new item and push the max between current max and current element :param item: The item to push """ self.__stack.append(item) if len(self.__max_stack) > 0: current_max = self.__max_stack[-1] if item > current_max: # If current item is greater than current max, it goes at the top of the stack self.__max_stack.append(item) else: # If current item is smaller than current max, we push the current max once again self.__max_stack.append(current_max) else: self.__max_stack.append(item) def pop(self): """ Pop item from top of the stack (LIFO) and max stack :return: The item on top of the stack """ self.__max_stack.pop() return self.__stack.pop() def size(self): """ Return the size of the stack. :return: Size of the stack """ return len(self.__stack) def is_empty(self): """ Check whether stack is empty. :return: True if empty, False otherwise. """ return self.size() == 0 def return_the_maximum(self): """ Return the maximum element in the stack, which is always on top of the stack :return: The maximum element in the stack """ return self.__max_stack[-1] def unit_test(): """ Test QueueWithTwoStacks """ stack = StackWithMax() stack.push(20) stack.push(10) stack.push(30) print(stack.return_the_maximum()) stack.pop() print(stack.return_the_maximum()) stack.pop() print(stack.return_the_maximum()) stack.pop() unit_test()
true
8c24667aedd376115553508d8c9aefcd724c1102
SeanHub/LearningPython
/Lists & Slicing.py
1,791
4.40625
4
one = input("Word One: ") two = input("Word Two: ") three = input("Word Three: ") four = input("Word Four: ") five = input("Word Five: ") # add strings to list newList = [one, two, three, four, five] print("Your list is: ") # cast list to string to print print(str(newList)) # print based upon index print("The third element in your list is, " + str(newList[2])) # print based upon minus index print("The second until last element in your list is, " + str(newList[-2])) # print based upon second letter of first word in list print("The second letter of the first element in the list is, " + str(newList[0][1])) # a slice to extract elements, includes both -2 and the rest of the list print("The last two elements are, " + str(newList[-2:])) # prints even elements, the two blanks = start at 0, end at end of list print("The even elements are: " + str(newList[::2])) # prints the odd elements print("The odd elements are: " + str(newList[1::2])) # prints elements backwards print("Elements backwards: " + str(newList[::-1])) # prints even elements backwards print("The even elements backwards: " + str(newList[::-2])) # prints odd elements backwards print("The odd elements backwards: " + str(newList[3::-2])) # check the list for element based on user input search = input("Search for a word inside your list: ") print(search in newList) # print number of elements in list print("The number of elements in your list: " + str(len(newList))) # edit element in list editIndex = input("Choose element to edit: ") editString = input("Choose new string: ") newList[int(editIndex) - 1] = editString print(str(newList)) # delete an element del newList[int(input("Choose element to delete: ")) - 1] print(str(newList)) input("Press Enter to quit...")
true
299c3992ec4cff71530925822f567aa46b7e3ba4
Deanwinger/python_project
/python_fundemental/214_reverse_a_stack.py
490
4.34375
4
# 程序员代码面试指南 P8 好好体会递归 # 逆序一个栈 def get_last_element(stack): res = stack.pop() if not stack: return res else: last = get_last_element(stack) stack.append(res) return last def reverse(stack): if not stack: return i = get_last_element(stack) print(i) reverse(stack) stack.append(i) return if __name__=="__main__": stack = [1,2,3,4,5] reverse(stack) print(stack)
false
093a17e722d246c50d3b4dac7f40d333d12b8099
JaMalgorzata/Bio334_2020
/examples/day1_1_example1.py
516
4.25
4
list1 = [1, 2, 3, 4, 5, 6] # initialization of a list total = 0 # initialization of total variable for i in list1: # iteration of each element of the list total += i # add the element to the total variable print("total =", total) # show the result total = sum(list1) # simple implementation print("total = %d" % total) # show in a different way total = sum(range(1, 7)) # simple implementation print("total = %d" % total) # show in a different way
true
595ed511d5a308942f53e8fb3a71ae1ffb40da26
BrianLandes/GunslingerGame
/TreeList.py
2,416
4.1875
4
# Brian Landes # a structured list used for sorting objects class TreeList(object): # takes values and pushes them into its nodes, where they're sorted def __init__(self): self.root = None pass def Put(self, value, data ): # takes a value for comparing and data for storing and returning if self.root is None: self.root = TreeNode( value, data, None ) else: self.root.Put( value, data ) def AsString(self): return self.root.AsString() def ToList(self,ascending=True): return self.root.ToList(ascending) class TreeNode(object): def __init__(self, value, data, parent): self.value = value self.data = data self.left = None self.right = None self.parent = parent def Put(self, new_value, new_data ): # compares the new value against its own value and pushes it to either # the left or the right node if new_value < self.value: if self.left is None: # either create a new node where there wasn't one self.left = TreeNode(new_value, new_data, self) else: # or continue the push downwards through the node self.left.Put( new_value, new_data ) else: # this will also catch equal-to, which is fine if self.right is None: self.right = TreeNode(new_value, new_data, self) else: self.right.Put(new_value, new_data) def AsString(self): s = '' if self.left is not None: s += self.left.AsString() s += ', ' s += self.data if self.right is not None: s += ', ' s += self.right.AsString() return s def ToList(self,ascending=True): values = [] if ascending: if self.left is not None: values = values + self.left.ToList(ascending) else: if self.right is not None: values = values + self.right.ToList(ascending) values = values + [ self.data ] if ascending: if self.right is not None: values = values + self.right.ToList(ascending) else: if self.left is not None: values = values + self.left.ToList(ascending) return values
true
d13cb9353518723a605226c5a6c5fefe55401e42
BiliBiLL/CS519
/leetcode_problems/pascaltriangle.py
616
4.125
4
""" Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ tri = [[1]] for i in range(numRows -1): temp = [x+y for x,y in zip([0]+tri[i],tri[i] + [0])] tri.append(temp) return tri if __name__ == "__main__": s = Solution() print s.generate(3) print s.generate(5) print s.generate(7)
true
7a44573ca4ac92064753ab652eb3d92484c48211
FayK12/PythonRepo
/Space_Boxing.py
879
4.21875
4
#this code asks for your weight and tells you what your weight would be on another planet weight = int(input("Please enter your current earth weight (lb only): ")) print("\nI have info for the following planets: ") print("1. Venus 2. Mars 3. Jupiter") print("4. Saturn 5. Uranus 6. Neptune") choice = int(input("\nWhich planet are you visiting? ")) if (choice == 1): pweight = weight*0.78 planet = "Venus" elif (choice == 2): pweight = weight*0.39 planet = "Mars" elif (choice == 3): pweight = weight*2.65 planet = "Jupiter" elif (choice == 4): pweight = weight*1.17 planet = "Saturn" elif (choice == 5): pweight = weight*1.05 planet = "Uranus" elif (choice == 6): pweight = weight*1.23 planet = "Neptune" print("Your weight would be",pweight,"pounds on the planet", planet)
true
ea2384fa1686ca6d155782651088a025938ebddc
hofmannicusrex/DMACC_Python_202003
/Module6/basic_function_assignment/basic_function_assignment_hofmann/basic_function_assignment_hofmann.py
995
4.125
4
""" Program: basic_function_assignment_hofmann.py Author: Nick Hofmann | nickhofmann1989@hotmail.com | nohofmann@dmacc.edu Last Modified: 6/15/2020 Program specifications: The program will demonstrate a simple method call. It will handle simple input errors using a try-catch statement as well. """ def hourly_employee_input(): user_name = input('Please enter a name: ') try: hours_worked = int(input('Enter the number of hours worked please: ')) except ValueError as err0r: print('\n\nHey jabronie, the input you entered didn\'t match the data type expected.\n') raise try: hourly_wage = float(input('What is the hourly rate of pay? ')) except ValueError as err0r: print('\n\nHey jabronie, the input you entered didn\'t match the data type expected.\n') raise print('\nEmployee Name:', user_name, '\nHours Worked:', hours_worked, '\nHourly Wage:', '{:4.2f}'.format(hourly_wage)) if __name__ == '__main__': hourly_employee_input()
true
c5b3bfeb22f6ea667fd5c7b72b57cc711ff887b6
hofmannicusrex/DMACC_Python_202003
/Module6/function_parameter_assignment/function_parameter_assignment_main/function_parameter_assignment_hofmann.py
532
4.21875
4
""" Program: function_parameter_assignment_hofmann.py Author: Nick Hofmann | nickhofmann1989@hotmail.com | nohofmann@dmacc.edu Last Modified: 6/16/2020 Program specifications: The program will demonstrate a basic function with parameters. """ def multiply_string(message, n): """ :param message: String containing my favorite class this semester. :param n: Int containing the number of times I want the message to print. :return: The string * the int. """ return print(message * n) if __name__ == '__main__': multiply_string('C++\t', 6)
true
0074f891fdece774b71f1be575dbcd679bdfa7d0
psg0796/abstract-generator
/generator.py
2,158
4.25
4
from typing import Dict from abc import ABCMeta, abstractmethod class Generator: __metaclass__ = ABCMeta @abstractmethod def generate_method(self, method_name, method_schema, indent) -> str: """ A method to generate the method template from the method schema :param method_name: Name of the method :param method_schema: schema of the method, contains params and return type :param indent: basic indentation to file while generating template :return: string format template of generated method """ @abstractmethod def generate_class(self, class_name, class_schema, indent) -> str: """ A method to generate the class template from the class schema :param class_name: Name of the class :param class_schema: Schema of the class, consists of methods which are defined :param indent: basic indentation to follow while writing the template :return: string format of the generated class """ pass @abstractmethod def get_string_val(self, type_, val) -> str: """ A method to return the string formatted value ex. if called with type_ = str and val = my_string, it returns "my_string", so that this can be written as a string in the generated template :param type_: type of the val, may be str, int, float, or any basic type :param val: value to be converted to the format :return: return string formatted value """ pass @abstractmethod def generate_enum(self, enum_name, enum_schema, indent) -> str: """ A method to generate enum classes :param enum_name: Name of the enum :param enum_schema: schema of the enum, consists of members and their types :param indent: basic indentation to follow while generating the template :return: string format of the generated enum class """ pass @abstractmethod def generate(self) -> None: """ The driver method for the generation of the template in a language :return: None """ pass
true
a4e9e529935a78964196fb3a46a9816ca259ad98
Maaitrayo/Python-Programming-Basics
/4_integers.py
723
4.40625
4
#This program is to denote some integers functions a = 10 b = 20 print("The sum of "+str(a)+" + "+str(b)+ " = "+str(a+b)) print("The difference of "+str(a)+" - "+str(b)+ " = "+str(a-b)) print("The product of "+str(a)+" * "+str(b)+ " = "+str(a*b)) print("The quotient of "+str(a)+" / "+str(b)+ " = "+str(a/b)) a = 10 b = 3 #c = pow(a,b) print("The power operator is:'**' "+str(a ** b)) print("____________________________\n") #Floats print("Float Variables: ") a = 0.1 b = 0.2 print("The sum of "+str(a)+" + "+str(b)+ " = "+str(a+b)) print("The difference of "+str(a)+" - "+str(b)+ " = "+str(a-b)) print("The product of "+str(a)+" * "+str(b)+ " = "+str(a*b)) print("The quotient of "+str(a)+" / "+str(b)+ " = "+str(a/b))
false
38b171ae22c6a5f9b6149e00e62b82222b1b5dc0
saraattia412/basic_python
/condition.py
1,439
4.1875
4
x=5 if x==5 : print(x) name='sara' age=20 if name=='sara' and age==20 : print('your name is sara , and your are also 20 years old') if name=='sara' or name=='aya' : print('your name is either sara or aya') username='sara atia' password='12345' if username=='sara atia' and password=='12345' : print('login success ,welcome sara' ) y=500 if y>600 : print('y is bigger than 600') else: print('y is smalle than 600') x=100 if x==100 : print('x=100') elif x==200 : print('x=200') else: print('x=0') x=100 if x<200 : print('value less than 200') if x==150 : print('which is 150') elif x==100 : print('which is 100') elif x==50 : print('which is 50') elif x<50 : print('value less than 50') else: print('could not find true value') print('end..') x=5 if x==5 : print('x=5') name='sara' print('welcome sara') if name=='sara' else print('who are you') #example 1 x=5 y=6 z=3 r=2 if all([x==5 , y==6 , z==3 , r==2]): print('done') elif any([x==6 , y==5 , z==2 , r==3]): print('error') #example 2 players ={'treka':1 , 'brakate':2 } if 'treka' in players : print('found') #example 3 a=1 b=2 if a==1 and b==2 : print(True) if a==0 or b==2 : print(True) if not (a==1 and b==3) : print(True) if a!=0 and b!=3 : print(True) #example 4 players ={'treka':1 , 'brakate':2 } if 'sara' not in players : print('not found')
false
0fb1320822017527cd91bc9340379b08a8393bfd
eledemy/PY110-2021
/while_2.py
1,359
4.1875
4
# •Возвести числа A в целую степень N def pow_n(a, n): result = 1 i = 0 while i != n: result *= a i += 1 print(result) if __name__ == '__main__': pow_n(2, 5) # •Является ли заданное натуральное число степенью двойки? def is_pow_n(a, n=2): is_pow = False # завели флаг, предположили ,что число не является степенью 2 while True: over = a % n if over != 0: break a = a // n if a == 1: is_pow = True break return is_pow if __name__ == '__main__': print(is_pow_n(32, n=2)) # •Ежемесячная стипендия студента составляет А грн., а расходы на проживание превышают ее и составляют B грн. в месяц. # Рост цен ежемесячно увеличивает расходы на 3%. Определить, какую нужно иметь сумму денег, чтобы прожить учебный год # (10 месяцев), используя только эти деньги и стипендию. A = 1000 B = 2000 k = 0 s = 0 s_1 = A + B + B*0.03 while k != 10: s += s_1 k += 1 print(s)
false
fbf0bc5a6e821b530caf63519865fba69ab76587
xiongfeihtp/algorithm-and-data
/tree.py
2,318
4.1875
4
# 树的存储单位为节点 class Node(object): def __init__(self,item): self.elem = item self.lchild = None self.rchild = None class Tree(object): """二叉树""" def __init__(self): # 根节点 self.root = None def add(self, item): # 广度优先的遍历,始终在左边读取,右边补充,队列 node = Node(item) queue = [] # 列表当做队列处理 queue.append(self.root) #特殊情况,将问题等效为一个基本数据结构的操作 if self.root is None: self.root = node return while queue: cur_node = queue.pop(0) #如果根节点一开始为空。 if cur_node.lchild is None: cur_node.lchild = node return else: queue.append(cur_node.lchild) if cur_node.rchild is None: cur_node.rchild=node return else: queue.append(cur_node.rchild) #树的广度遍历 def breadth_travel(self): """树的广度遍历""" queue=[self.root] if self.root==None: return while queue: cur_node=queue.pop(0) print(cur_node.elem) if cur_node.lchild is not None: queue.append(cur_node.lchild) if cur_node.lchild is not None: queue.append(cur_node.rchild) #树的深度遍历 #遍历的过程存在递归 def preorder(self, node): if node is None: return print(node.elem) self.preorder(node.lchild) self.preorder(node.rchild) def medorder(self,node): if node is None: return self.medorder(node.lchild) print(node.elem) self.medorder(node.rchild) def endorder(self,node): if node is None: return self.endorder(node.lchild) self.endorder(node.rchild) print(node.elem) if __name__=="__main__": tree=Tree() tree.add(0) tree.add(1) tree.add(2) tree.add(3) tree.add(4) tree.add(5) tree.add(6) tree.add(7) tree.add(8) tree.add(9) tree.breadth_travel() print(" ") tree.preorder(tree.root)
false
9221568b58cc35632ae3bb5e09a8504b7db92768
Viola8/Python-NLP-Libraries
/numpy18_19_20.py
738
4.15625
4
# 18 Write a NumPy program to find common values between two arrays. import numpy as np array1 = [22,33,44,55,66,77] array2 = [22,44,66,88] print(np.intersect1d(array1,array2)) # Output: [22 44 66] # 19 Write a NumPy program to get the unique elements of an array. import numpy as np array1 = [23,34,34,34,45] print(np.unique(array1)) # 20 Write a NumPy program to find the set difference of two arrays. # The set difference will return the sorted, unique values in array1 that are not in array2. import numpy as np array1 = np.array([0, 10, 20, 40, 60, 80]) array2 = [10, 30, 40, 50, 70] print("Unique values in array1 that are not in array2:") print(np.setdiff1d(array1, array2)) # Output: [0 20 60 80]
true
7d12f7fb1f1a14ddc0ac9e2f2f389307b3e7e05e
Mgallimore88/web-dev
/Python_Level_One/code_breaker.py
1,075
4.125
4
from random import randint """ guessing game - run python3 code_breaker.py in terminal then start guessing. Nonesense clues will guide you to the winning combination! """ target = [randint(0, 9) for n in range(3)] def return_target_numbers(target): numstring = "" for letter in str(target): if letter.isdigit(): numstring += letter else: continue return numstring target_numbers = str(return_target_numbers(target)) print("Hi, please guess a 3 digit number") won = False i = 0 while won == False: i+=1 print(f"Enter guess({i})") guess = str(input()) print(f"you guessed {guess}") if len(guess) != 3: print("guess a 3 digit number") continue if guess == target_numbers: print("You win!") won = True continue for n,number in enumerate(guess): if number == target_numbers[n]: print("Eggs for breakfast") if number in target_numbers: print("The wind blows strongly to the west") print(f"Well done, you took {i} tries")
true
3477a38f4aaba7bcc0a50a43aa58d38868430b1b
Heino25/python_bible
/Chapter7/tuples.py
257
4.25
4
# Tuples can be used to store data but can not be changed. our_tuple = 1,2,3,"A","B","C" print(our_tuple) our_tuple = (1,2,3,"A","B","C") print(our_tuple) A = [1, 2, 3] A = tuple(A) print(A) (A, B, C,) = 1, 2, 3 print(A) G,H,J = "789" print(G) print(J, H)
true
4f9351bea04a429dffaad2c0001c141be755aeb2
akyare/Python-Students-IoT
/1-python-basics/2-control-flow-statements/ConditionalStatements.py
1,229
4.125
4
# IMPORTANT: # TABS AND SPACES DONT MIX IN PYTHON # Variable to play with age = 22 # Pythonic way to use if statement: if age: print('Will only execute if the age variable is evaluated as True [which it will...], ' 'meaning it holds a value and not None.') # Do not use any of the following: # if age is True: pass # if age == True: pass # if bool(age): pass # When using a simple statement, you can do it on the same line as the header line of the clause # Let's take a look at a conditional statement with multiple statements: if age >= 18: # Because we don't have {} in Python we dont need to argue where to put them for 2 decades. print("You're an:") print('Adult') # indented code belongs to if statement elif age >= 13: # To start an elif construction, it needs to be indented the same as the if statement print("You're a teenager") else: # And of course we can use the else statement. print('Child') # This part is after our conditional statements... print("After conditional statement") # If you want to use empty conditional statements [as a placeholder till implementation] # you can use the pass keyword: if age > 101: pass # Won't compile otherwise else: pass
true
83cf62abdb76cde35b76ef2c608b0b2cdce2257a
akyare/Python-Students-IoT
/1-python-basics/1-baby-steps/2-strings/FormattedStrings.py
479
4.15625
4
# Let's make 2 String variables to play with: first = 'Alexander' last = 'Keisse' # And concatenate them together: full = first + ' ' + last print(full) # Better practice would be using an expression, # which is evaluated at runtime: full_name = f'{first} {last}' full_name_also_valid = F"{first} {last}" print(full_name) print(full_name_also_valid) # Get the full powaaah: fancy_char_counting = F'{"Name has:"} {len(full_name) - 1} {"chars."}' print(fancy_char_counting)
true
e95cf406601b163ca422aa5d3aee605f4a870746
akyare/Python-Students-IoT
/1-python-basics/1-baby-steps/2-strings/UsefullStringMethods.py
1,549
4.46875
4
# Make a variable to play around with: course = 'Python programming' # Lets make it all caps: course_all_upper = course.upper() print(course_all_upper) # Convert to lower case: course_all_lower = course_all_upper.lower() print(course_all_lower) # Create 2 variables all lowercase: first_name = 'alexander' last_name = 'keisse' # First char of every word will be uppercase: full_name = F'{first_name} {last_name}'.title() print(full_name) # Let's see how we strip excessive white spaces: course_excess_whitespace = ' course' print(course_excess_whitespace) # Good practice to do this with user input: course_fixed = course.strip() print(course_fixed) # You can even take it a step further trimming left or right: course_excess_whitespace_left = ' course' course_excess_whitespace_right = 'course ' # Left trim: course_fixed_left = course_excess_whitespace_left.lstrip() # Right trim: course_fixed_right = course_excess_whitespace_right.rstrip() # Print the results: print(course_fixed_left) print(course_fixed_right) # If you want to search a string value for a certain value: print(course.find('pro')) # You will find start index # If the value can't be found -1 is returned: print(course.find('Pro')) # Lets replace a char in our string course for another one: course_replaced_a_char = course.replace('o', '0') print(course_replaced_a_char) # Lets see if a certain value is present in our course variable: print('Python' in course) # Or see if it is absent: print('python' not in course)
true
80402030f0c62fa0b2f3e708a61e86054d179424
akyare/Python-Students-IoT
/1-python-basics/1-baby-steps/4-operators/LogicalOperators.py
879
4.40625
4
# Lets make a variable to play with: name = 'Alex' empty_name = '' spaces_string = ' ' # In Python we have 3 logical operators: # and # or # not # Lets take a look at some examples with not operator: if not name: # We are using the fact that an empty string is Falsy print("name is empty") if not empty_name: print("empty_name is empty") # To check if the value of our variable is not simply whitespaces: if not spaces_string.strip(): print("spaces_string is actually an empty string after removing the spaces") # Create a new variable to play with: age = 12 # Now lets use the and operator: if age >= 18 and age < 65: print("Eligible") # And for completeness the or operator: if False or 1: print('1 is True') # This is called chaining comparision operators age = 21 if 18 <= age < 65: print('chaining comparision operators: 18 <= age < 65')
true
f5b55f399d2c0a3c3862147e051cb3611c53047b
akyare/Python-Students-IoT
/1-python-basics/1-baby-steps/1-start/MutableInmutable.py
790
4.5
4
# Reserving memory space: x = 420 # Lets lookup the memory location: print(f'memory address of variable x: {id(x)}, value: {x}') # String, boolean and Integers are immutable so the python interpreter # will allocate a new memory location if we alter the value of a variable: x = 42 print(f'memory address of variable x: {id(x)}, value: {x}', '\n') # Lists however are mutable objects: list_numbers = [1, 2, 3] print(f'memory address of variable list_numbers: {id(list_numbers)}, value: {list_numbers}') # Lets see what our memory address is after some changes: list_numbers.append(4) print(f'memory address of variable list_numbers: {id(list_numbers)}, value: {list_numbers}') # BONUS PART # Learn more: # Memory management in Python: https://www.youtube.com/watch?v=F6u5rhUQ6dU
true
c620336125ebe68de0ca55ff27123916a05fd8dc
akyare/Python-Students-IoT
/2-data-structures/1-list/AccessingItemsInList.py
1,112
4.53125
5
# Lets make a list to play with: letters = ['a', 'b', 'c', 'd'] # If you want to access the first item: print(f'first item: {letters[0]}') # The last item can be found as such: print(f'last item: {letters[-1]}') # Easy enough right? Ok now lets modify the first item: # letters[0] = 'A' letters[0].upper() # Does the same as the above expression # Now let's see what happened to our list: print(letters) # Just as we can slice strings we can slice our lists: print(letters[0:3]) # returns the first three elements # print(letters[:3]) # remember we can leave the first or second argument [Python assumes you start at 0] print(letters[1:]) # or leave the last index ;) # If we want a copy of our list: print(f'original list id: {id(letters)}') print(f'copied list id: {id(letters[:])}') # And we can also use steps to determine what will be taken out of our list: print(letters[::2]) # Lets make a second list to make it a bit more clear: numbers = list(range(101)) print(numbers[::2]) # this way we get al the even numbers # We can also reverse the list as follows: print(numbers[::-1])
true
c509a17867a1c25ba71dbfa330ea2d4bb55e3066
Zerl1990/algorithms
/sorting/insertion.py
1,032
4.34375
4
"""Insertion sort implementation.""" import random def insertion_sort(arr: list) -> list: """Sort list of values using insertion sort algorithm :param arr: List of values :return: New list with numbers sorted """ s_arr = arr.copy() for j in range(1, len(s_arr)): i = j - 1 while i > 0 and s_arr[i] > s_arr[i+1]: print_sorting_progress(s_arr, i, i+1) s_arr[i], s_arr[i + 1] = s_arr[i+1], s_arr[i] i -= 1 return s_arr def print_sorting_progress(arr: list, *args): """Print sorting progress :param arr: Current results. :param args: List with index to highlight :return: None """ values = [] for index, value in enumerate(arr): value = str(value) if index in args: value = '[' + value + ']' value = value.rjust(6) values.append(value) print(' '.join(values)) if __name__ == '__main__': numbers = random.sample(range(0, 100), 10) numbers = insertion_sort(numbers)
true
1538c1555a47b9f80d0270c56820f47624de73f8
jsalmoralp/Python-Proyecto-Apuntes
/Curso/paquete/07_Listas.py
1,432
4.625
5
""" Listas: Son estructuras de datos que nos permiten almacenar distintos valores. (equivalentes a los arrays en otros lenguajes de programación) Son estructuras dinámicas, pueden MUTAR. """ # Creamos una Lista con llaves. lista1 = ["Joan", 25, 98.3, True, "Pepi", 56.3] print(lista1) print(lista1[:]) # Toda la lista. print(lista1[2]) # Un elemento en concreto. print(lista1[-1]) # El último elemento. print(lista1[0:3]) # Una porción de la lista. print(lista1[:2]) # Desde la primera posición con dos valores. print(lista1[3:]) # Desde la posicion 3 hasta el final. lista1.append("Nuevo valor") # Añadimos un nuevo valor al final de la lista. print(lista1) lista1.insert(4, "Valor sitio predeterminado") # Añadimos un valor en un indice predeterminado. print(lista1) lista1.extend(["añadimos", "otra", "lista"]) # Fusionamos dos listas. print(lista1) print(lista1.index("Pepi")) # Saber en que indice se encuentra un elemento. lista1.remove(56.3) # Elimina un elemento por su valor. print(lista1) lista1.pop() # Elimina el ultimo elemento de una lista. print(lista1) lista2 = ["esto es", "otra", "lista"] lista3 = lista1 + lista2 # Podemos almacenar en una variable todos los valores de dos listas. print(lista3) print(lista2 * 2) # Podemos crear una lista que todos sus valores estan duplicados. print("otra" in lista2) # Devuelve true o false si el elemento que le pasamos esta dentro de la lista.
false
3941dd5d6740e825e479e6bce66ced9b9ccc7957
bappi2097/hackerrank-python
/hackerrank/sWAP cASE.py
365
4.15625
4
def swap_case(s): list_s = list(s) for i in range(len(list_s)): if list_s[i].isalpha(): if list_s[i].isupper(): list_s[i] = list_s[i].lower() else: list_s[i] = list_s[i].upper() return "".join(list_s) if __name__ == '__main__': s = input() result = swap_case(s) print(result)
false
e587920da5eeef79a828ffba23a0a02f299a26e7
johnyildr/homework-repo
/questionslist.py
1,038
4.28125
4
# 1-) By typing spam['a', 'b', 'hello', 'd'] # 2-) It evaluates to 0, assigning 0 as a variable. # 3-) It evaluates to assign -1 as an item inside spam. # 4-) It evaluates to assign -6 as an item inside spam. # 5-) It evaluates to assign :2 as an item inside spam. # 6-) bacon.index('cat') evaluates to 1 # 7-) bacon.append(99) evaluates to add 99 to the list. # 8-) bacon.remove('cat') removes 'cat' from the list. # 9-) The operator for concatenation is +, while the operator for replication is *. # 10-) The difference between append and insert is that append can add new items to the list but insert can modify an occupied position. # 11-) The first way is using the remove() method and the other way is to use pop() # 12-) One of the similarities between string and list are that string is that they both can display things on the screen, secondly they both need print to display, and lastly they both # 13-) They contain items. # 14-) deepcopy() creates a new object which is a copy, while copy() only copies it to another object.
true
385825aef2a7bdf148c544f7804e1ad5bbe9aad7
Timeandspace7/LearnPythonExercise
/guessGame.py
604
4.15625
4
#!/usr/bin/env python3 # # Number Guessing Game! def prompt(num): # Use this function to ask the user about a guess. # This function returns 'H', 'L', or 'C'. print(f"My guess: {num}") inp = "" while inp.upper() not in ['H', 'L', 'C']: inp = input(f"Is {num} too (H)igh, too (L)ow, or (C)orrect? ") return inp.upper() def play(max): print(f"Think of a number from 1 to {max}.") num = input("When you're ready, press Enter.") while (prompt(num) != "C"): num = input("press Enter."); print(f"Yes, it's {num}"); play(1000)
true
6b75f151567a541b8e95248b75e00f27eba8390d
Jorza/python-useful-codes
/palindrome_test.py
498
4.1875
4
def palindrome_test(in_string, bad_chars): """ Find if the inputted word is a palindrome :param in_string: :param bad_chars: :return: """ # Reconstruct input string without bad characters or spaces (only letters) letter_string = "".join([char for char in in_string.lower() if char not in bad_chars]) letter_string = letter_string.replace(" ", "") # Determine if string of letters is a palindrome return letter_string == letter_string[::-1]
true
1b5dfbc6590c146fd9719fe0d3388cf12a502c7e
Shourya0902/Learning
/interquartiles.py
1,444
4.125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'interQuartile' function below. # # The function accepts following parameters: # 1. INTEGER_ARRAY values # 2. INTEGER_ARRAY freqs # def median(b): a = len(b) b.sort() if (a % 2) == 0: c = int(a / 2) med = (b[c-1]+b[c])/2 elif (a % 2) == 1: c = int((a-1)/2) med = b[c] return int(med) def quartiles(arr): # Write your code here b = list(arr) b.sort() a = int(len(b)) x = list() y = list() z = list if a % 2 == 0: c = int((a/2) - 1) x = (b[:c+1]) y = (b[c+1:]) q1 = median(x) q2 = median(b) q3 = median(y) elif a % 2 == 1: c = int((a-1)/2) x = (b[:c]) y = (b[c+1:]) q1 = median(x) q2 = b[c] q3 = median(y) qd = q3 - q1 return qd def interQuartile(values, freqs): # Print your answer to 1 decimal place within this function arr = list() for i in range(len(values)): for j in range(freqs[i]): arr.append(values[i]) a = quartiles(arr) return print(float(a)) if __name__ == '__main__': n = int(input().strip()) val = list(map(int, input().rstrip().split())) freq = list(map(int, input().rstrip().split())) interQuartile(val, freq)
false
c6b27e8fcaa98873d66e7768337c709cdbc76c79
gsakthi1/PythonExercise
/PythonBasics/basic_list_tup_dict.py
1,790
4.28125
4
# List - Can do everything [] a = ["sakthi","srishti","shanthi"] print(a) print(a[2]) print(a[0:3]) for x in a: print('Looping : ',x) a.append("shakthi") print(len(a)) if 'shakthi' in a: print("shakthi present") else: print("shakthi Not present") #Tuple - Cannot remove an item, can add items. () thistuple = ("apple", "banana", "cherry") print(thistuple) thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) #Sets - Unordered, Unindexed {} items thisset = {"Set_apple", "Set_banana", "Set_cherry"} #Order of print will vary as the items are unordered for x in thisset: print(x) thisset.add("orange") thisset.update(["up1",'up2','up3']) set1 = {"a", "b" , "c"} set2 = {1, 2, 3} set3 = set1.union(set2) print(set3) #Dictonaries - Unordered, Unindexed {} items (Key - Value Pairs) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["model"]) print(thisdict.get("brand")) thisdict["year"] = 2018 #Print keys for x in thisdict: print("Keys :" ,x) #Print values for x in thisdict: print("Values 1:" ,thisdict[x]) for x in thisdict.values(): print("Values 2:" ,x) for x, y in thisdict.items(): print("Both:", x, y) #Nested dictionaries child1 = { "name" : "Emil", "year" : 2004 } child2 = { "name" : "Tobias", "year" : 2007 } child3 = { "name" : "Linus", "year" : 2011 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 } print(myfamily) child4 = child3 print(child4) child4["year"] = 2019 print(myfamily) childy = child2.copy() childy["year"] = 2020
true
81847819aafe37edf10e00eb1931b51a2e1b642c
shub0/algorithm-data-structure
/python/search_2D_matrix.py
2,215
4.125
4
#! /usr/bin/python ''' 1.Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. 2. Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascending from top to bottom. For example, Consider the following matrix: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true. Given target = 20, return false. ''' class Solution: # @param matrix, a list of lists of integers # @param target, an integer # @return a boolean def searchMatrix(self, matrix, target): m = len(matrix) n = len(matrix[0]) start = 0 end = m * n - 1 while start <= end: mid = start + (end - start) / 2 mid_row = mid / n mid_col = mid % n if matrix[mid_row][mid_col] < target: start = mid + 1 elif matrix[mid_row][mid_col] > target: end = mid - 1 else: return True return False def searchMatrix2(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ ROW = len(matrix) if ROW < 1: return False COL = len(matrix[0]) col = COL - 1 row = 0 while col >= 0 and row < ROW: if matrix[row][col] == target: return True if matrix[row][col] > target: col -= 1 else: row += 1 return False if __name__ == '__main__': solution = Solution() print solution.searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,50]], 3)
true
84bcc94cbd374a026dfec54270c340db224b864b
shub0/algorithm-data-structure
/python/simplify_path.py
808
4.125
4
#! /usr/bin/python ''' Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" ''' class Solution: # @param path, a string # @return a string def simplifyPath(self, path): segments = path.split('/') simple_path = list() for segment in segments: if segment == '.': continue elif segment == '..': if len(simple_path) > 0 : del simple_path[-1] elif len(segment) > 0: simple_path.append(segment) return '/' + '/'.join(simple_path) if __name__ == '__main__': solution = Solution() print solution.simplifyPath('/home/') print solution.simplifyPath('/a/./b/../../c/')
true
7d916767d868feceaf75bfcdfe338d8dbe837905
shub0/algorithm-data-structure
/python/reconstruct_itinerary.py
1,805
4.25
4
''' Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. Example 1: tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Return ["JFK", "MUC", "LHR", "SFO", "SJC"]. Example 2: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Return ["JFK","ATL","JFK","SFO","ATL","SFO"]. Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. ''' class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ import collections graph = collections.defaultdict(list) for (src, dest) in tickets: graph[src].append(dest) for city in graph: graph[city].sort(reverse = True) path = list() def dfs(city): while len(graph[city]) > 0: dest = graph[city].pop() dfs(dest) path.append(city) dfs("JFK") return path[::-1] solution = Solution() print solution.findItinerary([["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]) print solution.findItinerary( [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]])
true
0b67dabe30f08389faf87970aa0f068c51e53951
aldrichwidjaja/CP1404PRAC
/PRAC_02/password_checker.py
1,013
4.1875
4
import re while True: user_input = input("Enter a password : ") is_valid = False if (len(user_input)<6 or len(user_input)>12): print("Not Valid! Total characters should be between 6 and 12") continue elif not re.search("[A-Z]",user_input): print("Not valid! It should contain one letter between A-Z") continue elif not re.search("[a-z]", user_input): print("Not valid! It should contain one letter between a-z") continue elif not re.search("[1-9]", user_input): print("Not valid! It should contain one number between 1-9") continue elif not re.search("[@!&+_*^$#&]", user_input): print("Not valid! It should contain special characters") continue elif re.search("[\s]", user_input): print("Not valid! It should not contain any space") continue else: is_valid = True break if(is_valid): print("Password is valid: ", user_input)
true
3231f933c600dc261fb641e6a2efed15a7101c25
aldrichwidjaja/CP1404PRAC
/PRAC_05/hex_colours.py
457
4.21875
4
color_name = {"ALICEBLUE": "#f0f8ff", "WHITE1": "#F13122", "WHITE2": "#F12T1F2", "WHITE3": "#F141T2", "RED1": "#F14123R", "RED2": "#Y125123T", "BLACK10": "#F1F1F22", "BLACKWHITE": "#F1F122222" } pickcolor = input("Enter color of choice: ").upper() while pickcolor !="": if pickcolor in color_name: print(pickcolor, "is", color_name[pickcolor]) else: print("Invalid choice!") pickcolor = input("Enter color of choice: ").upper()
false
0797d93780db12204dbaf367ee134f51759e2679
jojojames/Python
/MiniPrograms/forLoopskhan.py
1,294
4.5
4
#For Loops - Khan Academy #Range, a built in python function ###### range, print ranges range formatforrange (start | stop | step) print "This prints out a range of 6, which starts from 0 and ends at 5..range(6)", range(6) print "This prints out a range of 7, which starts from 0 and ends at 6..range(7)", range(7) print "This prints out a range from 1 - 7, but not including 7..range(7)", range(1,7) print "This prints out a range from 2 - 8, but not including 8,,range(8)", range(2,8) print "This prints out a range from 2 to 20, not including 20, incrementing by 3", range(2,20,3) print "This prints out a range from 100-0, subtracting 20 incrementally", range(100,-1,-20) ###### for loop - basic loop for i in range(5): #remember the colon print i #prints out 0-4 for i in range(10): #remember the colon print i, #prints out 0-9 #the , puts the numbers on the same line print "\n" #new line print "basic for loop has ended" #### for loop - adding print "for loop - adding" sum = 0 for i in range(10): #remember the colon sum = sum + i print sum, #### for loop - subtracting print "" print "for loop - subtracting" total = 100 for i in range(5): total = total - 20 print total,
true
a1fd2abf6a1ee858b74ec06e6dbc4549824273da
jojojames/Python
/MiniPrograms/factorial.py
782
4.53125
5
#Writing A Simple Factorial Program - Khan Academy # - factorial - # 1! = 1 , 2! = 2 * 1, 3! = 3 * 2 * 1, 4! = 4 * 3 * 2 * 1 -- and so on #another basic for loop number = input("Enter a non-negative interger to take the factorial of: ") #string product = 1 for i in range(number): #range provides a list of numbers product = product * (i+1) print product ###Defining a Factorial Function #returns the factorial of the wrgument "number" def factorial(number): product = 1 for i in range(number): product = product * (i+1) return product user_input = input("Enter a non-negative interger to take the factorial of: ") factorial_of_user_input = factorial(user_input) print factorial_of_user_input
true
57c5c5a14d23478c6e2cb81efc299746c3a3585c
devanujpatel/python_learning
/learning classes/reversing a word.py
288
4.1875
4
class Reverse: def reverse_word(self,word): my_reverse_word = "" reversed=word[::-1] for letters in reversed: my_reverse_word += letters print(my_reverse_word) attribute=input("enter a word: ") obj=Reverse() obj.reverse_word(attribute)
true
21d4ba20b72da8e442179aa004c43c590ee8921f
yusrahassan737/SimplePython
/die.py
451
4.21875
4
# Name: Yusra Hassan # Date: September 16, 2020 # Decription: Very simple simulation of rolling a die # Purpose: Practice with random module # Start-Up import random action = input("Type \"roll\" to roll the die: ") # Ouput a random number from 1-6 however many times the user first said to if (action == "roll"): times = int(input("How many times? ")) while times > 0: print(random.randint(1, 6)) times = times - 1
true
7795bfbec233eed264b5687599681e0583787283
rajeshroshanprasad/python-practice
/prac2.py
457
4.15625
4
#types of variable: instance variable and class variable #instance variable is defined in object __init__ #class variable is defined in class. if this is changed it will change all the object class car: wheel = 5 # class variable #instance variable def __init__(self,brand,rank): self.brand = brand self.rank = rank car1=car("audi", 1) car2=car("Mercedes",2) print(car.wheel) print(car1.brand, car1.rank, car2.brand, car2.rank)
true
23e39b5dde1588b148ff3f44450392fc5f432c76
anAmeQ/learnpython
/code/ex3.py
1,240
4.46875
4
# -*- coding: utf-8 -*- print"I will not count my chickens:" print"Hens", 25.0 + 30 / 6 print"Roosters", 100.0 - 25 * 3 % 4.0#余数运算 print"Now I will count the eggs:" print 3.0 + 2 + 1 - 5 + 4.0 % 2.0 - 1 / 4 + 6#运算优先级 print"Is it true that 3 + 2 < 5 - 7?" print 3.0 + 2 < 5 - 7#直接显示运算正确与否 print"what is 3 + 2?",3.0 + 2 print"what is 5 - 7?",5.0 - 7 print"Oh,that's why it's False." print"How about some more." print"Is it greater?",5.0 > -2 print"Is it greater or equal",5.0 >= -2 print"Is it less or eaqul?",5.0 <= -2 print 12 * 6 # 。意思一下 # 浮点数就是小数==。因为python版本不同浮点数处理稍微不同。 # 重写就是整数后面加个.0,照做了233 print"I will not count my chickens:" print"Hens", 25.0 + 30.0 / 6.0 print"Roosters", 100.0 - 25.0 * 3.0 % 4.0 print"Now I will count the eggs:" print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 print"Is it true that 3 + 2 < 5 - 7?" print 3.0 + 2.0 < 5.0 - 7.0 print"what is 3 + 2?",3.0 + 2.0 print"what is 5 - 7?",5.0 - 7.0 print"Oh,that's why it's False." print"How about some more." print"Is it greater?",5.0 > -2.0 print"Is it greater or equal",5.0 >= -2.0 print"Is it less or eaqul?",5.0 <= -2.0
false
f0af257825449f216ce3fa08afc099414c98176b
ShubhamDalbhanjan/LetsUpgradeFCSpython
/Assignment3.py
1,331
4.125
4
#!/usr/bin/env python # coding: utf-8 # # Assignment 3 Letsupgrade Python FCS Day 3 # - Q.1 write a program for sum of n numbers using while loop # In[2]: num = 16 if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) # In[10]: num =int(input("enter number")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) # In[11]: num =int(input("enter number")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate until zero while(num > 0): sum += num num -= 1 print("The sum is", sum) # - Q.2. Take a integer and find prime or not # In[46]: num = int(input("Enter a number: ")) # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") break else: print(num,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num,"is not a prime number") # In[ ]: # In[ ]: # In[ ]:
true
3f42a24a15f240cab31c75a198998f93c42a5ed4
xinyu88/PYTHON-ESERCIZI2
/es28.py
1,467
4.28125
4
''' I nomi della città e i corrispondenti Codici di Avviamento Postale (CAP) vengono inseritida tastiera e memorizzati in un dizionario, dove la CAP è la chiave. Fornito poi da tastiera il nome di una città, costruisci un programma che visualizzi il suo CAP oppure un messaggio nel caso la città non sia compresa nell'elenco. Analogamente, fornendo il CAP restituisce il nome della città oppure un messaggio di errore ''' dcitta = {} dcap = {} print("inserisci 1 per terminare") while True : cap = int(input("inserisci il CAP : ")) citta = input("inserisci il nome della citta : ") if cap == 1 or citta == "1" : break else : dcap[cap] = citta #CAP è la chiave dcitta[citta] = cap #citta è la chiave print("Dato il nome della città o il CAP, vuoi sapere la città o il CAP ? ") print("inserire 1. se vuoi sapere il nome della città corrispondente al CAP ") print("inserire 2. se vuoi sapere il cap") r = int(input("risposta = ")) if r == 1 : cap = int(input("inserisci il CAP : ")) if cap in dcap : print("la città avente come CAP", cap, "è", dcap[cap]) else : print("Nessuna città avente CAP", cap) else : citta = input("inserisci il nome della città di cui vuoi conoscere il CAP : ") if citta in dcitta : print("Il CAP di", citta, "è", dcitta[citta]) else : print("Nessuna CAP della città", citta)
false
e7fc5ade51ad6fd0e0c448dd68582dfaf5f0133d
tsikorksi/class-scripts
/quicksort.py
1,835
4.34375
4
# Quicksort algorithm - measured with cProfiler # Time Complexity : # items | total | sort only # 1 - 5ms / 0 # 10 - 6ms / 0 # 100 - 7ms / 0 # 1000 - 12ms / 4ms # 10000 - 120ms / 95ms # 100000 - 350ms / 199ms (maximum recursion depth reached, algorithm did not finish execution) # memory usage: since it uses O(logn) memory to store the recursive arrays, this algorithm is quite memory inefficient # , hence why python stops the process if too many items are present. CPU usage is quite low, as the algorithm is # optimised for performance over memory usage import random def quick_sort(sorting_array): """ quicksort algorithm :param sorting_array: the list to be sorted :return: the two split half of the list """ if len(sorting_array) == 1 or len(sorting_array) == 0: return sorting_array else: pivot = sorting_array[0] i = 0 for j in range(len(sorting_array) - 1): if sorting_array[j + 1] < pivot: sorting_array[j + 1], sorting_array[i + 1] = sorting_array[i + 1], sorting_array[j + 1] i += 1 sorting_array[0], sorting_array[i] = sorting_array[i], sorting_array[0] first_part = quick_sort(sorting_array[:i]) second_part = quick_sort(sorting_array[i + 1:]) first_part.append(sorting_array[i]) return first_part + second_part def generator(count): """ generates lists of random numbers depending on supplied count :param count: number of items to generate :return: list of random numbers """ random_list = [random.randrange(1, 101, 1) for _ in range(count)] return random_list def tester(): """ tests timings of quicksort :return: """ count = 10000 random_list = generator(count) quick_sort(random_list) tester()
true