blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
273a89d8a1cdacd050949614756f6f6f54722eee
L0ganhowlett/Python_workbook-Ben_Stephenson
/65 Compute the Perimeter of a Polygon.py
505
4.25
4
#65: Compute the Perimeter of a Polygon import math dist=lambda x,y,w,z:float(math.sqrt(((w-x)**2)+((z-y)**2))) perimeter=0.0 x=input("Enter the x-coordinate:") y=input("Enter the y-coordinate:") w=x z=y while x!="": a=x b=y x=input("Enter the x-coordinate:") y=input("Enter the y-coordinate:") if x!="": perimeter+=dist(float(x),float(y),float(a),float(b)) else: perimeter+=dist(float(a),float(b),float(w),float(z)) print("Perimeter:",perimeter)
false
802259a7fc26d6bb9eeb002c75cbb489d34e5b31
L0ganhowlett/Python_workbook-Ben_Stephenson
/49 Ritcher Scale.py
940
4.21875
4
# 49 Ritcher Scale a = float(input("Enter the magnitude: ")) if a < 2.0: print("Magnitude of ",a," earthquake is considered Micro earthquake") elif 2.0 <= a < 3.0: print("Magnitude of ",a," earthquake is considered Very minor earthquake") elif 3.0 <= a < 4.0: print("Magnitude of ",a," earthquake is considered Minor earthquake") elif 4.0 <= a < 5.0: print("Magnitude of ",a," earthquake is considered Light earthquake") elif 5.0 <= a < 6.0: print("Magnitude of ",a," earthquake is considered Moderate earthquake") elif 6.0 <= a < 7.0: print("Magnitude of ",a," earthquake is considered Strong earthquake") elif 7.0 <= a < 8.0: print("Magnitude of ",a," earthquake is considered Major earthquake") elif 8.0 <= a < 10.0: print("Magnitude of ",a," earthquake is considered Great earthquake") elif 10.0 <= a: print("Magnitude of ",a," earthquake is considered Meteoric earthquake")
false
84cf3eee10b3ffd05bcb2930ee134646da979cb7
moisotico/Python-excercises
/excersices/lists/queue_linked_list.py
1,352
4.375
4
# Represents the node of list. class Node: def __init__(self, data): self.data = data self.next = None class CreateList: # Declaring tle pointer as null. def __init__(self): self.head = Node(None) self.tail = Node(None) # method to add element to linked list queue def add(self, data): newNode = Node(data) # check if list is empty if self.head.next is None: self.tail = newNode self.head.next = self.tail else: self.tail.next = newNode self.tail = self.tail.next # method to add element to linked list queue def remove(self): # pop head element if self.head is not None: self.head = self.head.next # show list from the top def peek(self): node = self.head.next while node is not None: print(node.data) node = node.next # show list from the top def isEmpty(self): if self.head.next is None: print("The queue is empty!") else: print("The queue is not empty") if __name__ == "__main__": list = CreateList() list.add(7) list.add(5) list.add(9) list.add(2) list.remove() list.remove() list.remove() list.remove() list.peek() list.isEmpty()
true
de1cc3bf61e9fea5b0f108804f7a0b45da0ba4dc
python240419/07.06.2019
/foreach.py
317
4.125
4
names = ['yossi', 'dana','orli', 'yosef'] print(names) # for loop # foreach name in named do #for name in reversed(names): for name in names: #print(f'{name} is type {type(name)}') if name == 'orli': break # exit the loop print(f'{name}') if name == 'dana': print('this is dana')
false
69f281633daafdebdb472d1db228660eb9344164
Ndkkqueenie/hotel-guest
/guest.py
2,502
4.59375
5
#Let's say we have a text file containing current visitors at a hotel. # We'll call it, guests.txt. Run the following code to create the file. # The file will automatically populate with each initial guest's first name on its own line. guests = open("guests.txt", "w") initial_guests = ["Bob", "Andrea", "Manuel", "Polly", "Khalid"] for i in initial_guests: guests.write(i + "\n") guests.close() #with open("guests.txt") as guests: # for line in guests: # print(line) # The output shows that our guests.txt file is correctly populated with each initial guest's first name on its own line. Cool! # Now suppose we want to update our file as guests check in and out. # Fill in the missing code in the following cell to add guests to the guests.txt file as they check in. new_guests = ["Sam", "Danielle", "Jacob"] with open("guests.txt", "a") as guests: for i in new_guests: guests.write(i + "\n") guests.close() # with open("guests.txt") as guests: # for line in guests: # print(line) # Now let's remove the guests that have checked out already. There are several ways to do this, however, the method we will choose for this exercise is outlined as follows: # Open the file in "read" mode. # Iterate over each line in the file and put each guest's name into a Python list. # Open the file once again in "write" mode. # Add each guest's name in the Python list to the file one by one. # Ready? Fill in the missing code in the following cell to remove the guests that have checked out already. checked_out=["Andrea", "Manuel", "Khalid"] temp_list=[] with open("guests.txt", "r") as guests: for g in guests: temp_list.append(g.strip()) with open("guests.txt", "w") as guests: for name in temp_list: if name not in checked_out: guests.write(name + "\n") with open("guests.txt") as guests: for line in guests: print(line) # Now let's check whether Bob and Andrea are still checked in. How could we do this? # We'll just read through each line in the file to see if their name is in there. # Run the following code to check whether Bob and Andrea are still checked in. guests_to_check = ['Bob', 'Andrea'] checked_in = [] with open("guests.txt","r") as guests: for g in guests: checked_in.append(g.strip()) for check in guests_to_check: if check in checked_in: print("{} is checked in".format(check)) else: print("{} is not checked in".format(check))
true
a1a5b7049dbf72c07391b584fcc43609393d9636
eclairsameal/TQC-Python
/第4類:進階控制流程/PYD408.py
243
4.125
4
even = 0 odd = 0 for i in range(10): n = int(input()) if n%2==0: even+=1 else: odd+=1 print("Even numbers: {}".format(even)) print("Odd numbers: {}".format(odd)) """ Even numbers: _ Odd numbers: _ """
false
21edc9be5705343c347caaba952e3c26da5f6781
eclairsameal/TQC-Python
/第2類:選擇敘述/PYD202.py
226
4.40625
4
x = int(input()) if x%3==0 and x%5==0: print(x,"is a multiple of 3 and 5.") elif x%3==0: print(x,"is a multiple of 3.") elif x%5==0: print(x,"is a multiple of 5.") else: print(x,"is not a multiple of 3 or 5.")
true
594d46ab05cf2c2aa160bc7a331ee448f19b69fc
rdsim8589/holbertonschool-higher_level_programming
/0x06-python-test_driven_development/4-print_square.py
458
4.28125
4
#!/usr/bin/python3 """ This is the "Print Square" module The Print Square module supplies the simple function\ to print a square of # of a size """ def print_square(size): """ Return the square of # of size x size """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") if size > 0: print("\n".join(["#" * size for i in range(size)]))
true
f28d2166344842ed4018a25f78aa1accfa9bd03e
zabilsabri/Sum-Of-Odd-Series
/Odd Number Sequence.py
321
4.125
4
_foundby_ = "zabilsabri" n = 9 # YOUR ODD NUMBER INPUT answer = 1 if n % 2 == 0: # CHECK IF YOUR INPUT NUMBER ODD OR EVEN print("ODD") else: for i in range(n): if i % 2 != 0: # OMIT ALL EVEN NUMBER answer = answer + i answer += 2 # ADD 2 EVERY LOOPING print(answer)
false
702df8cff2c17e2685aac36a4384b8b499bf7e05
bhavikjadav/Python_Crash_Course_Eric_Matthes_Chapter_4
/4.9_Cube Comprehension.py
273
4.25
4
#!/usr/bin/env python # coding: utf-8 # # 4-9. Cube Comprehension: Use a list comprehension to generate a list of the first 10 cubes. # In[1]: # This is call Comprehension of a list. cubes = [value**3 for value in range(1, 10)] # In[2]: print(cubes) # In[ ]:
true
14732573cc07a9067e3362c35343bd1755b4d707
LogeshRe/Python-Utilities
/Filelist.py
810
4.1875
4
# This Program is to get the List of files in a folder # On Running it opens file explorer. # Choose the folder you want. # Once again explorer opens. # Give a name for file and save it as txt. # The file contains the list of all files in the folder. # 23/12/18 from tkinter.filedialog import askdirectory from tkinter.filedialog import asksaveasfile from os import listdir def openfile(): folder = askdirectory() return(folder) def filesave(files = [] , *args): filetypes = [("All Files","*"),("Text",".txt")] f = asksaveasfile(mode = 'w', defaultextension=".txt",filetypes = filetypes) if f is None: return else: for name in files: f.write(name + '\n') f.close def main(): filepath = openfile() filelist = listdir(filepath) filesave(filelist) if __name__ == "__main__" : main()
true
d3c8c439fcecd822f0c85be872905a7a8200ce5b
lingsitu1290/code-challenges
/random_problems.py
1,818
4.1875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Write a program that asks the user to enter 10 # words, one at a time. The program should then # display all 10 words in alphabetical order. Write # this program using a loop so that you don't have to # write any additional lines of code if you were to # change the program to ask the user for 100 words. # That is, you'd only need to make one simple change, # and not have to write any new lines of code. def return_sorted_nums(num): result = [] for i in range(num): word = raw_input("Please give me a word:") result.append(word) for word in sorted(result): print word # return_sorted_nums(10) # Create a program that calculates the median of # this array of odd numbers: [1, 3, 4, 7, 12] which # should output “4”, the median. Be sure your # program can determine the median of any array # having an odd number of elements. To check, # replace the array above with [1, 2, 5, 9, 12, 13, 17] # where the median “9” should be returned. import math def return_median(lst): """ >>> return_median([1,3,4,7,12]) 4 >>> return_median([1,2,5,9,12,13,17]) 9 """ return lst[int(math.ceil(len(lst)/2))] # Find the intersection of two sorted arrays. Can assume numbers are unique """ def intersection(list1, list2): """ >>> intersection([1,2,3,4,5,6],[5,6,7,8,9]) [5, 6] >>> intersection([7,8,9],[5,6,7,8,9]) [7, 8, 9] """ num_set = set() result = [] for num in list1: num_set.add(num) for num in list2: if num in num_set: result.append(num) return result if __name__ == "__main__": import doctest if not doctest.testmod().failed: print "\n*** ALL TESTS PASS; YOU MUST BE JUMPING WITH JOY\n"
true
53d90eeda0e524a06cc008b24fda1a8343c78131
lingsitu1290/code-challenges
/three_int_sum_to_zero.py
1,428
4.3125
4
# Pixlee Whiteboarding def three_int_sum_to_zero1(lst): """ Determine if any 3 integers in an array sum to 0. #>>> three_int_sum_to_zero1([0,1,2,-1,3,5,2,-2]) #True #>>> three_int_sum_to_zero1([2,3,4,5,-1,2]) #False >>> three_int_sum_to_zero1([2,0,1,9,0]) False """ for i, num in enumerate(lst): for j, num1 in enumerate(lst): for k, num2 in enumerate(lst): #print i, num, j, num1, k, num2 if i == j or j == k or i == k: continue if lst[i] + lst[j] + lst[k] == 0: return True return False def three_int_sum_to_zero2(lst): """ Determine if any 3 integers in an array sum to 0. #>>> three_int_sum_to_zero2([0,1,-1,3,5,2,-2]) #True # >>> three_int_sum_to_zero2([2,3,4,5,-1,2]) # False >>> three_int_sum_to_zero2([2,3,1,9,0,0]) False """ for i, num in enumerate(lst): sublst = lst[i+1:] for j, num1 in enumerate(sublst): subsublst = sublst[j+1:] for k, num2 in enumerate(subsublst): total = num + num1 + num2 # print i, num, j, num1, k, num2 if total is 0: return True return False if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. WOWZA!\n"
false
f4b55e2ea2389bf8dd460a526c99ce0ba16225cf
lingsitu1290/code-challenges
/flip_the_bit.py
1,552
4.15625
4
# Various ways to return 1 if 0 is given and return 0 if 1 is given def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ if num == 0: return 1 else: return 0 #switch, break, return def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ return not num def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ num_dict={0:1,1:0} return num_dict[num] def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ num_list=[1,0] return num_list[num] def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ return (num + 1) % 2 def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ return abs(num-1) def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ # ^ Binary XOR # It copies the bit if it is set in one operand but not both. # (a ^ b) return (num ^ 1) def flip_the_bit(num): """ >>> flip_the_bit(1) 0 >>> flip_the_bit(0) 1 """ # ^ Binary XOR # It copies the bit if it is set in one operand but not both. # (a ^ b) from operator import xor return xor(num, 1) if __name__ == "__main__": import doctest result = doctest.testmod() if result.failed == 0: print "ALL TESTS PASSED"
true
3dd89365fb041b8a6f6581059c8fd761a6c3036e
ARUN14PALANI/Python
/PizzaOrder.py
1,051
4.1875
4
print("Welcome to AKS Pizza Stall!") pizza_size = input(str("Please mention your pizza size 'S/M/L': ")) add_peproni = input("Do you need add peproni in your pizza? Mention (y/n): ") add_cheese = input("Do you need add extra cheese in your pizza? Mention (y/n): ") bill_value = 0 print(add_peproni.lower()) print(pizza_size.lower()) if (pizza_size.lower() == "s"): bill_value = 15 elif pizza_size.lower() == "m": bill_value = 20 elif pizza_size.lower() == "l": bill_value = 25 else: print("Error Occured : Please mention correctly") if (add_peproni.lower() == "y") and pizza_size.lower() == "s": bill_value += 2 elif (add_peproni.lower() == "y") and (pizza_size.lower() == "m" or pizza_size.lower() == "l"): bill_value += 3 if add_cheese == "y" and (pizza_size.lower() == "m" or pizza_size.lower() == "l" or pizza_size.lower() == "s"): bill_value += 1 print(f"You Ordered size :({pizza_size}), Added Peproni ({add_peproni}), Added Extra Cheese ({add_cheese})") print(f"Your total bill value is Rs.{bill_value}/-")
true
b42b11517300a0271107d0206f050dde24ca3bf1
ChiragTutlani/DSA-and-common-problems
/Algorithms/dijkstra_algorithm.py
1,565
4.1875
4
# Three hash tables required # 1. Graph # 2. Costs # 3. Path/Parent Node graph = { "start":{ "a":6, "b":2 }, "a":{ "finish":1 }, "b":{ "a":3, "finish":5 }, "finish":{} } # print(graph) inf = float("inf") costs = { "a": 6, "b": 2, "finish": inf } # print(costs) parent = { "a" : "start", "b" : "start", "finish" : None } # print(parent) processed = [] def find_lowest_cost_node(costs): lowest_cost = float("inf") lowest_cost_node = None for node in costs.keys(): cost = costs[node] if cost < lowest_cost and node not in processed: lowest_cost = cost lowest_cost_node = node return lowest_cost_node node = find_lowest_cost_node(costs) # Find the lowest cost node that hasn't been processed while node is not None: # If you have processed the while loop is done cost = costs[node] neighbors = graph[node] for n in neighbors.keys(): # Go through all its neighbors new_cost = cost + neighbors[n] if costs[n] > new_cost: # Update if cheaper costs[n] = new_cost parent[n] = node processed.append(node) # Mark the node processed node = find_lowest_cost_node(costs) # Repeat print('Shortest path to finish: ' + str(costs["finish"])) print("The path: ", end='') path = " finish" node = "finish" while node!="start": path = " " + parent[node] + path node = parent[node] print(path)
true
96254fbc29edc870dbf9e6db304f997f0147ef93
mjuniper685/LPTHW
/ex6.py
1,156
4.375
4
#LPTHW Exercise 6 Strings and Text #create variable types_of_people with value of 10 assigned to it types_of_people = 10 #Use string formatting to add variable into a string stored in variable x x = f"There are {types_of_people} types of people." #create variable binary and assign it a string binary = "binary" #create variable do_not and assign it a string do_not = "don't" #use string formatting to add the above variables in a string and assign it to variable y y = f"Those who know {binary} and those who {do_not}." #print variable x print(x) #print variable y print(y) #print string and add variable x inside using string formatting print(f"I said: {x}") #print a string and add variable y inside using string formatting print(f"I also said: '{y}'") #assign false to variable hiliarious hilarious = False #create variable with string assigned containing space to insert formatting joke_evaluation = "Isn't that joke so funny?! {}" #print variable and use .format() method to add another variable print(joke_evaluation.format(hilarious)) w = "This is the left side of..." e = "a string with a right side." #concatenate the above strings print(w + e)
true
560e6d3b7fd09e72105961df949917c6198ae7de
henriqueotogami/microsoft-learn-studies
/Atributos da Classe - Aula 39/main.py
584
4.40625
4
class A: #Variável de classe ou atributo da classe vc = 123 #criando objeto, ou melhor, intanciando a classe a1 = A() a2 = A() #Acessando o atributo da classe criado em cada objeto print(a1.vc) print(a2.vc) #Acessando o atributo da classe na estrutura da classe print(A.vc) #Alterando "de fora" o valor do atributo da classe dentro de um objeto, ou seja, na instância a1.vc = 321 #Da forma acima, o valor de 123 permanece fixo dentro da estrutura da classe, ou seja, A.vc = 123 e a2.vc = 123. Vai mudar somente na estrutura da classe que foi instanciada no objeto "a1".
false
6b92d4b843d9754a6206e9d93e5348a769719895
Oskorbin99/Learn_Python
/Other/Lamda.py
520
4.15625
4
# Simple lambda-functions # add = lambda x, y: print(x+y) # add(5, 4) # But it is not good because do not assign a lambda expression, use a def def add_def(x, y): print(x+y) add_def(5, 4) # Use lambda for sort tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')] print(sorted(tuples, key=lambda x: x[1])) print(sorted(range(-5, 6), key=lambda x: x * x)) # Use lambda for lexical closures def make_adder(n): return lambda x: x+n plus_3 = make_adder(3) print(plus_3(4)) print(make_adder(3)(4))
true
162e1267cc8ad48fd285455eca25720328adfa09
Oskorbin99/Learn_Python
/Сlass/Variable.py
500
4.1875
4
class Dog: num_legs = 4 # <- Переменная класса def __init__(self, name): self.name = name # <- Переменная экземпляра jack = Dog('Джек') jill = Dog('Джилл') print(jack.name, jill.name) print(jack.num_legs, jill.num_legs) Dog.num_legs = 3 print(jack.num_legs, jill.num_legs) # True way edit class variables class CountedObject: num_instances = 0 def __init__(self): self.__class__.num_instances += 1
false
eab8aa205f7463c74d64ecf91d1d1c053deda762
barmalejka/Advanced_Python
/hw2/pt1.py
598
4.21875
4
import operator def calc(x, y, operation): try: x = float(x) y = float(y) except ValueError: return 'Inputs should be numbers. Please try again.' operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} if operation not in ['+', '-', '*', '/']: return 'Acceptable operations are +, -, *, /. Please try again.' return operations[operation](x, y) x = input("Enter first number: ") y = input("Enter second number: ") op = input("Enter operation: ") print(calc(x, y, op))
true
985440717e2e19291a05f9afe5b9f7bda9d5ccfa
manas1410/Python-addition
/Addition.py
419
4.15625
4
#program to find the addition of two numbers #takes the input of 1st number from the user and stores it in num1 num1 = int(input("Please enter your number num1:")) #takes the input of 2nd number from thwe user and stores it in num2 num2 = int(input("Please enter your number num2:")) #stores the addition of two numbers add = num1 + num2 #prints the addition two numbers print("Addition of Two numbers is : ",add)
true
a5d29c3be92b2eb4bc8cd2f2fbf8faf8cb37f0d6
dorayne/Fizzbuzz
/fizzbuzz.py
1,595
4.125
4
#!/usr/bin/env python # initialize default values for variables start_c = 1 end_d = 101 div_a = 3 div_b = 5 def error_check(test): # convert input to integer, exit program if input is not a number try: tested = int(test) return tested except: print "Invalid input, please try again and enter a whole number" exit() def fizzbuzz(): ''' Fizzbuzz logic: Print all num in seq, replace with "fizz" if divisible by div_a, with "buzz" if divisible by div_b and with "fizzbuzz" if divisible by div_a AND div_b ''' global div_a, div_b, seq for num in seq: if num % div_a == 0 and num % div_b == 0: print "fizzbuzz" elif num % div_a == 0: print "fizz" elif num % div_b == 0: print "buzz" else: print num ''' Get user input run error_check if length of input is > 0 variable will not be changed from default if input is <= 0 ''' a = raw_input("Enter fizz divisor \n") if len(a) > 0: div_a = error_check(a) b = raw_input("Enter buzz divisor \n") if len(b) > 0: div_b = error_check(b) c = raw_input("Enter range start \n") if len(c) > 0: start_c = error_check(c) d = raw_input("Enter range end \n") if len(d) > 0: end_d = error_check(d) if start_c > end_d: seq = range(start_c, end_d + 1, -1) elif start_c < end_d: seq = range(start_c, end_d + 1) elif start_c == end_d: print "Cannot create range from 2 equal numbers, please try again" exit() else: print "What did the math break?" print "\n" fizzbuzz()
true
829259503dfa0153bcd851bb901474d436a595ff
KRSatpute/GreyAtom-Assignments
/25Nov2017/map_func_run.py
1,128
4.125
4
""" Write a higher order generalized mapping function that takes a list and maps every element of that list into another list and return that list ex: i) Given a list get a new list which is squares of all the elemments of the list ii) Given a list get a list which has squares of all the even numbers and cubes of all the odd numbers from the list Running the map_func """ from map_func import my_map_func def squared(num): """ return square of number """ return num ** 2 def square_even_cube_odd(num): """ return square if num is even else return cube """ return num ** 2 if num % 2 == 0 else num ** 3 def main(): """ running the code """ seq_a = [5, 8, 10, 1, 2] seq_b = [9, 3, 6, 4, 7] print my_map_func(seq_a, squared) # will print [25, 64, 100, 1, 4] print my_map_func(seq_b, squared) # will print [81, 9, 36, 16, 49] print my_map_func( seq_a, square_even_cube_odd) # will print [125, 64, 100, 1, 4] print my_map_func( seq_b, square_even_cube_odd) # will print [729, 27, 36, 16, 343] if __name__ == "__main__": main()
true
4bb91fc31df7ba6caf08dc214bae1132bccd3be0
C-CCM-TC1028-111-2113/homework-2-SofiaaMas
/assignments/04Maximo/src/exercise.py
354
4.125
4
def main(): #escribe tu código abajo de esta línea num1=int(input('Inserta el primer número')) num2=int(input('Inserta el segundo número')) num3=int(input('Inserta el tercer número')) if num2<num1>num3: print(num1) elif num1<num2>num3: print(num2) elif num1<num3>num2: print(mun3) pass if __name__=='__main__': main()
false
fb3abdd0cd80c80246907fdccc11fa1c2c3af742
sanjanprakash/Hackerrank
/Languages/Python/Python Functionals/map_lambda.py
367
4.1875
4
cube = lambda x: x*x*x # complete the lambda function def fibonacci(n): # return a list of fibonacci numbers arr = [] if (n > 0) : if (n >= 2) : arr = [0,1] while (n > 2) : arr.append(arr[-1] + arr[-2]) n -= 1 else : arr = [0] return arr if __name__ == '__main__':
true
2663bd81905b0b3d0b5a0d1a69acc6c190456821
DanielMSousa/beginner-projects
/1. BMI Calculator/Calculadora IMC.py
867
4.1875
4
""" Created on Thu Jun 17 21:54:11 2021 @author: daniel """ print('###################################################') print(' BMI Calculator ') print('###################################################') print() print("This program can't substitute any doctor or health professional diagnosis") print('BMI may not be precise for everyone!') weight = float(input('Insert your weight (kg)')) height = float(input('Insert your height (meters)')) print() bmi = round(weight / (height ** 2), 2) print('Your BMI is {}'.format(bmi)) if bmi < 18.5: print('Underweight') elif 18.6 <= bmi and bmi < 24.9: print('Normal weight') elif 25 <= bmi and bmi < 29.9: print('Overweight') elif 30 <= bmi and bmi < 34.9: print('Obese') elif 35 <= bmi and bmi < 39.9: print('Obese (severe)') else: print('Obese (morbid)')
true
db190d1765bb1b92e6d41c918c351c1ca5a661bc
jwsander/CS112-Spring2012
/hw08/basic_funcs.py
1,637
4.4375
4
#!/usr/bin/env python # Create a greeter def greeter(name): if name == str(name): print "hello,", name.lower() elif name == int(name): print "hello,", name #User Input (Optional): #name = raw_input("What's your name?") #greeter(name) # Draw a box def box(w,h): #Limitations if w == str(w) or h == str(h): print "Error: Invalid Dimensions" elif w != int(w) or h != int(h): print "Error: Invalid Dimensions" elif w <= 0 or h <= 0: print "Error: Invalid Dimensions" #Extra Variables else: listw = ["+"] listh = ["|"] row = "" space = "" #Last line thin_box = False if h < 2: thin_box = True #Changing width w -= 1 while w > 1: listw.append("-") listh.append(" ") #space in middle w -= 1 if w == 1: listw.append("+") #right corner listh.append("|") #right side #Printing rows for x in listw: row += str(x) for y in listh: space += str(y) print row #Changing length while h > 2: print space h -=1 #Bottom line if len(listw) >= 1 and thin_box == False: print row #User Input (Optional) #usr_w = raw_input("Width of box: ") #usr_h = raw_input("Height of box: ") #box(usr_w,usr_h) #Tests box(1,1) box(1,2) box(1,3) box(1,4) box(2,1) box(3,1) box(4,1) box(2,2) box(2,3) box(2,4) box(3,2) box(4,2) box(3,3) box(3,4) box(4,3) box(4,4)
false
d663e2af3f922141c364ecc842dfb337b6f1ea9a
brianpendleton-zz/anagram
/scripts/find_anagrams.py
674
4.25
4
""" Script to find anagrams given an input word and a filepath to a text file of known words. Argparse or Optparse could be used, but no current requirements for optional flags or features to the script. """ from anagram import find_anagrams, load_words_file import sys def main(word, filepath): valid_words = load_words_file(filepath) for anagram in find_anagrams(word, valid_words): print anagram if __name__ == "__main__": if len(sys.argv) != 3: msg = """ Invalid arguments specified. Usage: python find_anagrams.py <word> <filepath> """ print msg else: main(sys.argv[1], sys.argv[2])
true
2bd8767bf274053e614965265ac628b3a5c255f8
colingdc/project-euler
/4.py
489
4.15625
4
# coding: utf-8 # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. def is_palindrome(n): return str(n) == str(n)[::-1] palindromes = [] for i in range(100, 1000): for j in range(100, 1000): ij = i * j if is_palindrome(ij): palindromes.append(ij) print palindromes print max(palindromes)
true
e09b68fe95f607bf91a6aae1bddbec12185e7ff0
antdevelopment1/dictionaries
/word_summary.py
656
4.3125
4
# Prints a dictionary containing the tally of how many # times each word in the alphabet was used in the text. # Prompts user for input and splits the result into indiviual words. user_input = input("Please provide a string to be counted by words: ").split(" ") diction = {} # Creates an empty dictionary. for word in user_input: # Loops through words in user input. if word in diction: # Checks to see if word is already inside dictionary. diction[word] += 1 # If it is, we increment by. else: # Otherwise we assign 1 to any words not repeated more than once. diction[word] = 1 print(diction) # Print the modified dictionary.
true
b117c4ffe9a092727d29ec759efb4b99b1ef3944
ivaben/lambdata
/lambdata_maltaro/df_utils.py
578
4.40625
4
""" utility functions for working with DataFrames """ import pandas import numpy TEST_DF = pandas.DataFrame([1, 2, 3]) def add_list_to_dataframe(mylist, df): """ Adds a list to pandas dataframe as a new column. Then returns the extended dtaframe. """ df["new_column"] = mylist return df def count_zeros(df): """ Transforms a dataframe to a np array, then counts how many 0s are in the array. The result will be printed out. """ num_zeros = (df.values == 0).sum() print("Your Dataframe contains {} zeros".format(num_zeros))
true
82b46061e0d4a3bec5fda8586ded8598926cc36e
Indi44137/Functions
/Revision 4.py
312
4.125
4
#Indi Knighton #6/12/2014 #Revision 4 import math temperature = int(input("Please enter the teperature in fahrenheit: ")) def convert_to_celsius(temperature): fahrenheit = temperature celsius = (fahrenheit - 32) * (5/9) print(celsius) return celsius convert_to_celsius(temperature)
false
51440d306d7272a3b6a18f79515d37366c4c624e
melissed99/driving-route-finder
/dijkstra.py
1,023
4.125
4
def least_cost_path(graph, start, dest, cost): """Find and return a least cost path in graph from start vertex to dest vertex. Efficiency: If E is the number of edges, the run-time is O( E log(E) ). Args: graph (Graph): The digraph defining the edges between the vertices. start: The vertex where the path starts. It is assumed that start is a vertex of graph. dest: The vertex where the path ends. It is assumed that dest is a vertex of graph. cost: A class with a method called "distance" that takes as input an edge (a pair of vertices) and returns the cost of the edge. For more details, see the CostDistance class description below. Returns: list: A potentially empty list (if no path can be found) of the vertices in the graph. If there was a path, the first vertex is always start, the last is always dest in the list. Any two consecutive vertices correspond to some edge in graph. """
true
aef1daa1692f2536688c27101e11b4a830767599
spicywhale/LearnPythonTheHardWay
/ex8.py
747
4.375
4
#assigns the variable formatter = "{} {} {} {}" #changes formatter's format to function. This allows me to replace the {} in line 2 with 4 other values, be it lines of text, numbers or values. #prints formatter with 4 different values print(formatter.format(1, 2, 3, 4)) #prints formatter with 4 different values print(formatter.format("one", "two", "three", "four")) #prints formatter with 4 different values print(formatter.format(True, False, False, True)) #prints formatter with 4 different values print(formatter.format(formatter, formatter, formatter, formatter)) #prints formatter with 4 different values print(formatter.format( "I'm just sitting here.", "Typing lines of text.", "I want an orange.", "Banana Phone.", ))
true
10e46dfa1367cc2ff2d4cdee5de17e1327468b34
CarJos/funcionespy
/9.py
845
4.1875
4
'''9. Construir una función que reciba un entero y le calcule su factorial sabiendo que el factorial de un número es el resultado de multiplicar sucesivamente todos los enteros comprendidos entre 1 y el número dado. El factorial de 0 es 1. No están definidos los factoriales de números negativos. ''' def factorial(entero): if entero == 0: return 1 elif entero > 0: fact = 1 for i in range(1,entero + 1): fact = fact * i return fact def main(): try: entero = int(input("Ingrese un numero entero: ")) if entero < 0: print("El factorial de un negativo no esta definido") else: f = factorial(entero) print ("El factorial del numero es :",f) except ValueError: print("Error") if __name__ == '__main__': main()
false
9545460a2aead536e4ee5ab78f74b31584012464
amandathedev/Python-Fundamentals
/03_more_datatypes/1_strings/04_05_slicing.py
412
4.40625
4
''' Using string slicing, take in the user's name and print out their name translated to pig latin. For the purpose of this program, we will say that any word or name can be translated to pig latin by moving the first letter to the end, followed by "ay". For example: ryan -> yanray, caden -> adencay ''' name = input("What is your name? ") pig_latin = (name[1:]) print(f"{pig_latin}-{(name[0].lower())}ay")
true
1995310414b904bbc19de4c6709f1dc1049b20f0
amandathedev/Python-Fundamentals
/02_basic_datatypes/02_01_cylinder.py
315
4.21875
4
''' Write the necessary code calculate the volume and surface area of a cylinder with a radius of 3.14 and a height of 5. Print out the result. ''' import math radius = 3.14 height = 5 volume = math.pi * (radius ** 2) * height volume = round(volume, 2) print("The volume of the cyliner is " + str(volume) + ".")
true
3f3c65621a8c08e005a3efe10aeb16c43524a08a
amandathedev/Python-Fundamentals
/12_string_formatting/12_01_fstring.py
1,791
4.34375
4
''' Using f-strings, print out the name, last name, and quote of each person in the given dictionary, formatted like so: "The inspiring quote" - Lastname, Firstname ''' famous_quotes = [ {"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."}, {"full_name": "Emo Philips", "quote": "A computer once beat me at chess, but it was no match for me at " "kick boxing."}, {"full_name": "Edsger W. Dijkstra", "quote": "Computer Science is no more about computers than astronomy " "is about telescopes."}, {"full_name": "Bill Gates", "quote": "The computer was born to solve problems that did not exist before."}, {"full_name": "Norman Augustine", "quote": "Software is like entropy: It is difficult to grasp, weighs nothing, " "and obeys the Second Law of Thermodynamics; i.e., it always increases."}, {"full_name": "Nathan Myhrvold", "quote": "Software is a gas; it expands to fill its container."}, {"full_name": "Alan Bennett", "quote": "Standards are always out of date. That’s what makes them standards."} ] # https://stackoverflow.com/questions/55433855/how-to-combine-list-of-dictionaries-based-on-key for x in famous_quotes: print(f"\"{x['quote']}\" - {', '.join(reversed(x['full_name'].split()))}") # quote_names = [k['full_name'] for k in famous_quotes] # quote = [i['quote'] for i in famous_quotes] # print(f"\"{quote[0]}\" - {quote_names[0]} ") # print(f"\"{quote[1]}\" - {quote_names[1]} ") # print(f"\"{quote[2]}\" - {quote_names[2]} ") # print(f"\"{quote[3]}\" - {quote_names[3]} ") # print(f"\"{quote[4]}\" - {quote_names[4]} ") # print(f"\"{quote[5]}\" - {quote_names[5]} ") # print(f"\"{quote[6]}\" - {quote_names[6]} ")
true
4fd88f7c40fd99638e7b0ec03a4e353927d57f50
amandathedev/Python-Fundamentals
/03_more_datatypes/4_dictionaries/04_19_dict_tuples.py
471
4.40625
4
''' Write a script that sorts a dictionary into a list of tuples based on values. For example: input_dict = {"item1": 5, "item2": 6, "item3": 1} result_list = [("item3", 1), ("item1", 5), ("item2", 6)] ''' # http://thomas-cokelaer.info/blog/2017/12/how-to-sort-a-dictionary-by-values-in-python/ import operator input_dict = {"item1": 5, "item2": 6, "item3": 1} print(input_dict) result_list = sorted(input_dict.items(), key=operator.itemgetter(1)) print(result_list)
true
3cad7c59eb9cb4fe0e7ee41c01abe41b51c11669
danielzengqx/Python-practise
/1 min/binary search.py
708
4.125
4
#Binary search -> only for the sorted array #time complexity -> O(logn) array = [1, 2, 3, 4, 5] def BS(array, start, end, value): mid = (start + end) / 2 if start > end: print "None" return if array[mid] == value: print mid return elif array[mid] > value: BST(array, start, mid-1, value) elif array[mid] < value: BST(array, mid+1, end, value) BS(array, 0, len(array)-1, 3) #Iteration method for the binary search def BS2(array, value): start = 0 end = len(array) - 1 while start <= end: mid = (start + end)/2 if array[mid] == value: return mid elif array[mid] > value: end = mid - 1 elif array[mid] < value: start = mid + 1 return None print BS2(array, 5)
true
7176d418d1a0dc3f60f8d419d73174ab0184f160
danielzengqx/Python-practise
/CC150 5th/CH9/9.1.py
866
4.15625
4
#a child is running up a staircase with n steps, and can hop either 1 step, 2 step, 3 step at a time #Implement a method to count how many possible ways the child can run up the stairs def stair(n, counter): if n == 0: counter[0] += 1 return if n < 1: return else: stair(n-1, counter) stair(n-2, counter) stair(n-3, counter) #every subproblem will return the result to the upper level problem #using the memorization method def staircase(n, list2): if n == 0: return 1 if n < 1: return 0 if list2[n] != 0: return list2[n] else: return staircase(n-1, list2) + staircase(n-2, list2) + staircase(n-3, list2) def main(): n = 6 list1 = [0] stair(n, list1) print list1 #checking the value list2 = [0]*(n+1) print staircase(n, list2) if __name__ == "__main__": main()
true
02a416d2aee37a0bfebd86a33ef35d98c3891e82
danielzengqx/Python-practise
/2016 interview/r practise/messaging.py
2,026
4.125
4
# 第一轮 # 给定一段英文消息,以及一个固定的长度,要求将消息分割成若干条,每条的最后加上页码如 (2/3),然后每条总长度不超过给定的固定长度。典型的应用场景就是短信发送长消息。 # 经过询问之后得到更多详细要求及假设: # (1)消息数量尽可能少,不必凑整句,可以在任意空格处分页; # (2)这个固定长度可能非法,比如某个词很长导致一条消息放不下,要判断并抛出异常; # (3) 假设空格分割,不会出现连着两个空格的情况。 #implementation step #First -> detect the white space, store a list of string #checking the max length, if length exceed the max, return error #Second -> create an empty list, iterate the loop and add the element in the list and add the number at the end def step(string): list1 = [] length = 0 for x in string.split(' '): item = x.strip() list1.append(item) length += len(item) maxlength = 16 #-> length total = length/maxlength if (length%maxlength) != 0: total += 1 newstring, list2 = "", [] i = 0 Pnum = 0 while i < len(list1)-1: #corner cases if len(list1[i]) > maxlength-3: print "eee" return False newstring = "" #temp and j are used to store the pre step's result while i < len(list1): temp = newstring newstring = newstring + list1[i] j = i i += 1 if len(newstring) > maxlength-3: break i = j Pnum+=1 list2.append(temp + str(Pnum) + "/" + str(total)) #used for adding the last string if list1[-1] not in list2[-1]: list2.append(list1[-1]+ str(Pnum+1) + "/" + str(total)) print list1 print list2 def main(): string = "ewewewewewewe rre www, wede yyyyeeeeeeee" step(string) if __name__ == "__main__": main()
false
fd9d02de7d3f099f5d4267804fe5c7a4b8ee4a69
danielzengqx/Python-practise
/CC150 5th/CH2/2.5 best solution.py
2,564
4.125
4
# Given a circular linked list, implement an algorithm which returns node at the beginning of the loop. # EXAMPLE # input: A -> B -> C -> D -> E -> C [the same C as earlier] # output: C # 1), assume we have two types of runners, first, slow runner(s1) and fast runner (s2). s1 increment by 1 and s2 increment by 2 # 2), s2 starts at kth position, which is bigger than 0, s1 starts at 0 position # 3), if s1 can catch up s2, then that means the path is circle # 4), s1 will be set at the starting node, s2 will be set at the previous meeting point class Node(object): def __init__(self, data): self.data = data self.nextNode = None self.traveled = 0 def printn(node): index = 0 while(node != None): print node.data node = node.nextNode index += 1 #reverse printing def printback(node): if node == None: return else: printback(node.nextNode) print node.data def get_number(node, a): index = 0 while(node != None): a.append(node.data) node = node.nextNode index += 1 def get_add(a, b): sum1 = 0 index1 = 0 sum2 = 0 index2 = 0 for i in a: sum1 += int(i) * pow(10, index1) index1 += 1 print sum1 for j in b: sum2 += int(j) * pow(10, index2) index2 += 1 return sum1 + sum2 def deleteNode(node): if node.nextNode == None or node == None: print "no way to do it" return else: node.data = node.nextNode.data node.nextNode = node.nextNode.nextNode return def circle(node): #init state faster = node.nextNode slower = node #iteration while faster != slower: if faster == None or slower == None: print "no circle" return elif faster.nextNode == None: print "no circle" return faster = faster.nextNode.nextNode slower = slower.nextNode # print faster.data, slower.data #find the starting position of the cycle slower = node faster = faster.nextNode while faster != slower: print "hehe" faster = faster.nextNode slower = slower.nextNode print faster.data #first linked list node = Node("0") node1 = Node("1") node2 = Node("2") node3 = Node("3") node4 = Node("4") node5 = Node("5") node.nextNode = node1 node1.nextNode = node2 node2.nextNode = node3 node3.nextNode = node4 node4.nextNode = node5 node5.nextNode = node1 circle(node) #cannot handle one circle case
true
b1e6b5ea5c807000c7c463917b25bcc09812385f
danielzengqx/Python-practise
/CC150 5th/CH5/5.2.py
781
4.125
4
#Given a (decimal - e.g. 0.72) number that is passed in as a string, print the 32 bits binary rep- resentation. If the number can not be represented accurately in binary, print “ERROR” # the number base 5th version, the number is between 0 to 1, the max number is 1 - 2^(-32) # 1), There are two types of binary representations, first binary cannot represent the double, second binary exceeds the limited of 32 bits def checking(): num = 0.375 #check the max value boundary if num > 1 - pow(2, -32): return "error" power = -1 bit = 0 #check 32 bits times = 0 while num != 0: num = num * 2 x = int(num) bit += pow(10, power) * x num = num - x power -= 1 print bit checking()
true
e3fa4d976c1d6c1b6decfa4c0d24962076d5f829
danielzengqx/Python-practise
/CC150 5th/CH5/5.8.py
1,589
4.21875
4
#1, screen is stored as a single array of bytes. #2, width of screen can be divided by 8 pixels or 1 byte #3, eight consecutive pixels to store in one byte #4, height of the screen can be derived from #---------the width of screen #---------the length of a single array #---------height = the length of a single array / the width of screen # -------- -------- --SSSSSS SSSSSSSS SSSSSSSS SSS----- => this is 6 bytes, 8 pixel in each byte # start byte is 3rd, end byte is 5th # this is only one line representation 6 bytes (width), totally bytes on the screen = 6 bytes (width) * height list1 = [0] * 18 def printline(): global list1 breaker = 0 for i in list1: if breaker == 6: print "\n" breaker = 0 print i, breaker += 1 def drawline(): global list1 width = 6 x1 = 2*8 + 2 x2 = 2*8 + 3 y = 2 #starting point of x1 start_offset = x1 % 8 start_full_byte = x1 / 8 if start_offset != 0: #set the starting point list1 [width * y + start_full_byte] = 1 start_full_byte += 1 #ending point of x2 end_offset = x2 % 8 end_full_byte = x2 / 8 if end_offset != 7: #set the starting point list1 [width * y + end_full_byte] = 1 end_full_byte -= 1 print start_full_byte, end_full_byte #set byte for that one line cor_x = start_full_byte while cor_x <= end_full_byte: list1 [width * y + cor_x] = 1 cor_x += 1 printline() drawline()
true
1cb1e67c83c2ed46f228e1deea7359f2c3974fc5
Makhanya/PythonMasterClass
/OOP2/specialMethods.py
2,056
4.5625
5
""" Special Methods 2.(Polymorphism) The same operation works for different kinds of objects How does the following work in Python 8 + 2 #10 "8" + "2" #82 The answer is "special method" Python classes have special(also known as "magic") methods, that are dunders(i.e double underscore-named). There are methods with special names that give instructions to python for how to deal with objects Special Methods Example What is happening in our example? 8 + 2 #10 "8" + "2" #82 The operator is shorthand for a special method called __add__() that gets called on the first operand If the first(left_ operand is an instance of int, __add__() does mathematical addition. If it's a string, it does string concatenation Special Methods Applied Therefore, you can declare special methods on your own classes to mimic the behavior of builtin objects, like so using __len__ class Human: def __init__(self, height): self.height = height #in inches def __len__(self): return self.height mk=Human(60) lan(mk) #60 String Representation The most common use-case for special methods is to make classes "look pretty" in strings By default, our classes look ugly: class Human: pass mk = Human() print(mk) #<__main__.Human at 0x1062b8309> String Representation Example The __repr__ method is one of several ways to provide a nicer string representation class Human: def __init__(self, name="somebody"): self.name = name def __repr__(self): return self.name dude = Human() print(dude) #"somebody" """
true
ef4ff8fd0f38d7aae7463c629e9b3775dcc671a5
Makhanya/PythonMasterClass
/TuplesSets/loopingTuple.py
392
4.53125
5
# Looping # We can use a for loop to iterate over a tuple just like a list! # names = ( # "Colt", "Blue", "Rusty", "Lassie" # ) # for name in names: # print(name) # months = ("January", "February", "March", "April", "May", "June", # "July", "August", "September", "October", "November", "December") # i = len(months)-1 # while i >= 0: # print(months[i]) # i -= 1
true
483a6e8f975974e3b754109e4b72b18c0783e1b6
Makhanya/PythonMasterClass
/TuplesSets/tuple.py
524
4.21875
4
# Tuples are commonly used for Unchanging data: months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") # Tuple can be used as keys in dictionaries locations = { (35.68995, 39.6917): "Tokyo Office", (40.7128, 74.0060): "New York Office", (37.7749, 122.4194): "San Francisco Office" } # Some dictionary method like .items() return tuples cat = {'name': 'biscuit', 'age': 0.5, 'favorite_toy': 'my chapstic'} print(cat.items())
true
27d974269a5d178efe810beddf8efc2a7db0f4c3
Makhanya/PythonMasterClass
/TuplesSets/Sets.py
1,399
4.625
5
# Sets # Sets are like formal mathematical sets # Sets do not have duplicate values # Elements in sets aren't ordered # You cannot access items in a set by index # Sets can be useful if you need to keep track of a collection of # elements, but don;t care about ordering, Keys or values and dulicate # # cities = ["Los Angeles", "Boulder", "Kyoto", "Florence", "Santiago", # "Los Angeles", "Shanghai", "Boulder", "San Francisco", "Oslo", "Tokyo"] # print(len(set(cities))) # print(set(cities)) # Add # Adds an element to a set. If the element is already in the set, the set does'nt change # s = set([1, 2, 3, 6, 7, 8]) # s.add(5) # print(s) # s.add(4) # print(s) # Remove # removes a value from the set - returns a KeyError if the value is not found # s.remove(3) # print(s) # # Set Math # Sets have quite a few other mathematics methods # including # Intersection # symmetric_difference # union # Suppose I teach two classes: math_students = {"Matthew", "Helen", "Prashant", "James", "Aparna"} biology_students = {"Jane", "Matthew", "Charlotte", "Mesut", "Oliver", "James"} # To generate a set with all unique students print(math_students | biology_students) # To generate a set with students who are in both courses print(math_students & biology_students)
true
533a4e9756f3090eab131ff9e12277d2dfca9d09
Makhanya/PythonMasterClass
/Lambdas/minAndmax.py
1,212
4.25
4
""" Max Return the largest item in a iterable or the largest of two or more arguments # max (strings, dicts with same keys) print(max([3, 4, 1, 2])) # 4 print(max([1, 2, 3, 4])) # 4 print(max(["awesome"])) # w print(max({1: 'a', 3: 'c', 2: 'b'})) # 3 """ # nums = [40, 32, 6, 5, 10] # print(nums) # print(f"The maximum number in nums {max(nums)}") # print(f"The minimum number in nums {min(nums)}") # print(f"max in 'Hello World' - {max('hello wordl')}") # print(f"min in 'Hello World' - {min('Hello World')}") # names = ['Arya', 'Samson', 'Dora', 'Tim', 'Ollivander'] # print(names) # print(f"Min in names - {min(names)}") # print(f"Max in names - {max(names)}") # print(min(len(name)for name in names)) # print([len(name) for name in names]) # print(max(names, key=lambda n: len(n))) # print(min(names, key=lambda n: len(n))) songs = [ {"title": "happy birthday", "playcount": 1}, {"title": "Survive", "playcount": 6}, {"title": "YMCA", "playcount": 99}, {"title": "Toxic", "playcount": 31} ] #print(max(songs, key=lambda s: s['playcount'])) print(max(songs, key=lambda s: s['playcount'])['title'])
false
91d5ed77a512286ff516c5967b07a6c71f8e0cff
Pernillo918/CursoPython
/ht1.py
1,241
4.59375
5
''' Ejercicio1 Escribir un programa que pida al usuario un número entero y muestre por pantalla un triángulo rectángulo como el de más abajo, de altura el número introducido. Ejemplo El usuario ingresa el numero 5 * ** *** **** ***** ''' print("") print("Bienvendio al programa, este es el Ejercicio 1") print("") numero = int(input("Digite un numero:")) if (numero >=0): for i in range(numero): for j in range(i+1): print("*", end="") print() else: print("El numero ingresado no es un numero entero positivo") ''' Ejercicio2 Escribir un programa que pida al usuario un número entero y muestre por pantalla si es un número primo o no. ''' print("") print("Bienvendio al programa, este es el Ejercicio2") print("") numero = int(input("Digite un numero:")) validacion=0 if numero>1: for i in range(2, numero): calculo= numero calculo=calculo%i if calculo==0: validacion+=1 if validacion== 0: print("El numero "+str(numero)+" es primo") else: print("El numero " +str(numero) + " no es primo") else: print("El numero digitado no es entero positivo")
false
27ab1bab32d6bdc3f021bf7ca29e7d2821c32dac
fgokdata/exercises-python
/coursera/functions.py
515
4.125
4
def printAll(*args): # All the arguments are 'packed' into args which can be treated like a tuple print("No of arguments:", len(args)) for argument in args: print(argument) #printAll with 3 arguments printAll('Horsefeather','Adonis','Bone') #printAll with 4 arguments printAll('Sidecar','Long Island','Mudslide','Carriage') ############## def printDictionary(**args): for key in args: print(key + " : " + args[key]) printDictionary(Country='Canada',Province='Ontario',City='Toronto')
true
983437a9e05194097f02d0f154dc8e9a5419d7d6
Puqiyuan/Example-of-Programming-Python-Book
/chapter1/person_alternative.py
1,357
4.34375
4
""" a complete instance example of OOP in python. test result: pqy@sda1:~/.../chapter1$ python person_start.py Bob Smith 40000 Smith 44000.0 """ class Person: """ a general person: data + logic """ def __init__(self, name, age, pay = 0, job = None): self.name = name self.age = age self.pay = pay self.job = job def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay *= (1.0 + percent) def __str__(self): return ('<%s => %s: %s, %s>' % (slef.__class__.__name__, self.name, self.job, self.pay)) class Manager(Person): """ a person with custom raise inherits general last name """ def __init__(self, name, age, pay): Person.__init__(self, name, age, pay, 'manager') def giveRaise(self, percent, bonus = 0.1): Person.giveRaise(self, percent + bonus) """by call back avoid redundancy""" if __name__ == '__main__': bob = Person('Bob Smith',44) sue = Person('Sue Jones', 47, 40000, 'hardware') tom = Manager(name = 'Tom Doe', age = 50, pay = 50000) print(sue, sue.pay, sue.lastName()) for obj in (bob, sue, tom): obj.giveRaise(.10) print(obj)
true
291cabb8919366b24c0ff339d2897ae55ba3c386
vivianakinyi/Coding-Interviews-Prep
/kth_largest.py
887
4.34375
4
# Find kth largest elements in an unsorted array def kth_largest(arr, k): print "In kth largest" mergeSort(arr) # Split the array to kth item print arr[:k] # for i in range(k): # print arr[i] # Descending order i.e from largest to smallest def mergeSort(arr): if len(arr) > 1: mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] mergeSort(left) mergeSort(right) i = j = k = 0 while i < len(left) and j <len(right): if left[i] > right[j]: # Store the largest value first arr[k] = left[i] i += 1 else: arr[k] = right[j] j = j + 1 k = k + 1 # Check if more values are left on the lefthalf while i < len(left): arr[k] = left[i] i += 1 k += 1 # Check if more values are left on the righthalf while j < len(right): arr[k] = right[j] j += 1 k += 1 arr = [1,23,12,9,30,2,50] kth_largest(arr, 3)
false
da1d96284276b485582823b463700d9956e01725
KahlilMonteiro-lpsr/class-samples
/6-3CaesarsCipher/applyCipher.py
1,349
4.34375
4
# applyCipher.py # A program to encrypt/decrypt user text # using Caesars Cipher # # Author: rc.monteiro.kahlil [at] leadps.org import string # makes a mapping of alphabet to decoded alphabet # arguments: key # returns: dictionary of mapped letters def createDictionary(key): alphabet = list(string.ascii_lowercase) alphabet1 = {} num = 0 for n in alphabet: alphabet1[n] = (alphabet[(key + num) % 26]) num += 1 return alphabet1 # receive: user's encrypted message # arguments: none # return: encoded messge def getMessage(message): return message # for each letter in the message, decodes and record # arguments:encoded message, dictionary # returns decoded message def decodedMessage(message, dictionary): code = '' for m in message: newCode = dictionary[m] code = code + newCode return code # outputs the message to the terminal # arguments: decoded message # returns: none def printMessage(decodemessage): print(decodemessage) # execution starts here # ask user for key print("What key would you like to use decode?(1-25)") key = int(raw_input()) print("What message would you like to decode?") message = raw_input() print("Here's the decoding of your message:") dictionary = createDictionary(key) encodeMessage = getMessage(message) decodeMessage = decodedMessage(encodeMessage, dictionary) printMessage(decodeMessage)
true
90b8498a0612e66df9743ed07a3521a145c8d918
bhayru01/Python-Exercises
/addFloatNumbers.py
1,723
4.5
4
####### File Exercise from the book "Python For Everyone" by Horstmann ####### """ Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user a second chance to enter the value. After two chances, quit reading input. Add all correctly specified values and print the sum when the user is done entering data. Use exception handling to detect improper inputs. """ ## The Function checks wheter n is float or not # @param n, element to check # @return, returns True Or False # def is_float(n): try: float(n) return True except ValueError: return False ## The Function asks to enter floats and returns it, if it is not - raises an ValueError # @return, returns a floating point number # def enterFloats(): number = input("Enter a Float: ") # Checking the number with is_float function if is_float(number): number = float(number) return number else: raise ValueError("Error: Digits only !") def main(): #counting the wrong entered values mistakes = 0 #limiting the wrong entered values limit = 2 #summing the total entered float numbers total = 0 #when wrong entered values is less than limited wrong values while mistakes < limit: #handling exceptions try: digit = enterFloats() # summing float values total += digit except ValueError as exception: print(str(exception)) #when value is not float increasing mistakes by one mistakes += 1 #printing total sum after has been entered two wrong values print(total) main()
true
f31b5a47fd89394ef9725443e3aa463b79bc9c50
bhayru01/Python-Exercises
/NumberOfCharsWordsLines.py
1,537
4.3125
4
####### File Exercise from the book "Python For Everyone" by Horstmann ####### """ p7.5 Write a program that asks the user for a file name and prints the number of: characters, words, and lines in that file. """ file = open("input.txt", "w") file.write("Mary had a little lamb\nWhose fleece was white as snow.\nAnd everywhere that Mary went,\nThe lamb was sure to go!") file.close() #I AM ASSUMING CHARACHTERS ONLY LETTERS # TIME COMPLEXITY O(N) def countCharacters(file): numberOfChars = 0 char = file.read(1) while char != "": char = char.strip(".,?!") if char.isalpha(): numberOfChars += 1 char = file.read(1) return numberOfChars # TIME COMPLEXITY O(N) def countWords(file): numberOfWords = 0 letter = file.read(1) word ="" while letter != "": letter = letter.strip(".,?!") word += letter if not letter.isalpha(): numberOfWords += 1 letter = file.read(1) return numberOfWords def countLines(file): countLines = 0 for line in file: countLines += 1 return countLines def main(): userInput = input("Enter file name: ") openFile = open(userInput, "r") print("Number Of Characters: ", countCharacters(openFile)) openFile.close() openFile = open(userInput, "r") print("Number Of Words: ", countWords(openFile)) openFile.close() openFile = open(userInput, "r") print("Number Of Lines: ", countLines(openFile)) openFile.close() main()
true
b5060a2f70653672895b2225e76c2bf1ddc2e573
cervthecoder/scratch_code
/begginning_cerv/user input.py
243
4.28125
4
name = input("Enter your name: ") #user put here some infromation which is stored inside a variable age = input ("enter your age: ") print("Hello " +name+ "! Your age is "+age+".") #prints the variables plus some other information (string)
true
15e424f10556b081b77b9033d89abdc0051f60af
cervthecoder/scratch_code
/begginning_cerv/if statement.py
307
4.21875
4
is_male = False #make a true/false value is_tall = False if is_male and is_tall: print("You're a male and tall") elif is_male and not(is_tall): print("You're a short male") elif not (is_male) and is_tall: print("You're a tall female") else: print("You're a female and not tall")
true
3e82cdc424ff7701097af941d10ff294173fce1f
elducati/bootcampcohort19
/fizz_buzz.py
397
4.1875
4
def fizz_buzz(num): #checks if number is divisible by 3 and 5 if num % 3 == 0 and num % 5 == 0: return 'FizzBuzz' #checks if number if number is divisible by 5 elif num % 5 == 0: return 'Buzz' #checks if number is divisible by 3 elif num % 3 == 0: return 'Fizz' #returns number if not divisible by either 3 or 5 else: return num
false
9e15be4deb11a9e2810d5fb3bd9beb7769a2d345
rrdietsch/Python-Classes
/hello world.py
847
4.25
4
######################################### # Aprendiendo python # by: el dicky ######################################### #test import os os.system('cls') ''' first_name = "Ricardo" #print(first_name) first_name = "michelle" print(first_name) ''' #dictionary nombres = ["juan", "Luis", "Ricardo"] #tuple nombres = ("juan", "Luis", "Ricardo") #dictionaries nombre_edad = { "ricardo": "36", "Luis": "34", "Juan": "36", } ## escape word ej. /n <-new line ## you can only concantenate with strings ######################## # strings greeting = "que lo que" ''' gretting.upper() // mayuscula gretting.lower() // minuscula .swapcase() // invierte las mayuculas con minusculas .Title() //mayuscula cada palabra .Capitalize() //mayuscual primera palabra de oracion ''' print(greeting.split(" ")[1:3]) ##############################
false
3a11b81f210e012e7fce39a2d40387e8d2dd7dc3
CODavies/Python_Dietel
/Chapter2/Multiples_Of_A_Number.py
274
4.15625
4
first_Number = int(input('Enter first number: ')) second_Number = int(input('Enter second number: ')) if second_Number % first_Number == 0: print(first_Number, " is a multiple of ", second_Number) if second_Number % first_Number != 0: print("The are not multiples")
true
94d45fbfca9b0bebc195843f95e2c9328c08040d
lirui-ML/my_leetcode
/Algorithms/234_Palindrome_Linked_List/Palindrome_Linked_List.py
2,162
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 描述:回文链表 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1->2->2->1 输出: true 进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/palindrome-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: """普通版, O(n)时间复杂度 O(n)空间复杂度""" result = [] while head: result.append(head.val) head = head.next for i in range(len(result) // 2): if result[i] != result[len(result) - i - 1]: return False return True def isPalindrome2(self, head: ListNode) -> bool: """进阶版, O(n)时间复杂度 O(1)空间复杂度, 快慢双指针+反转链表""" # rev records the first half, need to set the same structure as fast, slow, hence later we have rev.next rev = None # initially slow and fast are the same, starting from head slow = fast = head while fast and fast.next: # fast traverses faster and moves to the end of the list if the length is odd fast = fast.next.next # take it as a tuple being assigned (rev, rev.next, slow) = (slow, rev, slow.next), hence the re-assignment of slow would not affect rev (rev = slow) rev, rev.next, slow = slow, rev, slow.next if fast: # fast is at the end, move slow one step further for comparison(cross middle one) slow = slow.next # compare the reversed first half with the second half while rev and rev.val == slow.val: slow = slow.next rev = rev.next # if equivalent then rev become None, return True; otherwise return False return not rev
false
cfdec71e99f0b3a80db0681d590e988193bbc783
HarshRangwala/Python
/python practice programs/GITpractice31.py
1,437
4.65625
5
# -*- coding: utf-8 -*- """ Created on Fri Jun 15 14:36:13 2018 @author: Harsh """ ''' Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. ''' def listing(): l = list() for i in range(1,21): l.append(i**2) print(l) ''' Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list. Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list ''' def listing1(): l = list() for i in range(1,21): l.append(i**2) print(l[:5]) print(l[-5:]) # '''Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). # Then the function needs to print the last 5 elements in the list.''' ''' Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list. ''' def listing2(): l = list() for i in range(1,21): l.append(i**2) print(l[5:])
true
b519c13d65845d3b859878a27608f8bdd1eda9e2
HarshRangwala/Python
/python prc/PRACTICAL1E.py
1,102
4.1875
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 5 18:26:47 2018 @author: Harsh """ def Armstrong(): num=int(input("Please Input here::")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") def pallindrome1(): num=int(input("Please Input here::")) sum1=0 n=num while num!=0: rem=num%10 sum1=(sum1*10)+rem num=num//10 if sum1==n: print(n,"is a palindrome") else: print(n,"is not a palindrome number") Options={ 0: Armstrong, 1: pallindrome1 } Selection = 0 while Selection != 2: print("0. Armstrong") print("1. Pallindrome1") Selection = int(input("Select an option: ")) if (Selection >= 0) and (Selection < 2): Options[Selection]()
true
d573c3a0f4641b652c6a421630ae6273c2520683
HarshRangwala/Python
/python practice programs/GITpractice16.py
431
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 9 23:30:39 2018 @author: Harsh """ ''' Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,3,5,7,9 ''' v = input("Please input here::\n\n") num = [x for x in v.split(",") if int(x)%2!=0] print(",".join(num))
true
27d7b880c1caf75afd0896a6d1ef6dac88659a5f
NareTorosyan/Python_Introduction_to_Data_Science
/src/first_month/Homeworks/task_1_2_1_lists.py
440
4.34375
4
#1 Write a Python program to get the largest number from a list. x = [9,8,5,6,4,3,2,1] x.sort() print(x[-1]) #2 Write a Python program to get the frequency of the given element in a list to. x =[1,2,3,4,5,6,7,8,9,9,9,9,9] print(x.count(9)) #3 Write a Python program to remove the second element from a given list, if we know that the first elements index with that value is n. x= [1,2,3,4,3,5,2] n=1 x.sort() x.pop(n+1) print(x)
true
c0f5fc4c97b304d5f862491ee2bd91e6b7a4ecdb
tuantvk/python-cheatsheet
/src/python-example/set.py
1,182
4.15625
4
#!/usr/bin/python # set set1 = {"Weimann", "Dickens", "Lakin"} print(set1) # output: # {'Weimann', 'Lakin', 'Dickens'} # check if "Weimann" is present in the set set2 = {"Weimann", "Dickens", "Lakin"} print("Weimann" in set2) # output: # True # add set3 = {"Weimann", "Dickens", "Lakin"} set3.add("Schneider") print(set3) # output: # {'Lakin', 'Dickens', 'Schneider', 'Weimann'} # add multiple items to a set set4 = {"Weimann", "Dickens", "Lakin"} set4.update(["Schneider", "Kshlerin", "Pfannerstill"]) print(set4) # output: # {'Dickens', 'Kshlerin', 'Schneider', 'Weimann', 'Lakin', 'Pfannerstill'} # get the length of a set set5 = {"Weimann", "Dickens", "Lakin"} print(len(set5)) # output: # 3 # remove set6 = {"Weimann", "Dickens", "Lakin"} set6.remove("Dickens") print(set6) # output: # {'Lakin', 'Weimann'} # clear set7 = {"Weimann", "Dickens", "Lakin"} set7.clear() print(set7) # output # set() # del set8 = {"Weimann", "Dickens", "Lakin"} del set8 try: print(set8) except: print("Not found") # output: # Not found # set constructor set9 = set(("Weimann", "Dickens", "Lakin")) print(set9) # output: # {'Weimann', 'Dickens', 'Lakin'}
false
9dd831fc2689ea4f88ccabfcfc1625872360131e
tuantvk/python-cheatsheet
/src/python-example/string.py
1,350
4.4375
4
#!/usr/bin/python str1 = 'Hello World!' str2 = "I love Python" print("str1[0]: ", str1[0]) print("str2[7:]: ", str2[7:]) # output: # str1[0]: H # str2[7:]: Python # display multiline str3 = """ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s """ print("multiline", str3) # output: # Lorem Ipsum is simply dummy text of the printing # and typesetting industry. Lorem Ipsum has been the # industry's standard dummy text ever since the 1500s # the len() method return the length of a string str4 = "Example for length" print("length", len(str4)) # output: # length 18 # string in upper case or lower case str5 = "I Love Python" print("upper", str5.upper()) print("lower", str5.lower()) # output: # upper I LOVE PYTHON # lower i love python # replace str6 = "I Love Python" print(str6.replace("o", "0")) # output: # I L0ve Pyth0n # split str7 = "I Love Python" print(str7.split(" ")) # output: # ['I', 'Love', 'Python'] # format quantity = 3 price = 10 my_order = "I want {} item for {} dollars" print(my_order.format(quantity, price)) # output: # I want 3 item for 10 dollars # strip, removes any whitespace from the beginning or the end str8 = " I Love Python " print(str8.strip()) # output: # I Love Python
true
ad987950a320d893b0b71089f95bdabe34176a87
skywalker-young/LeetCode-creepy
/unique-path.py
1,666
4.25
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Note: m and n will be at most 100. """ class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ table = [[0 for x in range(n)] for x in range(m)] for i in range(m): table[i][0] = 1 for i in range(n): table[0][i] = 1 for i in range(1,m): for j in range(1,n): table[i][j] = table[i-1][j] + table[i][j-1] return table[m-1][n-1] """ Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. For example, [ [0,0,0], [0,1,0], [0,0,0] ] """ class Solution: def uniquePathsWithObstacles(self, obstacleGrid): if not obstacleGrid: return r, c = len(obstacleGrid), len(obstacleGrid[0]) dp = [[0 for _ in range(c)] for _ in range(r)] dp[0][0] = 1 - obstacleGrid[0][0] for i in range(1, r): dp[i][0] = dp[i-1][0] * (1 - obstacleGrid[i][0]) for i in range(1, c): dp[0][i] = dp[0][i-1] * (1 - obstacleGrid[0][i]) for i in range(1, r): for j in range(1, c): dp[i][j] = (dp[i][j-1] + dp[i-1][j]) * (1 - obstacleGrid[i][j]) return dp[-1][-1]
true
16c43c5c88baeaf413f7a3ba03f07a2767d29988
KrisZ1234/Python_various
/quadratic.py
1,484
4.125
4
import math print("------ a*x**2 + b*x + c = 0 ------- ") inp1_str = input("Type a -> ") inp2_str = input("Type b -> ") inp3_str = input("Type c -> ") def solutions(a,b,c): """ inputs: 3 float numbers Does the proper calculations (for ALL scenarios) and prints the solutions """ D = (b**2) - (4*a*c) if D > 0: if a == 0 and b != 0 and c == 0: print('Solution: x=',0) elif a == 0 and b != 0 and c != 0: print("Solution: x=",-c/b) else: x1 = (-b + math.sqrt(D)) / (2*a) x2 = (-b - math.sqrt(D)) / (2*a) print("Solutions: x1=",x1) print(" x2=",x2) elif D == 0: if a == 0 and b == 0 and c != 0: print("Incorrect equation,",c,"= 0") elif a != 0 and b == 0 and c == 0: print('Solution: x=',0) elif a == 0 and b == 0 and c == 0: print("Infinite solutions") else: x = -b / (2*a) print("Solution: x=",x) else: print("No real Solutions") """ check if the inputs are correct and procedes to the solution """ if inp1_str and inp2_str and inp3_str: try: inp1 = float(inp1_str) inp2 = float(inp2_str) inp3 = float(inp3_str) solutions(inp1,inp2,inp3) except: print() print ("Incorrect inputs!!") else: print("Not enough inputs!!")
false
18e0e1c83373e8fe96430fbb141330e06c143f1b
AishwaryaVelumani/Hacktober2020-1
/rock paper scissors.py
1,668
4.25
4
import random def result(your_score,comp_score): if your_score>comp_score: print("Congratulations! You won the match. Play again!") elif your_score == comp_score: print("The match is a tie! Play again!") else : print("Opps! You lost the match. Try again!") def win(your_score): print("Yay! You won.") your_score+=1 return(your_score) def lose(comp_score): print("Oops! You loose.") comp_score+=1 return(comp_score) rule= { 1: 'Rock', 2: 'Paper', 3: 'Scissors' } name= input("Hello there! What's your name? ") print(f'Welcome to the game {name}!') your_score=0 comp_score=0 for i in range(0,3): choice= int(input("Choose your play: 1-Rock, 2-Paper, 3-Scissors ")) computer= random.randint(1, 3) if choice == 1 or 2 or 3: print(f'You choose {rule[choice]}') else: print("Please enter a valid number.") print(f'Computer choose {rule[computer]}') if computer==1 : if choice==2: win(your_score) elif choice==3: lose(comp_score) else : print("It's a tie!") elif computer==2: if choice==3: win(your_score) elif choice==1: lose(comp_score) else : print("It's a tie!") else : if choice==1: win(your_score) elif choice==2: lose(comp_score) else : print("It's a tie!") print(f''' Your score : {your_score} Computer's score: {comp_score}''') result(your_score,comp_score)
true
0a32ce525ca251902664bd79f3eef7d295a4a747
Soleviso/pythonProject1
/calculator.py
283
4.125
4
x = int(input("Eingabe Zahl x: ")) y = int(input("Eingabe Zahl y: ")) operation = input("Rechenaufgabe (+, -, /, *): ") if operation == "+": print(x + y) if operation == "-": print(x - y) if operation == "/": print(x / y) if operation == "*": print(x * y)
false
733464c49bc5ee51d3e2a4cc29f29f3a1db9171d
carlosalf9/InvestigacionPatrones
/patron adapter python/class Adapter.py
544
4.1875
4
class Adapter: """ Adapts an object by replacing methods. Usage: motorCycle = MotorCycle() motorCycle = Adapter(motorCycle, wheels = motorCycle.TwoWheeler) """ def __init__(self, obj, **adapted_methods): """We set the adapted methods in the object's dict""" self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr): """All non-adapted calls are passed to the object""" return getattr(self.obj, attr) def original_dict(self): """Print original object dict""" return self.obj.__dict__
true
e029b1def2a907109eeaf9cb9434edec6eb40ddc
naistangz/codewars_challenges
/7kyu/shortestWord.py
332
4.5625
5
""" Instructions - Simple, given a string of words, return the length of the shortest word(s). - String will never be empty and you do not need to account for different data types. """ def find_short(s): convert_to_list = list(s.split(" ")) shortest_word = min(len(word) for word in convert_to_list) return shortest_word
true
fd90a725870c45b4a1c848893ad1dbf394ec5240
naistangz/codewars_challenges
/7kyu/simpleConsecutivePairs.py
1,639
4.28125
4
""" Instructions In this Kata your task will be to return the count of pairs that have consecutive numbers as follows: pairs([1,2,5,8,-4,-3,7,6,5]) = 3 The pairs are selected as follows [(1,2),(5,8),(-4,-3),(7,6),5] --the first pair is (1,2) and the numbers in the pair are consecutive; Count = 1 --the second pair is (5,8) and are not consecutive --the third pair is (-4,-3), consecutive. Count = 2 --the fourth pair is (7,6), also consecutive. Count = 3. --the last digit has no pair, so we ignore. """ # 1st Iter # def pairs(arr): # count = 0 # # iterating through list # for i in range(len(arr)-1): # # checking if next number is consecutive # if arr[i] + 1 == arr[i+1]: # count += 1 # return count # # 2nd Iter # def pairs(arr): # count = 0 # if len(arr) % 2 != 0: # arr.pop() # return arr # returns [1, 2, 5, 8, -4, -3, 7, 6] # for i in arr[:-1:]: # if arr[i] + 1 == arr[i+1]: # count += 1 # return count # Unfinished # 3rd Iter def pairs(arr): print(f"Original List: {arr}") resulting = [] for i in range(len(arr)-1): resulting.append([arr[i], arr[i + 1]]) print(f"Paired element list: {str(resulting)}") # sample_arr = [1,2,5,8,-4,-3,7,6,5] # indexing = sample_arr[:-1:] # returns [1, 2, 5, 8, -4, -3, 7, 6] # print(indexing) # def pairs(arr): # listing = [] # for i in arr: # listing.append(i) # return listing # Returns # [1, 2, 5, 8, -4, -3, 7, 6, 5] # [-55, -56, -7, -6, 56, 55, 63, 62] print(pairs([1,2,5,8,-4,-3,7,6,5])) # 3 print(pairs([-55, -56, -7, -6, 56, 55, 63, 62])) # 4
true
43a739e5ab9392456bde250693f404050234d895
hamiltoz9192/CTI-110
/P4HW2_Hamilton.py
340
4.125
4
#CTI-110 #P4HW2 - Running Total #Zachary Hamilton #July 6, 2018 #This program creates a running total ending when a negative number is entered. total = 0 userNumber = float(input("Enter a number?:")) while userNumber > -1: total = total + userNumber userNumber = float(input("Enter a number?:")) print() print("Total:",total)
true
435b5497d7968cc076d860e436f4d9b7f109e336
AShuayto/python_codewars
/data_reverse.py
1,043
4.1875
4
''' A stream of data is received and needs to be reversed. Each segment is 8 bits long, meaning the order of these segments need to be reversed, for example: 11111111 00000000 00001111 10101010 byte1 byte2 byte3 byte4 should become: 10101010 00001111 00000000 11111111 byte4 byte3 byte2 byte1 The total number of bits will always be a multiple of 8. The data is given in an array as such: [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0] ''' def data_reverse(data): flattened = [] a = [data[i:i+8] for i in range(0,len(data),8)] a.reverse() for array in a: for num in array: flattened.append(num) return flattened ''' data1 = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0] data2 = [1,0,1,0,1,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1] test.assert_equals(data_reverse(data1),data2) data3 = [0,0,1,1,0,1,1,0,0,0,1,0,1,0,0,1] data4 = [0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0] test.assert_equals(data_reverse(data3),data4) '''
true
3d22a01a1504c7c5240aeeccedbab2f4226517d2
tmajest/project-euler
/python/p9/p9_2.py
702
4.15625
4
# A Pythagorean triplet is a set of three natural numbers, a b c, for which, # a^2 + b^2 = c^2 # # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. import math def isPythagoreanTriplet(a, b): c = math.sqrt(a*a + b*b) return math.floor(c) == c # Get all pythagorean triplets for 1 < a < b < 1000 pTriplets = [(a, b, int(math.sqrt(a*a + b*b))) for a in range(1, 500) for b in range(a+1, 500) if isPythagoreanTriplet(a, b)] # Get triplet whose sum is 1000 a, b, c = next(pTriplet for pTriplet in pTriplets if sum(pTriplet) == 1000) print a * b * c
false
7ecb0c43bd717c3bd54369dca6fd2e6c0ec5d502
nastyav0411/coding-challenge
/recursive_element_calc.py
452
4.3125
4
def recursive_element_calc( n ): # recursive function calculates n_th element of the sequence if n == 1: return 2 elif n == 2: return 2 else: return recursive_element_calc( n - 1 ) + recursive_element_calc( n - 2 ) if __name__ == '__main__': n = 15 # number of element in the sequence to calculate nth_element = recursive_element_calc(n)
false
cdaffc0412348680b67122b1a959ab448a4809eb
Md-Monirul-Islam/Python-code
/Advance-python/Constructor with Super Method-2.py
531
4.21875
4
#Constructor with Super Method or Call Parent Class Constructor in Child Class in Python class Father: def __init__(self): self.money = 40000 print("Father class constructor.") def show(self): print("Father class instance method.") class Son(Father): def __init__(self): super().__init__() #calling parent class constructor print("Son class constructor.") def display(self): print("Son class instance method.",self.money) object = Son() object.display()
true
293a10483534470b8ab48647a6c29ea49ca647e0
Md-Monirul-Islam/Python-code
/Advance-python/Abstract Class Abstract Method and Concrete Method in Python-2.py
531
4.125
4
from abc import ABC,abstractmethod class DefenceForce: @abstractmethod def area(self): pass def gun(self): #concreate method. print("Gun->>AK47") class Army(DefenceForce): def area(self): print("Army area->>Land") class AirForce(DefenceForce): def area(self): print("AirForce area->>Sky") class Navy(DefenceForce): def area(self): print("Navy area->>Sea") a = Army() af = AirForce() n = Navy() a.area() a.gun() print() af.area() af.gun() print() n.area() n.gun()
false
49c90b63c2ad1b5a59b98e74b62c815f44a5bdff
ruiliulin/liuliu
/习题课/Python视频习题课/高级语法训练/习题课23 Tk练习/习题课23 Tk练习1.py
779
4.15625
4
# encoding:utf-8 # 用Tkinter写一个小游戏随机生成我们需要的名字 import tkinter as tk import random window = tk.Tk() def random1(): s1 = ["cats", "hippos", "cakes"] s = random.choice(s1) return s def random2(): s2 = ["eats", "has", "likes", "hates"] s = random.choice(s2) return s def button_click(): name = nameEntry.get() verb = random2() noun = random1() sentence = name + " " + verb + " " + noun result.delete(0, tk.END) result.insert(0, sentence) nameLabel = tk.Label(window, text="Name: ") nameEntry = tk.Entry(window) button = tk.Button(window, text="生成随机名称", command=button_click) result = tk.Entry(window) nameLabel.pack() nameEntry.pack() button.pack() result.pack() window.mainloop()
false
2c91529b8b53c07adb1466be2b673aaf921efa6a
lrakai/python-newcomer-problems
/src/challenge_three.py
893
4.5
4
def list_uniqueness(the_list): ''' Return a dictionary with two key-value pairs: 1. The key 'list_length' stores the lenght of the_list as its value. 2. The key 'unique_items' stores the number of unique items in the_list as its value. Arguments the_list: A list Examples l = [1, 2, 2, 4] dictionary = list_uniqueness(l) print(dictionary['list_length']) # prints 4 print(dictionary['unique_items']) # prints 3 ''' # ==================================== # Do not change the code before this # CODE1: Write code that will create the required dictionary # ==================================== # Do not change the code after this return dictionary if __name__ == '__main__': l = [1, 2, 2, 4] dictionary = list_uniqueness(l) print(dictionary['list_length']) print(dictionary['unique_items'])
true
02e9d39c87c4456b5f5b3cfd8ed53b98db430328
flik/python
/iterator.py
576
4.53125
5
#Return an iterator from a tuple, and print each value: mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) #myit = mytuple print(next(myit)) # next() will not work without iter() conversion. print(next(myit)) print(next(myit)) mystr = "banana" for x in mystr: print(x) """ #Strings are also iterable objects, containing a sequence of characters: mystr = "banana" myit = iter(mystr) x = 0 while x < len(mystr): print(next(myit)) x +=1 print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) print(next(myit)) """
true
f232098adaba4d48f648697aa53b81e4faed8af3
flik/python
/class.py
850
4.46875
4
class MyClass: x = 5 y = 9 p1 = MyClass() print(p1.y) #------- other example class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) #print(p1.name) #print(p1.age) # ---third example with self use class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) #p1.myfunc() # Use the words mysillyobject and abc instead of self: init first param is behave like self class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is- " + abc.name) p1 = Person("John", 36) p1.name = "saqi" #updatig name del p1.age # Delete the age property from the p1 object: p1.myfunc()
false
ade463aad6ee764d4627acc5927eb64d535135bc
ziminika/prak__5
/task2/5/5.py
2,790
4.1875
4
from collections import defaultdict import sys # Description of class Graph: # The Graph is a dictionary of dictionaries. # The keys are nodes, and the values are dictionaries, # whose keys are the vertices that are associated with # a given node, and whose values are the weight of the edges. # Non-oriented Graph class Graph: # Сreating a Graph object def __init__(self): self.nodes = defaultdict(defaultdict) # Adding a new node to the graph def add_node(self, value): if value not in self.nodes: self.nodes[value] = {} # Adding vertices and edges def add_edge_and_weight(self, nodeStart, nodeEnd, weight): if nodeEnd not in self.nodes: self.add_node(nodeEnd) if nodeStart not in self.nodes: self.add_node(nodeStart) self.nodes[nodeStart][nodeEnd] = weight self.nodes[nodeEnd][nodeStart] = weight # Output an object of type Graph def __str__(self): output = "" for i in self.nodes: output += str(i) + " -> " + str(self.nodes[i]) + '\n' return output[0:-1] # Function to find the shortest path between nodes # nodeStart and nodeEnd. Dijkstra's algorithm is used. def short_way(self, nodeStart, nodeEnd): if nodeStart not in self.nodes: return "Error: nodeStart not in graph" if nodeEnd not in self.nodes: return "Error: nodeEnd not in graph" Inf = 0 for i in self.nodes: Inf += sum(self.nodes[i].values()) dist = {} # storing distances between the nodeStart and other is_min_dist = {} # bool type storage. "True" corresponds to the shortest distance already found path = {} # storing the path from nodeStart for i in self.nodes: dist[i] = Inf is_min_dist[i] = False dist[nodeStart] = 0 path[nodeStart] = [] node = nodeStart while is_min_dist[nodeEnd] != True: is_not_visited = True min_way = Inf for i in self.nodes[node]: is_not_visited = is_not_visited and is_min_dist[i] if not is_min_dist[i]: if dist[i] >= dist[node] + self.nodes[node][i]: dist[i] = dist[node] + self.nodes[node][i] path[i] = path[node].copy() path[i].append(node) is_min_dist[node] = True for i in dist: if is_min_dist[i] == False and min_way >= dist[i]: next_node = i min_way = dist[i] if is_not_visited == True and is_min_dist[nodeEnd] != True and node == nodeStart: return "Path doesn't exist" node = next_node path[nodeEnd].append(nodeEnd) return path[nodeEnd] G = Graph() end = 0 while end == 0: str1 = sys.stdin.readline() if str1 != "\n": node1 = str1[0:-1].split()[0] node2 = str1[0:-1].split()[1] weight = int(str1[0:-1].split()[2]) G.add_edge_and_weight(node1,node2, weight) else: end = 1 print("Selected nodeStart:") nodeStart = input() print("Selected nodeEnd:") nodeEnd = input() print(G.short_way(nodeStart, nodeEnd))
true
c8537ec4db97f54f6eab90aa26b3b0f03a79b3d2
ziminika/prak__5
/task2/4/4.py
2,361
4.125
4
from collections import defaultdict from collections import deque import sys # Description of class Graph: # The Graph is a dictionary of lists. # The keys are nodes, and the values are lists, # consisting of nodes that have a path fron a given node. # Oriented Graph class Graph: # Сreating a Graph object def __init__(self): self.nodes = defaultdict(list) # Adding a new node to the graph def add_node(self, value): if value not in self.nodes: self.nodes[value] = [] # Adding vertices and line def add_line(self, node_start, node_end): if node_end not in self.nodes: self.add_node(node_end) if node_start not in self.nodes: self.add_node(node_start) self.nodes[node_start].append(node_end) # Output an object of type Graph def __str__(self): output = "" for i in self.nodes: output += str(i) + " -> " + str(self.nodes[i]) + '\n' return output[0:-1] # Implementation of dfs algorithm def dfs(self, node): if node not in self.nodes: print("Error: node not in graph") return visited = [] # list of visited nodes self.dfs_rec(node, visited) # recursive algorithm not_visited = list(set(self.nodes) - set(visited)) # if there are unvisited nodes while not_visited: self.dfs_rec(not_visited[0], visited) not_visited = list(set(self.nodes) - set(visited)) # Recursive algorithm (need for dfs function) def dfs_rec(self, node, visited): if node not in visited: visited.append(node) print(node) for i in self.nodes[node]: if i not in visited: self.dfs_rec(i, visited) # Implementation of bfs algorithm def bfs(self, node): if node not in self.nodes: print("Error: node not in graph") return visited = [] # list of visited nodes q = deque() # the deque of nodes (used as a queue) q.append(node) while q: node = q.popleft() if node not in visited: visited.append(node) for i in self.nodes[node]: q.append(i) print(node) G = Graph() end = 0 while end == 0: str1 = sys.stdin.readline() if str1 != "\n": node1 = str1[0:-1].split()[0] node2 = str1[0:-1].split()[1] G.add_line(node1,node2) else: end = 1 print("Selected node:") node = input() print("Choose a method:\n1 - BFS\n2 - DFS") method = int(input()) if method != 1: if method != 2: print("Error: incorrect method") pass else: G.dfs(node) else: G.bfs(node)
true
e34199254a7fea1aea5f3e02310652c367f1897c
YaoJMa/CS362-HW3
/Yao_Ma_HW3_Leap_Year.py
483
4.28125
4
#Asks user for a input for what year year = int(input("Enter a year: ")) #Checks the conditions if the year is divisible by 400 if year%400==0: print("It is a leap year") #Checks the conditions if the year is divisible by 100 and 400 elif year%100==0 and year%400!=0: print("It is not a leap year") #Checks the condition if the year is divisible by 4 and 100 elif year%4==0 and year%100!=0: print("It is a leap year") else: print("It is not a leap year")
true
26602c6aeda22ee4cd53bb346f9c96604200ef73
vitthalpadwal/Python_Program
/hackerrank/preparation_kit/greedy_algorithms/max_min.py
1,761
4.28125
4
""" You will be given a list of integers, , and a single integer . You must create an array of length from elements of such that its unfairness is minimized. Call that array . Unfairness of an array is calculated as Where: - max denotes the largest integer in - min denotes the smallest integer in As an example, consider the array with a of . Pick any two elements, test . Testing for all pairs, the solution provides the minimum unfairness. Note: Integers in may not be unique. Function Description Complete the maxMin function in the editor below. It must return an integer that denotes the minimum possible value of unfairness. maxMin has the following parameter(s): k: an integer, the number of elements in the array to create arr: an array of integers . Input Format The first line contains an integer , the number of elements in array . The second line contains an integer . Each of the next lines contains an integer where . Constraints Output Format An integer that denotes the minimum possible value of unfairness. Sample Input 0 7 3 10 100 300 200 1000 20 30 Sample Output 0 20 Explanation 0 Here ; selecting the integers , unfairness equals max(10,20,30) - min(10,20,30) = 30 - 10 = 20 Sample Input 1 10 4 1 2 3 4 10 20 30 40 100 200 Sample Output 1 3 Explanation 1 Here ; selecting the integers , unfairness equals max(1,2,3,4) - min(1,2,3,4) = 4 - 1 = 3 Sample Input 2 5 2 1 2 1 2 1 Sample Output 2 0 Explanation 2 Here . or give the minimum unfairness of . """ import collections, sys if __name__ == '__main__': N = int(sys.stdin.readline()) K = int(sys.stdin.readline()) x = sorted(int(sys.stdin.readline()) for _ in range(N)) print(min(x[i + K - 1] - x[i] for i in range(0, N - K - 1)))
true
ab76daedef7fc55f293b31010b84f62472d2e028
vitthalpadwal/Python_Program
/hackerrank/algorithm/strings/super_reduces_strings.py
1,456
4.34375
4
""" Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations. In each operation he selects a pair of adjacent lowercase letters that match, and he deletes them. For instance, the string aab could be shortened to b in one operation. Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print Empty String Function Description Complete the superReducedString function in the editor below. It should return the super reduced string or Empty String if the final string is empty. superReducedString has the following parameter(s): s: a string to reduce Input Format A single string, . Constraints Output Format If the final string is empty, print Empty String; otherwise, print the final non-reducible string. Sample Input 0 aaabccddd Sample Output 0 abd Explanation 0 Steve performs the following sequence of operations to get the final string: aaabccddd → abccddd → abddd → abd Sample Input 1 aa Sample Output 1 Empty String Explanation 1 aa → Empty String Sample Input 2 baab Sample Output 2 Empty String Explanation 2 baab → bb → Empty String """ s = input() while True: for i in range(len(s)-1): if s[i] == s[i+1]: s = s[:i]+s[i+2:] break else: break print(s if s else "Empty String")
true
c5606deae4b3f8ac7e867c48c2d00c71317d78ab
vitthalpadwal/Python_Program
/hackerrank/decorator_standardize_mobile_no.py
1,332
4.65625
5
""" Let's dive into decorators! You are given mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx The given mobile numbers may have , or written before the actual digit number. Alternatively, there may not be any prefix at all. Input Format The first line of input contains an integer , the number of mobile phone numbers. lines follow each containing a mobile number. Output Format Print mobile numbers on separate lines in the required format. Sample Input 3 07895462130 919875641230 9195969878 Sample Output +91 78954 62130 +91 91959 69878 +91 98756 41230 Concept Like most other programming languages, Python has the concept of closures. Extending these closures gives us decorators, which are an invaluable asset. You can learn about decorators in 12 easy steps here. To solve the above question, make a list of the mobile numbers and pass it to a function that sorts the array in ascending order. Make a decorator that standardizes the mobile numbers and apply it to the function. """ def wrapper(f): def fun(l): f(['+91 ' + c[-10:-5] + ' ' + c[-5:] for c in l]) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l = [input() for _ in range(int(input()))] sort_phone(l)
true
268afaf374055a83b932122edd77f75d2b8abb14
vitthalpadwal/Python_Program
/hackerrank/algorithm/strings/strong_password.py
2,906
4.375
4
""" Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria: Its length is at least . It contains at least one digit. It contains at least one lowercase English character. It contains at least one uppercase English character. It contains at least one special character. The special characters are: !@#$%^&*()-+ She typed a random string of length in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong? Note: Here's the set of types of characters in a form you can paste in your solution: numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" special_characters = "!@#$%^&*()-+" Input Format The first line contains an integer denoting the length of the string. The second line contains a string consisting of characters, the password typed by Louise. Each character is either a lowercase/uppercase English alphabet, a digit, or a special character. Constraints Output Format Print a single line containing a single integer denoting the answer to the problem. Sample Input 0 3 Ab1 Sample Output 0 3 Explanation 0 She can make the password strong by adding characters, for example, $hk, turning the password into Ab1$hk which is strong. characters aren't enough since the length must be at least . Sample Input 1 11 #HackerRank Sample Output 1 1 Explanation 1 """ # !/bin/python3 import sys numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" special_characters = "!@#$%^&*()-+" def minimumNumber(n, password): add = 0 if all(n not in password for n in numbers): add += 1 if all(l not in password for l in lower_case): add += 1 if all(u not in password for u in upper_case): add += 1 if all(s not in password for s in special_characters): add += 1 return add + max(0, 6 - len(password) - add) if __name__ == "__main__": n = int(input().strip()) password = input().strip() answer = minimumNumber(n, password) print(answer) ''' numbers = "0123456789" lower_case = "abcdefghijklmnopqrstuvwxyz" upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" special_characters = "!@#$%^&*()-+" input() s=input() ans = 0 found = any(i in numbers for i in s) if not found: ans += 1 s += "0" found = any(i in lower_case for i in s) if not found: ans += 1 s += 'a' found = any(i in upper_case for i in s) if not found: ans += 1 s += 'A' found = any(i in special_characters for i in s) if not found: ans += 1 s += '!' if len(s) < 6: ans += 6 - len(s) print(ans) '''
true
082b98374cec16d6f9aee1670ae6c5a3fcbac0f5
vitthalpadwal/Python_Program
/hackerrank/algorithm/strings/caesar_cipher.py
2,003
4.59375
5
""" Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c. Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated +3: defghijklmnopqrstuvwxyzabc For example, the given cleartext and the alphabet is rotated by . The encrypted string is . Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted. Function Description Complete the caesarCipher function in the editor below. It should return the encrypted string. caesarCipher has the following parameter(s): s: a string in cleartext k: an integer, the alphabet rotation factor Input Format The first line contains the integer, , the length of the unencrypted string. The second line contains the unencrypted string, . The third line contains , the number of letters to rotate the alphabet by. Constraints is a valid ASCII string without any spaces. Output Format For each test case, print the encoded string. Sample Input 11 middle-Outz 2 Sample Output okffng-Qwvb Explanation Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated +2: cdefghijklmnopqrstuvwxyzab m -> o i -> k d -> f d -> f l -> n e -> g - - O -> Q u -> w t -> v z -> b Python 3 """ cnt = int(input()) string = input() shift = int(input()) res = "" while shift > 26: shift -= 26 for char in string: if char.isalpha(): is_upper = False; is_lower = False; if ord(char) < 95: is_upper = True else: is_lower = True ascii_new = ord(char) + shift if is_upper and ascii_new > 90: ascii_new = ascii_new - 26 if is_lower and ascii_new > 122: ascii_new = ascii_new - 26 res += chr(ascii_new) else: res += char print(res)
true
741eac7bd97af4a06ae3c38252654b88cb9c0e73
VitaliiRevenko/PytonLessonsForBeginnerBeetRootAcademy
/lesson_10/task1.py
701
4.21875
4
''' Task 1 A Person class Make a class called Person. Make the __init__() method take firstname, lastname, and age as parameters and add them as attributes. Make another method called talk() which makes prints a greeting from the person containing , for example like this: “Hello, my name is Carl Johnson and I’m 26 years old”. ''' class Person: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def talk(self): print(f'Hello, my name is {self.first_name} {self.last_name} and I’m {self.age} years old') information = Person('Vitalii', 'Revenko', 35 ) information.talk()
true
24390631ccf66c46fbee54cd5c1068a74b0b2791
VitaliiRevenko/PytonLessonsForBeginnerBeetRootAcademy
/lesson_22/task4.py
752
4.3125
4
# Task 4 # # def reverse(input_str: str) -> str: # """ # Function returns reversed input string # reverse("hello") == "olleh" # True # reverse("o") == "o" # True # def reverse(input_str: str) -> str: # if len(input_str) == 1: # return input_str # return input_str[-1] + reverse(input_str[:-1]) # # if __name__ == '__main': # assert reverse("hello") == "olleh" # assert reverse("o") == "o" def reverse1(input_str: str) -> str: if len(input_str) == 1: return "".join(reversed(input_str)) return "".join(reversed(input_str[-1])) + reverse1(input_str[:-1]) if __name__ == '__main__': assert reverse1("hello") == "olleh" assert reverse1("o") == "o"
false
a450d7febe14eacf228fa011272cd6d9fe78983e
robbailiff/maths-problems
/gapful_numbers.py
937
4.1875
4
""" A gapful number is a number of at least 3 digits that is divisible by the number formed by the first and last digit of the original number. For Example: Input: 192 Output: true (192 is gapful because it is divisible 12) Input: 583 Output: true (583 is gapful because it is divisible by 53) Input: 210 Output: false (210 is not gapful because it is not divisible by 20) Write a program to check if the user input is a gapful number or not. """ def gapful(n): ns = str(n) if len(str(n)) >= 3: num = int(str(ns[0]) + str(ns[-1])) if n % num == 0: return True else: return False else: print("Number needs to be at least 3 digits long") print(gapful(100)) def gapful_range(n): g_nums = [] for x in range(100, n): num = gapful(x) if num == True: g_nums.append(x) return g_nums print(gapful_range(1000))
true
18756becf16c3252294155a8b01c82acba7a8fd4
charugarg93/LearningML
/04_List.py
1,219
4.59375
5
books = ['kanetkar', 'ritchie', 'tanenbaum'] print(books[2]) # in python you can also have negative indices # -1 denotes last element of the list, -2 denotes second last item of the list and so on print("Experimenting with negative indices ::: "+ books[-3]) books.append("galvin") print(books) # extend method is used to add multiple items in a list books.extend(['rosen','headfirst', 'cormen']) print(books) more_books = ['kreyzig', 'mitchel'] books.extend(more_books) # print("Newly added books::: "+more_books) print(books) # slices are used to access the elements from one index to another # this will print elements from index 1 to 3. 4 will be excluded print(books[1:4]) my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) # elements beginning to 4th print(my_list[:-5]) # elements 6th to end print(my_list[5:]) # elements beginning to end print(my_list[:]) # deleting elements of list my_list = ['p','r','o','b','l','e','m'] # delete one item del my_list[2] # Output: ['p', 'r', 'b', 'l', 'e', 'm'] print(my_list) # delete multiple items del my_list[1:5] # Output: ['p', 'm'] print(my_list) # delete entire list del my_list # Error: List not defined print(my_list)
true
6b181ec8bd9d686fa14459e0b89dcfb96743dd69
arunk38/learn-to-code-in-python
/Python/pythonSpot/src/3_database_and_readfiles/1_read_write/read_file.py
397
4.125
4
import os.path # define a filename. filename = "read_file.py" # open the file as f # The function readlines() reads the file. if not os.path.isfile(filename): # check for file existence print("File does not exist: " + filename) else: with open(filename) as f: content = f.read().splitlines() # show the file contents line by line for line in content: print(line)
true