blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
f8b70ce34396a0e5c3d0aac7f95ede04f9169254
sreekanth-s/python
/old_files/count_number_of_on_bits.py
350
4.28125
4
print("Enter a number to find the number of ON bits in a number.") num=int(input("Enter a positive integer: ")) print_num = num count=0 if num > 0: while num > 0: if num & 1: count+=1 num = num >> 1 print("The number entered", print_num, "has", count, "ON bits.") else: print("Enter a positive number. ")
true
0507f088e2b020bb677f3772efd8affcdf63f8b3
sreekanth-s/python
/old_files/factorial.py
730
4.46875
4
""" num=int(input("Enter a number to find factorial: ")) if (num <= 0): print("Enter a valid integer! ") else: print("You've entered ", num) for i in range(1,num): num=num*i print("and the factorial is ",num) """ num=int(input("Enter a number to find factorial: ")) print("You've entered ", num) fact=1 if (num <= 0): print("Enter a valid integer! ") else: while num > 1: fact=fact*(num) num=num-1 print("and the factorial is ", fact) def factorial(num): fact=1 fact=fact*num num=num-1 factorial(num-1) """ def factorial(num): if num==1: print(result) exit() result=num*(num-1) factorial(num) # factorial(5) """
true
9363df1f25908275c4b4446c0911a110d7c7585b
sreekanth-s/python
/data_structures/stack_implementation.py
2,510
4.28125
4
def execution(): opr = input("Enter an operation to perform: ") if opr == "1" or opr == "push": value = input("Enter a value to push: ") ret = stack_push(value) if ret == None: print("The stack is full. try popping. \n \n") execution() else: print("\n \n") execution() elif opr == "2" or opr == "pop": ret = stack_pop(sl) if ret == None : print("The stack is empty. try pushing. \n \n ") execution() else: print("\n \n") execution() elif opr == "3" or opr == "is_empty": ret = stack_is_empty(sl) if ret == True : print("The stack is indeed empty. \n \n") execution() else: print("The stack is not empty. ") execution() elif opr == "4" or opr == "peek" : ret = stack_peek(sl) if ret == None : print("The stack is empty. try pushing. \n \n") execution() else: print("The top most element is ", ret, "\n \n") execution() elif opr == "5" or opr == "size" : ret = stack_size(sl) print("The size of the stack is ", ret, "\n \n") execution() elif opr == "6" or opr == "stack_print" : stack_print(sl) execution() else: print(sl, "is the final stack ") pass def stack_push(value): if len(sl) == s_size: return None else: sl.append(value) return sl def stack_pop(sl): if sl == []: return None else: return sl.pop() def stack_is_empty(sl): if len(sl) == 0: return True def stack_peek(sl): if sl == []: return None else: return sl[-1] def stack_size(sl): return len(sl) def stack_print(sl): print("The stack size entered is ", s_size) print("The current stack is ", sl, "\n \n") return if __name__ == "__main__": """ """ s_size = int(input("Enter stack size: ")) sl=[] if s_size < 1: print("Enter a valid size for stack.") exit else: print("you have selected a stack of size ", s_size) print("now you can perform below operations on the stack: \n \ 1. push \n \ 2. pop \n \ 3. is_empty \n \ 4. peek \n \ 5. size \n \ 6. print \n \ ") execution()
true
33c2bf53a6057e5985882bcb595bbf81c995cb8b
moisesvega/Design-Patterns-in-Python
/src/Creational Patterns/Factory Method/Factory.py
710
4.21875
4
''' Created on Jul 16, 2011 @author: moises ''' '''Defines the interface of objects the factory method creates''' class Product: pass '''Implements the Product interface''' class ConcreteProductA( Product ): def __init__( self ): self.product = "Guitar" '''Implements the Product interface''' class ConcreteProductB( Product ): def __init__( self ): self.product = "Drums" '''Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. ''' factory = { "Item1" : ConcreteProductA, "Item2" : ConcreteProductB, }
true
b5ce82a388586bf89689129118e1f9ce9a4a749a
JackRossProjects/cs-module-project-recursive-sorting
/src/sorting/sorting.py
1,708
4.21875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements indexM = 0 while (len(arrA) > 0) & (len(arrB) > 0): if arrA[0] <= arrB[0]: merged_arr[indexM] = arrA.pop(0) else: # arrA[0] > arrB[0] merged_arr[indexM] = arrB.pop(0) indexM += 1 while len(arrA) > 0: merged_arr[indexM] = arrA.pop(0) indexM += 1 while len(arrB) > 0: merged_arr[indexM] = arrB.pop(0) indexM += 1 return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 return arr ''' # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): # Your code here def merge_sort_in_place(arr, l, r): # Your code here '''
false
cae9cefa76b2a60f0d07f80b40946fca22e40def
AmandaRH07/PythonUdemy
/3. Programação Orientada a Objetos/112_Metaclasses.py
1,005
4.3125
4
""" Metaclasses Em Python tudo é objeto, incluindo classes Metaclasses são classes que criam classes Ex: type é uma metaclasse """ class Meta(type): def __new__(mcs, name, bases, namespace): print(name) if name == "A": return type.__new__(mcs, name, bases, namespace) print(namespace) if "b_fala" not in namespace: print(f"Você precisa criar o método b_fala em {name}") else: if not callable(namespace['b_fala']): print(f"b_fala precisa ser um métoo, não um atributo em {name}") return type.__new__(mcs, name, bases, namespace) class A(metaclass=Meta): def fala(self): self.b_fala() class B(A): teste = "Valor" # b_fala = "teste" # pass def b_fala(self): print("OI") def sei_la(self): pass b = B() b.fala() class Pai: nome = 'teste' C = type( 'c', (Pai,), {'attr': "Ola mundo"} ) c = C() print(type(c)) print(c.nome)
false
3c274abda74e08daecf01b020f49b323b8246366
AmandaRH07/PythonUdemy
/2. Intermediário/47- Ex01.py
1,360
4.3125
4
""" 1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome. """ def saudacao(saudacao, nome): print(f"{saudacao} {nome}") saudacao("Olá","Maria") """ 2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre eles. """ def soma(n1,n2,n3): print(f"{n1} + {n2} + {n3} = {n1+n2+n3}") n1 = int(input("Número 1: ")) n2 = int(input("Número 2: ")) n3 = int(input("Número 3: ")) soma(n1,n2,n3) """ 3 - Crie uma função que receba 2 números. O primeiro é um valor e o segundo um percentual (ex. 10%). Retorne (return) o valor do primeiro número somado do aumento do percentual do mesmo. """ def aumento_Percentual(valor, percentual): print(valor + (valor * percentual/100)) valor = int(input("Valor: ")) percentual = int(input("Percentual: ")) aumento_Percentual(valor,percentual) """ 4 - Fizz Buzz - Se o parâmetro da função for divisível por 3, retorne fizz, se o parâmetro da função for divisível por 5, retorne buzz. Se o parâmetro da função for divisível por 5 e por 3, retorne FizzBuzz, caso contrário, retorne o número enviado. """ def FizzBuzz(p): if p % 3 == 0 and p % 5 == 0: print("FizzBuzz") elif p%5 == 0: print("Fizz") elif p%3 == 0: print("Buzz") else: print(p) p = int(input("Digite um número: ")) FizzBuzz(p)
false
7a7ea125fd59dbdf811747afd70283ae9429c947
VamshiPriyaVoruganti/HackerRank
/Programs/Python functionals/lambda.py
342
4.15625
4
cube = lambda x: pow(x,3) # complete the lambda function def fibonacci(n): a=0;b=1;l=[] if n>0: l.append(a) if n>1: l.append(b) for x in range(n-2): c=a+b l.append(c) a=b b=c return l # return a list of fibonacci numbers
false
dd011849fd5a7129d7fc90f9f0df97a8f2c5094f
felipellima83/wiki.python.org.br-EstruturaSequencial
/Exercicio07.py
452
4.1875
4
#Felipe Lima #Linguagem: Python #Exercício 07 do site: https://wiki.python.org.br/EstruturaSequencial #Entra com a altura do quadrado altura = float(input("Qual a altura do quadrado: ")) #Entra com a base do quadrado: base = float(input("Qual a largura do quadrado: ")) #Realiza os cálculos area = base*altura dobro = area*2 #Imprime os resultados print("A área do quadrado é {:.2f}.".format(area)) print("O dobro da área é {:.2f}.".format(dobro))
false
3625d90df67e51c6683231dbe2fe15ab18776c5b
JudoboyAlex/python_fundamentals2
/reinforcement_exercise2.py
1,392
4.15625
4
# Let's take a different approach to film recommendations: create the same variables containing your potential film recommendations and then ask the user to rate their appreciation for 1. documentaries 2. dramas 3. comedies on a scale from one to five. If they rate documentaries four or higher, recommend the documentary. If they rate documentaries 3 or lower but both comedies and dramas 4 or higher, recommend the dramedy. If they rate only dramas 4 or higher, recommend the drama. If they rate just comedies 4 or higher, recommend the comedy. Otherwise, recommend a good book. documentary = "climate changing!" drama = "joker" comedy = "sonic" dramedy = "meet the parents" print("Please rate from one to five, your appreciation for documentary") response1 = int(input()) print("Please rate from one to five, your appreciation for dramas") response2 = int(input()) print("Please rate from one to five, your appreciation for comedy") response3 = int(input()) if response1 >= 4: print("I recommend you to watch {}.".format(documentary)) elif response1 <= 3 and response2 >= 4 and response3 >= 4: print("I recommend you to watch {}.".format(dramedy)) elif response2 >= 4 and response1 <= 3 and response3 <= 3: print("I recommend you to watch {}.".format(drama)) elif response3 >= 4 and response1 <= 3 and response2 <=3: print("I recommend you to watch {}.".format(comedy))
true
942c7fe91f9833c7804f86a42f4b5dcb6aa49e5b
vineetbaj/Python-Exercises
/30 days of code/Day 3 - Intro to Conditional Statements.py
946
4.5625
5
""" ***Day 3*** Objective In this challenge, we learn about conditional statements. Check out the Tutorial tab for learning materials and an instructional video. Task Given an integer, , perform the following conditional actions: If is odd, print Weird If is even and in the inclusive range of to , print Not Weird If is even and in the inclusive range of to , print Weird If is even and greater than , print Not Weird Complete the stub code provided in your editor to print whether or not is weird. Input Format A single line containing a positive integer, . Constraints Output Format Print Weird if the number is weird; otherwise, print Not Weird. """ #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': N = int(input().strip()) if N % 2 == 1: print("Weird") else: if 6<=N<=20 : print("Weird") else: print("Not Weird")
true
ed57527d425099403a508453e90d0850c3e8e825
0f11/Python
/pr04_adding/adding.py
2,513
4.21875
4
"""Adding.""" def get_max_element(int_list): """ Return the maximum element in the list. If the list is empty return None. :param int_list: List of integers :return: largest int """ if len(int_list) == 0: return None return max(int_list) pass def get_min_element(int_list): """ Return the minimum element in list. If the list is empty return None. :param int_list: List of integers :return: Smallest int """ if len(int_list) == 0: return None return min(int_list) pass def sort_list(int_list): """ Sort the list in descending order. :param int_list: List of integers :return: Sorted list of integers """ return sorted(int_list, reverse=True) pass def add_list_elements(int_list): """ Create a new sorted list of the sums of minimum and maximum elements. Add together the minimum and maximum element of int_list and add that sum to a new list Repeat the process until all elements in the list are used, ignore the median number if the list contains uneven amount of elements. Sort the new list in descending order. This function must use get_min_element(), get_max_element() and sort_list() functions. :param int_list: List of integers :return: Integer list of sums sorted in descending order. """ new_int_list = [] sort_list(int_list) while get_max_element(int_list) is not None and get_min_element(int_list) is not None: sort_list(int_list) if len(int_list) % 2 == 0 and len(int_list) > 1: uus1 = get_max_element(int_list) uus2 = get_min_element(int_list) uus3 = uus1 + uus2 new_int_list.append(uus3) del int_list[0] del int_list[-1] if len(int_list) % 2 != 0 and len(int_list) > 1: sort_list(int_list) uus1 = get_max_element(int_list) uus2 = get_min_element(int_list) uus3 = int(uus1) + int(uus2) new_int_list.append(uus3) del int_list[0] del int_list[-1] if len(int_list) == 1: break return sorted(new_int_list, reverse=True) pass if __name__ == '__main__': print(add_list_elements([0, 0, 0, 0, 0, 0, 1, 2, 5, 6])) # -> [6, 5, 2, 1, 0] print(add_list_elements([0, 0, 2, 0, 3, 4, 1, 2, 5, 6])) print(add_list_elements([-1, -2, -5, -14, -50])) # -> [-16, -51] print(add_list_elements([1])) # -> []
true
f91ab594ea14320cd78b821af01b64ed200abb3a
0f11/Python
/pr02_triangle/pr02_triangle.py
1,440
4.3125
4
"""Triangle info.""" import math def find_triangle_info(a, b, c): """ Write a function which finds perimeter, area and type of triangle based on given side lengths. (Note: a <= b <= c). The function should print "{type_by_length} {type_by_angle} triangle with perimeter of {perimeter} units and area of {area} units". IE: sides 3, 4, 5 should print "Scalene right triangle with perimeter of 12.0 units and area of 6.0 units". :return: None """ perimeter = a + b + c pindala1 = (a + b + c) / 2 area = round(math.sqrt(pindala1 * (pindala1 - a) * (pindala1 - b) * (pindala1 - c)), 2) if a == b == c: type_by_length = "Equilateral" elif a == b or b == c or a == c: type_by_length = "Isosceles" elif a != b != c: type_by_length = "Scalene" if (a * a) + (b * b) == (c * c): type_by_angle = "right" elif (a * a) + (b * b) < (c * c): type_by_angle = "obtuse" elif (a * a) + (b * b) > (c * c): type_by_angle = "acute" print(f"{type_by_length} {type_by_angle} triangle with perimeter of {perimeter} units and area of {area} units") # if __name__ == "__main__": # <- This line is needed for automatic testing find_triangle_info(4, 5, 6) # Scalene acute triangle with perimeter of 15.0 units and area of 9.92 units find_triangle_info(4, 4, 6) # Isosceles obtuse triangle with perimeter of 14.0 units and area of 7.94 units
false
ca58251889ad80531e12647fc58181b86fe0f808
sonhal/python-course-b-code
/user_loop.py
421
4.125
4
# CLI program for pointlessly asking the user if they want to continue loop_counter = 0 while(True): print("looped: "+ str(loop_counter)) loop_counter += 1 user_input = input("Should we continue? ") if user_input == "yes": continue elif user_input == "no": print("Thank you for playing!") break else: print("Dont know what you meant, am going to continue to ask!")
true
274acbf8fa74954bcf8885b4e0a203f14e6604c3
donyu/euler_project
/p14.py
1,028
4.3125
4
def collatz_chain(max): longest_chain.max = max longest_chain.max_len = 0 longest_chain(1, 1) return longest_chain.max_len def longest_chain(x, length): """Will find longest Collatz sequence by working backwards recursively""" if length > 10: return # base case if number over 1,000,000 if x > longest_chain.max: if length > longest_chain.max_len: longest_chain.max_len = length print "hi" + str(x) return # else send to possible before sequence number even_n = x * 2 odd_n = 0 if (x -1) % 3 == 0: odd_n = (x - 1) / 3 print even_n print odd_n if is_even(odd_n) and is_odd(even_n): return elif odd_n < 1 or is_even(odd_n): longest_chain(even_n, length + 1) elif even_n > longest_chain.max or is_odd(even_n): longest_chain(odd_n, length + 1) else: longest_chain(even_n, length + 1) longest_chain(odd_n, length + 1) def is_odd(x): return (x % 2 != 0) def is_even(x): return (x % 2 == 0) if __name__ == "__main__": print collatz_chain(20)
true
309aea1305c2be0d6acfcb41f6877965499388a4
malakani/PythonGit
/mCoramKilometers.py
757
4.71875
5
# Program name: mCoramKilometers.py # Author: Melissa Coram # Date last updated: September 21, 2013 # Purpose: Accepts a distance in kilometers and outputs the distance in kilometers # and miles. # main program def main(): # get the distance in kilometers distance = int(input('Enter the distance in kilometers: ')) # pass distance to compute_miles function for calculation and display compute_miles(distance) # print message print('Kilometers XXXXX is equal to XXXXX miles') # converts kilometers to miles and displays the distance in both forms def compute_miles(kilometers): miles = kilometers * 0.6214 print('The distance in kilometers is', kilometers) print('The distance in miles is', miles) # start the program main()
true
cbd34a38ce7d9d31317024c247563515d3bb48ad
malakani/PythonGit
/mCoramPenniesForPay.py
1,171
4.59375
5
# Program name: mCoramPenniesForPay.py # Author: Melissa Coram # Date last updated: 10/24/2013 # Purpose: Calculates and displays the daily salary and total pay earned. def main(): # Get the number of days from the user. print('You start a job working for one penny a day and your pay doubles every day thereafter.') days = int(input('How many days do you work? ')) # Print header print('Day\tSalary\t\t\tTotal Pay') print('------------------------------------------------') # Run function to calculate salary. create_table(days) # Function to calculate salary. def create_table(days): # Initialize total pay to zero. totalPay = 0 # Initialize salary to $0.01. salary = .01 # Loop to calculate and display the salary earned each day and total amount earned. for x in range(days): # Add salary to total pay. totalPay += salary # Display current day's salary and total amount earned including the current day. print(x + 1, '\t$', format(salary, '10,.2f'), '\t\t$', format(totalPay, '10,.2f')) # Double salary for the next day's pay. salary *= 2 # Run main function. main()
true
59a6d3c3e45ad3b18ac8089856e5feda50877c3a
CharlieDaniels/Puzzles
/trailing.py
410
4.25
4
#Given an integer n, return the number of trailing zeroes in n! from math import factorial def trailing(n): #find the factorial of n f = factorial(n) #cast it as a string f_string = str(f) #initialize counters num_zeroes = 0 counter = -1 #count the number of zeroes in n, starting from the end while f_string[counter] == '0': num_zeroes = num_zeroes + 1 counter = counter -1 return num_zeroes
true
58dae9443233c7661c2740523f7dfd559d313401
TanvirAhmed16/Advanced_Python_Functional_Programming
/11. List Comprehensions.py
1,716
4.46875
4
''' # Comprehensions in Python - Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined. Python supports the following 4 types of comprehensions: # List Comprehensions # Dictionary Comprehensions # Set Comprehensions # Generator Comprehensions # List Comprehensions: List Comprehensions provide an elegant way to create new lists. The following is the basic structure of a list comprehension: output_list = [output_exp for var in input_list if (var satisfies this condition)] Note that list comprehension may or may not contain an if condition. List comprehensions can contain multiple for (nested list comprehensions). ''' ''' Example #1: Suppose we want to create an output list which contains only the even numbers which are present in the input list. Let’s see how to do this using for loops and list comprehension and decide which method suits better. ''' # Constructing output list WITHOUT Using List comprehensions input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] output_list = [] for num in input_list: if num % 2 == 0: if num not in output_list: # Checking duplicate item. An extra condition. output_list.append(num) print(f'The output list using for loop is : {output_list}') # Constructing output list Using List comprehensions print(f'The output list using list comprehension is : ', [num for num in input_list if num % 2 == 0], '\n') # Creating new list very easily... print([num for num in range(0, 50) if num % 2 == 0]) my_list = [num*3 for num in range(0, 20)] print(my_list)
true
ff474eb65652308fee85de0d5d38885903b7372e
aaronyang24/python
/Assignment_Ch02-01_Yang.py
320
4.15625
4
time = int(input("Enter the elapsed time in seconds: ")) hours = time // 3600 remainder = time % 3600 min = remainder // 60 sec = remainder % 60 print("\n" + "The elapsed time in seconds = " + str(time )) print ("\n" + "The equivalent time in hours:minutes:seconds = " + str(hours) +":" + str(min)+":" + str(sec) )
true
e5651299e4b4159e6331e910dac0380344e35ba3
phillib/Python-On-Treehouse.com
/Python-Collections/string_factory.py
565
4.28125
4
#Created using Python 3.4.1 #This will create a list of name and food pairs using the given string. #Example: "Hi, I'm Michelangelo and I love to eat PIZZA!" dicts = [ {'name': 'Michelangelo', 'food': 'PIZZA'}, {'name': 'Garfield', 'food': 'lasanga'}, {'name': 'Walter', 'food': 'pancakes'}, {'name': 'Galactus', 'food': 'worlds'} ] string = "Hi, I'm {name} and I love to eat {food}!" def string_factory(dicts, string): new_list = [] for combo in dicts: new_list.append(string.format(**combo)) return new_list
true
277698d0c991dcf689dac18f73eb70137e75c573
elliehendersonn/a02
/02.py
766
4.65625
5
""" Problem: The function 'powers' takes an integer input, n, between 1 and 100. If n is a square number, it should print 'Square' If n is a cube number, it should print 'Cube' If n is both square and cube, it should print 'Square and Cube'. For anything else, print 'Not a power' Cube numbers less than 100 are: 1, 8, 27, 64. Tests: >>> powers(4) Square >>> powers(8) Cube >>> powers(53) Not a power >>> powers(27) Cube >>> powers(81) Square >>> powers(64) Square and Cube >>> powers(93) Not a power """ # This code tests your solution. Don't edit it. import doctest def run_tests(): doctest.testmod(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE) def powers(n):
true
5a7ca588a04c1717f05edb329cd3dda69519b0d7
ShemarYap/FE595-Python-Refresher
/Python_Refresher_Huq.py
1,220
4.1875
4
# Importing numpy and matplotlib import numpy as np import matplotlib.pyplot as plt # Setting the X values in the x variable x = np.arange(0, 2*np.pi, 0.01) # Setting the values for Sine in the sin_y variable sin_y = np.sin(x) # Plotting with x variable for X-axis and sin_y for Y-axis. # The linewidth argument increases the width of the line, # making it stand out more. The label argument will allow # for differentiation of lines on the same axis via a legend plt.plot(x, sin_y, linewidth=3, label='Sine') # Setting the values for Cosine in the cos_y variable cos_y = np.cos(x) # Plotting on same axis with x variable for X-axis and cos_y # for Y-axis. The linewidth and label arguments do the same # thing as previously described above the first plt.plot plt.plot(x, cos_y, linewidth=3, label='Cosine') # Adding appropriate title plt.title('One Period Plot of Sine and Cosine') # Labeling X-axis and Y-axis as appropriate plt.xlabel('X values from Zero to 2Pi') plt.ylabel('Sine and Cosine Values') # Including the legend to differentiate the two lines plt.legend() # Adding a grid plt.grid(True) # Showing the plot with all relevant information included plt.show()
true
13939777116661ac7fcd97f066470d0cd139d195
ramkishor-hosamane/Python-programming
/comb.py
646
4.25
4
def list_powerset(lst): # the power set of the empty set has one element, the empty set result = [[]] for x in lst: # for every additional element in our set # the power set consists of the subsets that don't # contain this element (just take the previous power set) # plus the subsets that do contain the element (use list # comprehension to add [x] onto everything in the # previous power set) result.extend([subset + [x] for subset in result]) res = [''.join(x) for x in result] #res.sort() res.reverse() return res lst='cde' print(list_powerset(lst))
true
75adbfcf31be2ec4bde27deffa4dde1782e2e5a7
Darlight/Algoritmos_proyectos
/proyecto_lamda.py
1,240
4.15625
4
""" Universidad del Valle de Guatemala CC3041 - Analisis y diseño de algoritmos Ing. Tomas Galvez Mario Perdomo Carnet 18029 proyecto_lamda.py """ #Usando la manera pythonica de los lambdas: https://realpython.com/python-lambda/ f = lambda x: x+1 g = lambda x: 2 * x h = lambda x, y: x**2 + y**2 cero = lambda fn, x: x uno = lambda fn, x: fn(x) dos = lambda fn, x: fn(fn(x)) tres = lambda fn, x: fn(fn(fn(x))) #vistos en clase #lambda n: lambda f: lambda x : f(n(f)(x)) sucesor = lambda fn, n, x: fn(n(fn,x)) #lambda a: lambda b: lambda fn: lambda x : a(f)(b(f)(x)) #print(suma(uno)(dos)(f)(1)) suma = lambda fn, a, b, x: a(fn,(b(fn,x))) #lambda a: lambda b: lambda f: lambda x : a((b)(f))(x) multi = lambda fn, a, b, x: a((b,fn),x) print("f(5) = " + str(f(5))) print("g(3) = " + str(g(3))) print("g(4,4) = " + str(h(4,4))) print("cero(f,4) = " + str(cero(f,4))) print("uno(f,4) = " + str(uno(f,4))) print("dos(g,4) = " + str(dos(g,4))) print("tres(f,4) = " + str(tres(f,4))) print("sucesor(f, dos, 5) = " + str (sucesor(f,dos,5))) print("suma(f, dos, uno, 3) = " + str(suma(f,dos,uno,3))) #pruba que suma(f,dos,uno,3) == tres(f,3), quitar el comentario de abajo #print(tres(f,3)) #print("multi(dos,tres,g,5 = " + str(multi(f,dos,uno,3)))
false
286551edca202747a0b390aa212e35136b4f3e21
yegornikitin/itstep
/lesson12/triple_result.py
717
4.15625
4
try: a = int(input("Please, insert first integer: ")) b = int(input("Please, insert first integer: ")) # First function, that will only show a + b def add(a, b): return a + b print("---------------") print("Result without decorator: ", add(a, b)) # Second function with decorator, that will show (a + b) * 3 def triple_result(func): def wrapper(*args): print("Result with decorator: ", func(*args) * 3) return wrapper @triple_result def add_2(a, b): return a + b add_2(a, b) except ValueError: print("---------------") print("Error. Please, try one more time and insert integers")
true
72d6893e88e7ae669fd7d5df179cbfb186f83e4d
simonisacoder/AI
/lab/lab1 数据集处理/re.sub.py
346
4.15625
4
import re # first way to check whether a word has number def hasNum1(string): return any(char.isdigit() for char in string) #second way: regular expression def hasNum2(string) s = "123 a:1 b:2 c:3 ab cd ef" s = s.split() print(s) for i in s: if re.search(r'\d',s(i),flag=0): print(s(i).group()) else: print('num')
true
a2669deb7b77b947e9eed229a36010a02af6f7e7
Allen-heh/learnpython
/d8/point.py
818
4.21875
4
#!/usr/bin/env python import math class point(object): def __init__(self, x, y): self._x = x self._y = y self.__z = x def move_to(self, x1, y1): self._x = x1 self._y = y1 def move_by(self, dx, dy): self._x += dx self._y += dy def distance(self, other): dx = self._x - other._x dy = self._y - other._y return math.sqrt(dx**2 + dy**2) def print_xy(self): print(self._x) print(self._y) def main(): p1 = point(10,10) p2 = point(2,2) #print(p1) #print(p1._point__z) #p1.print_xy() #print(p2) #p2.print_xy() #print(p1.distance(p2)) print(p1._x) #p1.move_to(1,2) #print(p1._x) point.move_to(p1,2,2) print(p1._x) if __name__ == "__main__": main()
false
5ea76df223d67ff9b2bf3f6d1046997dc34ffcf0
bhanurangani/code-days-ml-code100
/code/day-2/5.Getting Input From User/AppendingN ame.py
407
4.46875
4
#appending first name and last name name=str(input("enter the first name")) surname=str(input("enter the last name")) #no such function to append the string, but simply it can be done this way name=name +" "+ surname print(name) #using %s we can use to in cur the values to print z="%s is son of Mr. %s"%(name,surname) print(z) #printing using the operator print ("{} is son of Mrs.{}".format(name,surname))
true
f80b64c0f93213a777b10faa04c7a974bb75ecd8
vijayxtreme/ctci-challenge
/Arrays/isUnique_r1.py
822
4.28125
4
#Is Unique ''' I rewrote this one for ASCII / Alphabet Basically if there are more than 256 characters, this can't be unique because there are only 256 ASCII characters allowed. If we wanted to just do letters, we could do 26 letters and lowercase all entries The trick here is that unicode goes up to 128, so we can index every array here 0-128. If we come across a letter, we can just set it to True, so if we come across it again, we return False. Pretty brilliant using unicode. ''' def isUnique(str): if(len(str)>128): return False uniqs = [False] * 128 for i in range(0, len(str)): #ord converts to ascii 1-128, which is fine for an array val = ord(str[i]) if uniqs[val]: return False uniqs[val] = True return True print(isUnique("hello"))
true
d2d7eaabb74520239b0efdccd27413c4b742894b
zwagner42/dailyprogrammer
/Easy Programs/Problems1-20/Calendar_Date.py
2,005
4.625
5
#Program to find the day of the month based on a given number day, number month, and number year from sys import argv, exit from calendar import isleap, monthrange, weekday from Input_Check import is_Number, is_Number_Range #Displays an error message for an incorrect argument list def error_Message_Argument_List(): print("Error!! Wrong number of arguments. Sample on how to run this program:\n") print("py Calendar_Date.py 10 12 1995") exit() #Displays an error message for invalid members in the argument list def error_Message_Invalid_Members(): print("Error!! Invalid user input! Sample on how to run this program:\n") print("py Calendar_Date.py 10 12 1995") exit() #Finds and prints the day of the month for the given information from the command line arguments #Each argument passed is a piece from the argument list passed as integers #Uses the calendar weekday method and a list of the days as strings (day_List) def day_Selection(day, month, year): day_List = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] print(day_List[weekday(year, month, day)]) #--------------------------------------------------------------------------------------------- #Check if the argument list contains the right number of arguments if(len(argv) < 4 or len(argv) > 4): error_Message_Argument_List() #Check if the year is a 4 digit number if(len(argv[3]) != 4 or not is_Number(argv[3])): error_Message_Invalid_Members() else: #Check if the Month is within the range of 12 months and is a number if(not is_Number_Range(argv[2], 1, 12)): error_Message_Invalid_Members() #Check if the days is a number elif(not is_Number(argv[1])): error_Message_Invalid_Members() else: storage = monthrange(int(argv[3]), int(argv[2])) #Check if the days are within the range for a given month and year if(int(argv[1]) > storage[1] or int(argv[1]) < 1): error_Message_Invalid_Members() else: day_Selection(int(argv[1]), int(argv[2]), int(argv[3]))
true
cb8284d5ee30e8184ecf6c0bd3579829540a5923
cjohlmacher/PythonSyntax
/words.py
367
4.3125
4
def print_upper_words(wordList,must_start_with): """Prints the upper-cased version of each word from a word list that starts with a letter in the given set""" for word in wordList: if word[0] in must_start_with: print(word.upper()) print_upper_words(["hello", "hey", "goodbye", "yo", "yes"], must_start_with={"h", "y"})
true
3012f4a88f70458121ad44ac54f5fcbf2d6bbbb7
Lievi77/csl-LATAM-graph
/public/data/LATAM_filter.py
2,206
4.21875
4
import pandas as pd # Script to filter out COVID-19 Data # by: Lev Cesar Guzman Aparicio lguzm77@gmail.com # ----------------------------METHODS------------------------------------------------------------------ # ------------------------------MAIN---------------------------------------------------------------------- def main(): # first we will read the .csv file covid_df = pd.read_csv("./LATAM-JUNE-5-2020.csv") # reads well # now we filter the continentExp column to only have "America Values" # first stage of filtering # first Step: create a boolean expression representing what we want to keep # boolean variable; selects all the rows that satisfy the condition is_from_americas = covid_df.continentExp.eq("America") # another syntax # alternate syntax: is_from_americas = covid_df["continentExp"] = covid_df["continentExp"] == "America" # we will chain multible boolean variables for Latin American Cases only not_latam = ["United_States_of_America", "Canada"] # to store the filtered data, save the new df in a new variable covid_df_americas = covid_df[is_from_americas & ~ covid_df.countriesAndTerritories.isin(not_latam)] # now let us sort our df by date in ascending order # format in the original file is dd-mm-YYYY covid_df_americas['dateRep'] = pd.to_datetime( covid_df_americas[['day', 'month', 'year']]) # convert it to a datetime object for sorting # inplace has to be true for the sorting to be stored covid_df_americas.sort_values(by=['dateRep'], inplace=True) # now group the data by date and record the cases condensed_df_americas = covid_df_americas.groupby(by="dateRep").sum().cases # now let us write a new filtered .csv file covid_df_americas.to_csv("LATAM-JUNE-5-2020-filtered.csv") # filter all dates before Feb 28 # create the threshold date before_date = pd.to_datetime('2020-02-28') # return a new dataframe with dates after Feb 28, 2020 condensed_df_americas = condensed_df_americas[condensed_df_americas.index >= before_date] # write a new .csv file with columns dateRep, condensed_df_americas.to_csv("Condensed.csv") main()
true
c05d8a1ab12e4ba46536fcbc1388c1ce99b990fe
ppppdm/mtcpsoft
/test/sharedMemory_test2.py
892
4.1875
4
# -*- coding:gbk -*- # author : pdm # email : ppppdm@gmail.com # # test shareMemory use import mmap with mmap.mmap(-1, 13) as map: map.write(b'helloworld') map.close() import mmap # write a simple example file with open("hello.txt", "wb") as f: f.write(b"Hello Python!\n") with open("hello.txt", "r+b") as f: # memory-map the file, size 0 means whole file map = mmap.mmap(f.fileno(), 0) # read content via standard file methods print(map.readline()) # prints b"Hello Python!\n" # read content via slice notation print(map[:5]) # prints b"Hello" # update content using slice notation; # note that new content must have same size map[6:] = b" world!\n" # ... and read again using standard file methods map.seek(0) print(map.readline()) # prints b"Hello world!\n" # close the map map.close()
true
407390b8637167b2ee74d8e96907547ac93f358c
iamSubhoKarmakar/Python_Practice
/inheritance.py
463
4.21875
4
class Parent(): def print_last_name(self): print('Bro') class Child(Parent): # we took the details from the parent class that's inheritance def print_first_name(self): print('BroJr') ''' #we gonna understand how to over write the parent last name def print_last_name(self): print('Dude') ''' # remove the ''' and see the real dude brojr = Child() brojr.print_first_name() brojr.print_last_name()
false
9c7870676af46b7a15cdcb2c193a4a3b6a789903
iamSubhoKarmakar/Python_Practice
/abstract-classes.py
788
4.125
4
#abstract classes - can not be instantiated, can only be ingerited, base class #it can not directly creeate an object but the data of this class can only be inherited to a #child clss for in an object #lets do cal salary from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod def calculate_salary(self, sal): pass #lets inherite the abstract class to another class below to cal salary class Developer(Employee): def calculate_salary(self, sal): final_salary = sal * 1.10 return final_salary def position_1(self, position): self.position = position return position emp_1 = Developer() print(emp_1.calculate_salary(10000)) print(emp_1.position_1('Web Developer'))
true
dc30aba7ef2f24014fe1aecfbd7eb7226f272e4a
Tavares-NT/Curso_NExT
/MóduloPython/Extras04.py
803
4.1875
4
'''Faça um programa, com uma função que necessite de uma quantidade de argumentos indefinida, e um argumento de operação dos valores. Esta função deverá returnar o resultado da operação destes valores.''' def soma(valores): resultado = 0 for x in valores: resultado += x return resultado def calculadora(*valores, operacao='soma'): if (operacao=='soma'): return soma(valores) elif (operacao=='multiplicacao'): resultado = 1 for x in valores: resultado *= x return resultado elif (operacao=='divisao'): resultado = 1 for x in valores: resultado /= x return resultado elif (operacao=='subtracao'): resultado = 0 for x in valores: resultado -= x return resultado print(calculadora(1,1,1,4,72,6,operacao='soma'))
false
60910e3586893a7907446f288d24467d6bc58843
Tavares-NT/Curso_NExT
/MóduloPython/Ex44.py
338
4.15625
4
'''Crie um programa que receba um valor inteiro e avalie se ele é positivo ou negativo. Essa avaliação deve ocorrer dentro de uma função que retorna um valor booleano.''' def verificaSinal(): if n > 0: return print("Positivo") else: return print("Negativo") n = int(input("Digite um número inteiro: ")) verificaSinal()
false
ec1e387ffee6638ecc4084d227a4e4946d5ca223
akelkarmit/sample_python
/date_to_day.py
1,210
4.28125
4
print "this program asks for your birthday and tells you the day of the\nweek when you were born" import calendar birthdate=raw_input("enter your birthdate in dd-mm-yyyy format:") #raw_input assumes the input is a string date_of_birth=birthdate.split('-') day_of_birth=int(date_of_birth[0]) month_of_birth=int(date_of_birth[1]) year_of_birth=int(date_of_birth[2]) #print day_of_birth #print month_of_birth #print year_of_birth day_of_week = calendar.weekday(year_of_birth,month_of_birth,day_of_birth) day_mapping_dict = {0:'Monday',1:'Tuesday',2:'Wednesday',3:'Thursday',4:'Friday',5:'Saturday',6:'Sunday'} print "you were born on a ",day_mapping_dict[day_of_week] ##print "****************************" ##if day_of_week == 0: ## print "you were born on a Monday" ##elif day_of_week == 1: ## print "you were born on a Tuesday" ##elif day_of_week ==2: ## print "you were born on a Wednesday" ##elif day_of_week == 3: ## print "you were born on a Thursday" ##elif day_of_week == 4: ## print "you were born on a Friday" ##elif day_of_week == 5: ## print "you were born on a Saturday" ##elif day_of_week == 6: ## print "you were born on a Sunday" ##print "****************************"
true
6176fd13f6bdf06ff6f1a66564d1d5c68b6a93b7
bhavikjadav/Python_Crash_Course_Eric_Matthes_Chapter_8
/8.8_User Album.py
914
4.46875
4
#!/usr/bin/env python # coding: utf-8 # # 8-8. User Albums: Start with your program from Exercise 8-7. Write a while loop that allows users to enter an album’s artist and title. Once you have that information, call make_album() with the user’s input and print the dictionary that’s created. Be sure to include a quit value in the while loop. # In[1]: def make_album(artist, album, songs_no=None): """This function returns the dictionary.""" artist_album = {"artist": artist.title(), "album": album.title()} if songs_no: artist_album["songs_no"] = songs_no return artist_album # In[4]: while True: artist1 = input("Enter the name of an artist : ") if artist1 == "quit": break album1 = input("Enter the name of an album : ") if album1 == "quit": break full_details = make_album(artist1, album1) print(f"{full_details}")
true
3f83c54243c409dbc54082293f92a03ec42cabe8
marahalqaisi/Python-Course
/Week 1/Practice 1-A.py
971
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[17]: #Practice 1-A name = str (input ("Enter your name: ")) num1 = float (input ("Enter the 1st number: ")) num2 = float (input ("Enter the 2nd number: ")) add = float (num1 + num2) sub = float (num1 - num2) multi = float (num1 * num2) div = float (num1 / num2) reminder = int (num1 % num2) exp = float (num1 ** num2) print ("\n") print (f"Hello {name}!") print ("\n") print ("The summation of ", num1 ," and", num2 , "equals ", add ) print ("\n") print ("The subtraction of ", num1 ," and", num2 ,"equals " , sub ) print ("\n") print ("The multiplication of ", num1 , " and", num2 , "equals " , multi ) print ("\n") print ("The division of ", num1, " over", num2 , "equals " , div ) print ("\n") print ("The reminder of division of ", num1, " over", num2 , "equals " , reminder ) print ("\n") print ("The value of ", num1, " rasied to the power of ", num2 , " equals " , exp ) print ("\n") # In[ ]:
false
a6abd5d887e00d0a0b2a4b1b768dc9805d238b61
Danieldevop/Python-examples
/strings.py
234
4.3125
4
# -*- coding:utf -*- my_string = "platzi" my_string[len(my_string)-1] my_string.upper() otro = "EDIFICIO" otro.lower() otro.find("F") cadena = raw_input("digita cadena de text: ") print("el numero de caracteres es: ", len(cadena))
false
2b866761322eea62a1ae60e8df76f28c0eb9132b
Pavan53/Python
/phone_directory.py
789
4.21875
4
# program to create a dictionary with name and mobile numbers phones = {} while True: name = input("Enter name :") if name == "end": break mobile = input("Enter mobile number :") if name in phones: # name is found phones[name].add(mobile) # add new number to existing set else: phones[name] = {mobile} # Add a new entry with name and set # print directory for name, numbers in phones.items(): print(name, numbers) Sample Run ========== Enter name :a Enter mobile number :434343 Enter name :b Enter mobile number :343434343 Enter name :a Enter mobile number :23232 Enter name :b Enter mobile number :23232232 Enter name :c Enter mobile number :343434 Enter name :end a {'23232', '434343'} b {'343434343', '23232232'} c {'343434'}
true
02ab80bea53b59c274ed247a2ea518e91af9da8a
HeyItsFelipe/python_tutorial
/12_if_statements.py
640
4.3125
4
######## If Statements ######## is_male = True if is_male: print("You are a male.") else: print("You are not a male.") is_tall = True if is_male or is_tall: print("You are a male or tall or both.") else: print("You are neither male or tall.") if is_male and is_tall: print("You are a tall male.") else: print("You are either not male or not tall or both.") if is_male and is_tall: print("You are a tall male.") elif is_male and not(is_tall): print("You are a short male.") elif not(is_male) and is_tall: print("You are not a male but are tall.") else: print("You are not male and not tall.")
true
005f339a14302990e4093adebbd0428893e55377
mauroindigne/Python_fundementals
/02_basic_datatypes/1_numbers/02_01_cylinder.py
296
4.25
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. ''' h = 5 r = 3.14 pie = 3.14159265359 volume = (pie * (r ** 2) * h) surface = ((2 * pie * r * h) + (2 * pie * (r ** 2))) print(volume) print(surface)
true
f2ec17a815493ee02a2719a193f13f13072e1dae
mauroindigne/Python_fundementals
/04_conditionals_loops/04_00_star_loop.py
443
4.625
5
''' Write a loop that for a number n prints n rows of stars in a triangle shape. For example if n is 3, you print: * ** *** ''' n = 5 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number of columns # values is changing according to outer loop for j in range(0, i + 1): # printing stars print("* ", end="") # ending line after each row print() # maybe this one
true
e358b650105e95f0ab0a8d3ced40804d66fe7605
Tuzosdaniel12/learningPython
/pythonBasics/if.py
567
4.1875
4
first_name = input("What is your first name? ") print("Hello,", first_name) if first_name == "Daniel": print(first_name, "is learning Python") elif first_name == "Dan": print(first_name, "is learning with fellow student in the community! Me too!") else: #ask if user is under or equal the age of 6 age = int(input("How old are you? ")) if age <= 6: print("Wow you're {} If you are confident in reading already....".format(age)) print("You should learn Python, {}".format(first_name)) print("Have a great day {}".format(first_name))
true
1aa0a846265f753285fd6ba6fde13f5428dd8b8a
Dex4n/algoritmos-python
/CalculoSalario.py
1,143
4.1875
4
#Recebe o valor pago ao trabalhador por hora trabalhada. valor_por_hora=0.0 #Recebe o valor da quantidade de horas trabalhadas pelo trabalhador no mês. numero_horas_trabalhadas=0.0 #Esta variável irá fazer a operação de cálculo (multiplicação) entre a variável valor_por_hora e a variável numero_horas_trabalhadas. calculo_salario=0.0 valor_por_hora=float(input('Quanto você ganha por hora? \n')) numero_horas_trabalhadas=float(input('Diga a quantidade de horas trabalhadas no mês: \n')) #Implementação do cálculo (multiplicação) entre as variáveis valor_por_hora e a variável numero_horas_trabalhadas. calculo_salario = valor_por_hora * numero_horas_trabalhadas INSS=0.08 FGTS=0.11 calculo_inss = calculo_salario * INSS calculo_fgts = calculo_salario * FGTS descontoTotal = calculo_fgts + calculo_inss salarioLiquido = calculo_salario - descontoTotal print('Salário bruto: %.2f' %(calculo_salario)) print('Total de desconto INSS: %.2f' %(calculo_inss)) print('Total de desconto FGTS: %.2f' %(calculo_fgts)) print('Total de descontos: %.2f' %(descontoTotal)) print('Total salário líquido: %.2f' %(salarioLiquido))
false
ce9097e61112db7ffe0aff654197eaf7b5c3b523
thatvictor7/Python-Intro
/chapter7/chp7-solution3.py
1,611
4.5
4
''' Victor Montoya Chapter 7 Solution 3 Fat Gram Calculator 7 July 2019 ''' MULTIPLIER = 9 MIN = 0 TO_PERCENT = 100 LOW_FAT_LIMIT = 29 def main(): print("This program calculates the % of calories from fat in a food,\n" "and signals when a food is low fat.\n", "When asked,...\n", "enter the number of fat grams and calories in the food.\n") obtainFatGrams() def obtainFatGrams(): user_input = float(input('Enter the number of fat grams (not less than 0.0 grams)\n')) while user_input <= MIN: user_input = float(input('Enter the number of fat grams (not less than 0.0 grams)\n')) obtainCalories(user_input) # return user_input def obtainCalories(fat_grams): calories = fat_grams * MULTIPLIER input_string = 'Enter the number of calories (MUST exceed ' + str(calories) + ')\n' user_input = float(input(input_string)) while calories > user_input: user_input = float(input(input_string)) calculateFat(fat_grams, user_input) def calculateFat(fat, calories): fat_percentage = ((fat * MULTIPLIER) / calories) * TO_PERCENT checkLowFat(fat_percentage) def checkLowFat(percent): if percent > LOW_FAT_LIMIT: print('The percentage of fat in this food is ', percent, '%') else: print('This food is considered low fat because the percentage of fat: ', percent, '%, is below 30.0%') restart() def restart(): user_input = str(input("Press 'c' to continue OR 'q' to QUIT\n")) user_input = user_input.lower() if user_input == 'c': obtainFatGrams() elif user_input == 'q': exit() main()
true
3948e50e14e929686ac4bd5be841110740e37e45
thatvictor7/Python-Intro
/chapter5/chp5-solution9.py
1,458
4.25
4
# Victor Montoya # Chapter 5 Solution 9 # Pennies for Pay # Declared constants DAY_ADDITION = 1 PAY_DOUBLER = 2 STARTING_POINT = 1 # Declared variables that will hold input, current pay getting doubles and the addition of salary days = 0 current_pay = .01 running_total = .01 def main(): display_program_and_obtain_days() iterator() def display_program_and_obtain_days(): # Declared days as a global variable global days # Printed purpose of program print("How much money will you earn in a period of time if your starting pay is", " 1 penny on first day and doubles every day") # Value of days global variable will be an integer from user + 1 so the loop iterates from 1 to whatever user inputs days = int(input("Enter Number of Days: ")) + DAY_ADDITION def iterator(): # Print table headers print("Day \t Pay \t\t\t Total") # For loop will iterate from 1 to whatever user entered for day in range(STARTING_POINT,days): # Inserted index into a function calculate_and_display_results(day) def calculate_and_display_results(day_number): # Declared global variables global current_pay global running_total # Printing actual results print(day_number, " \t ",current_pay, " \t \t", running_total) # Doubles current pay value for next loop current_pay = current_pay * PAY_DOUBLER # Added current pay to accumulator running_total += current_pay main()
true
f373e03756c50870dbd58f0ebecf4c85b4fe7d77
thatvictor7/Python-Intro
/chapter5/chp5-solution8.py
933
4.3125
4
# Victor Montoya # Chapter 5 Solution 8 # Celcius to Farenheit Table # Declared constants for celcius to farenheit formula and the number of times t]the loop will be executed FARENHEIT_MULTIPLIER = 1.8 FARENHEIT_ADDITION = 32 MAX_CELCIUS = 21 def main(): iterator() def iterator(): # for loop will iterate from 0 to 21(MAX_CELCIUS) for num in range(MAX_CELCIUS): # pass number of iteration into another method as argument celcius_to_farenheit(float(num)) def celcius_to_farenheit(celcius_temp): # declared local variable that holds the covertion from celcius to farenheit results = (celcius_temp * FARENHEIT_MULTIPLIER) + FARENHEIT_ADDITION # passed results variable and original celcius temp variable to another method as argument display_results(results, celcius_temp) def display_results(farenheit, celcius): # printed the arguments passed print(celcius, " \t ", farenheit) main()
true
a0848d243527fa1cf17542b9c5fc6d1e34a78cfc
maknetaRo/python-exercises
/definition/def3.py
273
4.34375
4
"""3. Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7) Expected Output : -336 """ def multiply_all(lst): total = 1 for num in lst: total *= num return total lst = [8, 2, 3, -1, 7] print(multiply_all(lst))
true
72b912889edb8a0e1491922c0b5afbbe0ac2e1ff
JakeEdm/CP1404Practicals
/prac_05/hex_colours.py
529
4.25
4
"""Hex Colours""" COLOUR_TO_HEX = {"blueviolet": "#8a2be2", "chocolate": "#d2691e", "green": "#00ff00", "hotpink": "#ff69b4", "light": "#eedd82", "lightsalmon": "#ffa07a", "medium": "#66cdaa", "navyblue": "#000080", "pale": "#db7093", "red": "#ff0000"} colour = input("Enter a colour: ").lower() while colour != "": if colour in COLOUR_TO_HEX: print(f'{colour} is {COLOUR_TO_HEX[colour]}') else: print("Invalid choice") colour = input("Enter a colour: ").lower()
false
07f0eabd1a032f5644e2709ed716cfc9adc36341
liwaya29/python
/7_conditions.py
1,122
4.34375
4
x = 2 y = 3 # equality operators print(x == y) z = x == y print(z) print(type(z)) print(x > y) print(x < y) print(x <= y) print(x >= y) pets = [1, 2, 3, "bob"] print(1 in pets) print("bob" in pets) print(4 not in pets) # negation = not if x == y: print("this is false") if x <= y: print("this is true") if x <= y: print("this is true") else: print("this is false") if x == y: print("this is true") else: print("this is false") if x == y and x < y: # false and true = false, t and t = t, f and f = f print("this is true") else: print("this is false") if x == y or x < y: # false or true = true, t or t = t, f or f = f print("this is true") else: print("this is false") """ truth table P Q P^Q (^ = AND) T F F F T F F F F T T T P Q P|Q (| = OR) T F T F T T T T T F F F P !P (! = NOT) T F F T """ if not x == y or not x < y: # not - ang true mafalse, ang false matrue print("this is true") else: print("this is false") if x == y: print("this is true") elif not x < y: print("y is less than x") else: print("this is false")
false
6e03cba810edb3796f2ad6a4a2bd6650b343c946
liuzh825/myAlgorithm
/Algorithm/如何实现栈/ep_02.py
1,545
4.125
4
''' 使用链表实现栈 具体方法 是否为空 栈的大小 栈顶元素 弹栈 压栈 后进先出 ''' class LNode(): def __init__(self, value=None): self.value = value self.next = None class MyStack(): def __init__(self, head=None): self.head = head # 是否为空 def isEmpty(self): return self.head == None or self.head.next == None # 栈的大小 def Size(self): if self.isEmpty(): print('栈为空') return cur = self.head.next i = 0 while cur != None: cur = cur.next i += 1 return i # 栈顶元素 def Top(self): return self.head.next.value # 弹栈 def pop(self): cur = self.head.next self.head.next = cur.next # 压栈 def push(self, v): v = LNode(v) next = self.head.next self.head.next = v v.next = next if __name__ == '__main__': head = LNode() head.next = LNode(1) head.next.next = LNode(2) ms = MyStack(head) if ms.isEmpty(): print('栈为空') else: print('栈不为空') size = ms.Size() print('栈的大小为:', size) topEle = ms.Top() print('栈顶元素', topEle) ms.pop() topEle = ms.Top() print('栈顶元素', topEle) size = ms.Size() print('栈的大小为:', size) ms.push(3) topEle = ms.Top() print('栈顶元素', topEle) size = ms.Size() print('栈的大小为:', size)
false
a323e99def52bd1f33d117695c02bb184c32bcb3
kozhukalov/snippets
/python/insertion_sort.py
321
4.1875
4
def insertion_sort(array): for i in range(1, len(array)): for j in reversed(range(i)): if array[j + 1] < array[j]: array[j], array[j + 1] = array[j + 1], array[j] else: break return array array = [7, 2, 1, 3, 4, 6, 5] print(insertion_sort(array))
false
7db1b5ac4431d1aaeb4594ae6c001f2820814d14
s1s1ty/Learn-Data_Structure-Algorithm-by-Python
/Data Structure/Linked List/linked_list.py
1,548
4.15625
4
class Node: def __init__(self, item, next): self.item = item self.next = next class LinkedList: def __init__(self): self.head = None # Add an item to the head of the linked list def add(self, item): self.head = Node(item, self.head) # Delete the first item of the linked list def remove(self): if self.is_empty(): return None else: item = self.head.item self.head = self.head.next return item # Find and delete an given item def delete(self, item): if not self.is_empty() and self.head.item == item: self.remove() return True else: current = self.head prev = None while current != None: if current.item == item: prev.next = current.next return True prev = current current = current.next return False # Check if the linked list is empty def is_empty(self): return self.head == None # Search for an item in the list def find(self, item): node = self.head while node != None: if node.item == item: return True node = node.next return False # Print all the items in the list def show_all_items(self): print("Items in the list:") node = self.head while node != None: print(node.item) node = node.next
true
893663f7761aa2739091d0bbeac4dadbfc913e88
Billdapart/Py3
/nestedFORLOOPpattern.py
380
4.125
4
# Write a Python program to construct the following pattern, using a nested for loop. # * # * * # * * * # * * * * # * * * * * # * * * * # * * * # * * # * num=5; for star in range(num): for repeat in range(star): print ('* ', end="") print('') for star in range(num,0,-1): for repeat in range(star): print('* ', end="") print('')
true
c6c19165d5a3b173c8f70261bfd76b088e5303f8
wasimusu/Algorithms
/sorting/mergeSort.py
1,409
4.34375
4
""" Implement merge sort using recursion Time complexity O(n*log(n)) Space complexity O(n) """ import random def merge(L, R): """ :param L: sorted array of numbers :param R: sorted array of numbers :return: L and R merged into one """ L = sorted(L) R = sorted(R) output = [] while L or R: # If none of the two lists are empty if L and R: if L[0] > R[0]: num = R.pop(0) else: num = L.pop(0) output.append(num) else: if L: output += L else: output += R break return output def split(array): """ :param array: the array to be splitted into two :return: returns two arrays """ mid = len(array) // 2 L = array[:mid] R = array[mid:] return L, R def merge_sort(array, split_min=20): # Stop recursive splitting if the array has less than split_min elements if array.__len__() >= split_min: L, R = split(array) L = merge_sort(L) R = merge_sort(R) else: L, R = split(array) output = merge(L, R) return output if __name__ == '__main__': array = list(range(60)) random.shuffle(array) sorted_a = merge_sort(array) assert sorted_a == sorted(array) print("Random : ", array) print("Sorted : ", sorted_a)
true
51956ef9a3f2acc307c32feaddb78485acedbf7a
BhosaleAkshay8055/tkinter-examples
/examples/Tuttle/螺旋线绘制.py
304
4.25
4
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # 螺旋线绘制 import turtle import time turtle.speed("fastest") turtle.pensize(2) for x in range(100): turtle.forward(2 * x) # 角度的控制 # 不同的值不同, 绘制的图像会不同 turtle.left(90) time.sleep(3) turtle.done()
false
f2234cb106640a6bcb4bbc2f686292f01495bf9e
Pierina0410/PierinaYasminPalaciosUlloque
/flotante.py
793
4.21875
4
#1-convertir el entero 300 a flotante x=200 a= float (x) print(a,type(a)) #2_convertir el entero 450 a flotante y=450 a=float(y) print(a,type(a)) #3-convertir entero 450 a flotante z=450 a=float(a) print(a,type(z)) #4-convertir la cadena 500 a flotante B="500" a=float(B) print(a,type(a)) #5-convertir la cadena 35039 flotante c="35039" a=float(c) print(a,type(a)) #6-convertir la cadena 31203 a flotante y="31203" a=float(y) print(a,type(a)) #7-convertir el boleano 20<58 en flotante e=20<58 a=float(e) print(a,type(a)) #8-convertir el boleano 44>=35 a flotante f=44>=35 a=float (f) print(a, type(a)) #9_convertir el boleano 99>11 a flotante h=99>11 a=float(h) print(a,type(a)) #10-convertir el entero 543 a flotante k=543 a=float(k) print(a,type (a))
false
7bfa89d3b9a120e66b12658ae499a42a9c5b6e82
TiagoTitericz/chapter2-py4e
/Chapter6/exercise3.py
456
4.125
4
'''Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) ''' def count(word, letter): count = 0 for l in word: if l == letter: count += 1 print(count) word = input("Enter the word: ") letter = input("Enter the letter: ") count(word, letter)
true
66fa6baf13c984638065754b49a5e36b299a8e38
TiagoTitericz/chapter2-py4e
/Chapter6/exercise5.py
536
4.5
4
'''Exercise 5: Take the following Python code that stores a string: str = 'X-DSPAM-Confidence:0.8475' Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.''' #First way str = 'X-DSPAM-Confidence:0.8475' pos = str.find(':') portion = float(str[pos+1:]) print(portion, type(portion)) '''#Second way str = 'X-DSPAM-Confidence:0.8475' portion = float(str[str.find(':')+1:]) print(portion, type(portion))'''
true
e58425d79803ac7c48ddd3f3376cfe660d2b8ad3
TiagoTitericz/chapter2-py4e
/Chapter2/fourth.py
272
4.34375
4
# Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, # and print out the converted temperature. tcelsius = float(input("Enter temp in Celsius: ")) tfahr = (tcelsius * (9 / 5)) + 32 print("Temp in Fahrenheit:", tfahr)
true
9368923c7d8c3c9200b926cb0a759ad33d65b026
DeniZhekova/Python
/uni-Lesson1.py
571
4.15625
4
name = input('What is your name?\n') print ('Hi, %s' , name) age=input("Enter your age: ") print ( "Hmm, " , age , "is a nice age to be...") address = input('What is your address?\n') print ('Probably it is nice to live in %s.' % address ) phoneNumber = input('What is your phone number?\n') print ('Probably I will give you a call on %s.' % phoneNumber ) college = input('What is your college major?\n') print ("Okay," , name , "with a %s" ,college , "degree. It was nice to meet you!" ) print ("Your name is: " + str(len(name)) + " letters long") #DenitsaZhekova
false
c51f7510238e8d65b83540fa0e1d975913ad4b60
a19131100/260201084
/lab7/exercise5.py
532
4.21875
4
password = input("Please enter the password: ") upper_count = 0 lower_count = 0 number_count = 0 if len(password)<8: print("Password is not valid") else: for element in password: if element.isdigit(): number_count += 1 else: if element.isalpha(): if element.isupper(): upper_count += 1 elif element.islower(): lower_count += 1 if (upper_count > 0) and (lower_count>0) and (number_count>0): print("password is valid") else: print("password is not valid")
true
931f3f69d1a04c6dea7df3e5d252c235f28f8ddc
chrddav/CSC-121
/CSC121_Lab02_Lab02_Problem2.py
534
4.125
4
Lab1 = float(input('Enter the score for Lab 1: ')) Lab2 = float(input('Enter the score for Lab 2: ')) Lab3 = float(input('Enter the score for Lab 3: ')) Test1= float(input('Enter the score for Test 1: ')) Test2= float(input('Enter the score for Test 2: ')) LabAverage = (Lab1 + Lab2 + Lab3) / 3 TestAverage = (Test1 + Test2) /2 Course_Grade = (LabAverage*0.55) + (TestAverage*0.45) print('Lab Average:', format(LabAverage, '.2f')) print('Test Average:', format(TestAverage, '.2f')) print('Course Grade:', format(Course_Grade, '.2f'))
true
13b039ed807ac7a7d98cca0fa3cd9c97c3241cf4
chrddav/CSC-121
/CSC121_Lab12_Lab12P2.py
1,480
4.40625
4
print('Converting US Dollar to a foreign currency') def main(): foreign_currency, dollar_amount = get_user_input() currency_calculator(foreign_currency, dollar_amount) def get_user_input(): """Prompts user to determine which currency they want to convert to and how much money they are converting""" foreign_currency = int(input('Enter 1 for Euro, 2 for Japanese Yen, 3 for Mexican Peso: ')) while foreign_currency not in (1, 2, 3): print("Error: Invalid Choice") foreign_currency = int(input('Enter 1 for Euro, 2 for Japanese Yen, 3 for Mexican Peso: ')) dollar_amount = int(input('Enter US Dollar: ')) while dollar_amount < 0: print("US Dollar amount cannot be negative") dollar_amount = float(input('Enter US Dollar: ')) return foreign_currency, dollar_amount def currency_calculator(foreign_currency, dollar_amount): """Imports functions from currency module to determine the amount of foreign currency""" if foreign_currency == 1: from currency import to_euro conversion = to_euro(dollar_amount) print("It is converted to ", conversion, 'Euros') elif foreign_currency == 2: from currency import to_yen conversion = to_yen(dollar_amount) print("It is converted to ", conversion, 'Yen') else: from currency import to_peso conversion = to_peso(dollar_amount) print("It is converted to ", conversion, 'Pesos') main()
true
dd103c6e61ade3def3f8360a013a6089b8691af6
chrddav/CSC-121
/CSC121_Lab03_Lab03P3.py
410
4.28125
4
X = float(input('Enter first number: ')) Y = float(input('Enter second number: ')) Z = float(input('Enter third number: ')) if X > Y and X > Z: print ('The largest number is: ', X) else: if Y > X and Y > Z: print ('The largest number is: ', Y) else: if Z > X and Z > Y: print ('The largest number is: ', Z) else: print ('The largest number is: ', X)
false
67b11455fa9442605617caa1e4d8927b0de22daf
raihanrms/py-practice
/sqr_sum-vs-sum_sqr.py
398
4.21875
4
''' The difference between the squared sum and the sum of squared of first n natural numbers ''' def sum_difference(n=2): sum_of_squares = 0 square_of_sum = 0 for num in range(1, n+1): sum_of_squares += num * num square_of_sum += num square_of_sum = square_of_sum ** 2 return square_of_sum - sum_of_squares print(sum_difference(12))
true
0eeaf290bdaea1e8b28ca1aefa174acb35151313
TiscoDisco/Python-codes
/Collatz Length.py
925
4.28125
4
# collatz_length (n) produces the number of steps that is required to get to one # using the Collatz method # collatz_length: Num -> Num # required: n != float n has to be positive # Examples: collatz_length(2) => 1 # collatz_length(42) => 8 import math import check def collatz_length (n): return length (n, 0) # length(n, counter) uses the counter to count the number of recursions # that happened to get to one and returns the number # length: Num Num -> Num def length (n, counter): if n == 1: return counter else: if n%2 == 0: n = n/2 return length (n, counter+1) else: n = 3 * n + 1 return length (n, counter+1) # Testing for length(n, counter): check.expect("Test1", collatz_length(2), 1) check.expect("Test2", collatz_length(42), 8) check.expect("Test3", collatz_length(300), 16)
true
e52d780ec9dd8967ec05ae1cd5ec39bcc8b70114
TiscoDisco/Python-codes
/Check by Queen.py
2,075
4.125
4
## check_by_queen (queen_pos, king_pos) prduces "Check!!!" if king's position can be ## attacked by the queen. Queen can moving infinite positions horizontally, vertically ## diagonally ## check_by_queen: Str Str -> None ## print (anyof "Check!!!" nothing) ## Required: queen_pos and king_pos = (anyof A to H) + (anyof 1 to 8) #Examples: check_by_queen ("E6", "A2") -> "Check!!!" # check_by_queen ("F2", "C2") -> "Check!!!" # check_by_queen ("A1", "H7") -> nothing import check def check_by_queen (queen_pos, king_pos): if (queen_pos[0] == king_pos[0]): return (print("Check!!!")) elif (queen_pos[1] == king_pos[1]): return (print ("Check!!!")) elif ((abs(int((converter(queen_pos))[0])) - (int((converter(king_pos))[0]))) == (abs(int((converter(queen_pos))[1])) - (int((converter(king_pos))[1])))): return (print("Check!!!")) ## converter (pos) changes a string position vlaue in a different way ## A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8 ## converter: Str -> Str def converter (pos): if (pos[0] == "A"): return ("1" + pos[1]) elif (pos[0] == "B"): return ("2" + pos[1]) elif (pos[0] == "C"): return ("3" + pos[1]) elif (pos[0] == "D"): return ("4" + pos[1]) elif (pos[0] == "E"): return ("5" + pos[1]) elif (pos[0] == "F"): return ("6" + pos[1]) elif (pos[0] == "G"): return ("7" + pos[1]) elif (pos[0] == "H"): return ("8" + pos[1]) #Testing for check_by_queen(queen_pos, king_pos): check.set_screen("Check!!!") check.expect("TEST1", check_by_queen("E6", "A2"), None) check.set_screen("Check!!!") check.expect("TEST2", check_by_queen("F2", "C2"), None) check.expect("TEST3", check_by_queen("A1", "H7"), None) check.set_screen("Check!!!") check.expect("TEST4", check_by_queen("F2", "F3"), None) check.expect("TEST5", check_by_queen("F2", "G4"), None)
true
fabbf7c356274e3deebe666c50592d92610d889c
JetimLee/DI_Bootcamp
/pythonlearning/week1/listsMethods.py
724
4.15625
4
basket = [1, 2, 3, 4, 5] print(len(basket)) basket.append('hello') print(basket) basket.pop() print(basket) basket.insert(3, 'gavin') # here insert takes the index and then the thing you want to insert # list methods do not give a new list, they just change the list # this means you cannot reassign the changed list to a new list print(basket) # append mutates the list in place - it doesn't produce a value, not like slicing # removing methods itemToGive = basket.pop(0) # pops at the index # can be reassigned to a new list - pop returns whatever you have just removed print(basket) print(itemToGive) basket.remove('gavin') print(basket) # here you give the value you want to remove basket.clear() print(basket)
true
f2004af1ad010067a47f3489ffa5b485bbe918ea
JetimLee/DI_Bootcamp
/pythonlearning/week1/tuples.py
260
4.25
4
# A tuple is like a list, but you cannot modify them - they're immutable my_tuple = (1, 2, 3, 4, 5) # my_tuple[1] = 'z' can't do this print(my_tuple[1]) print(4 in my_tuple) new_tuple = my_tuple[1:2] print(new_tuple) # only has 2 methods - count and index
true
471ce224eae83b54bb1430ee2779d7a02a1d324d
ValentinaKelly/Fundamentos_informatica
/Tp2.py/Ejercicio3.py
436
4.1875
4
#Escribí un programa que dado un número # del 1 al 6, ingresado por teclado, # muestre cuál es el número que está en la # cara opuesta de un dado. Si el número es # menor a 1 y mayor a 6 se debe mostrar un # mensaje indicando que es incorrecto el número ingresado. numero = int(input("ingrese un numero del 1 al 6:")) if numero >=1 and numero <=6: print(7 - numero) else: print("el numero ingresado es incorrecto")
false
91882bc96685253a25b283c7744a8a43b20981d0
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Udemy/colecoes/tuplas/Exercicios/exe02.py
303
4.3125
4
'''Exercício02 - Escreva um programa que receba do usuário o tamanho de uma tupla e seus respectivos itens''' r = int(input('qual o tamanho da sua tupla+')) tupla = range(r) tuplex = () for i in tupla: a = int(input('Digite um item para a sua tupla\n')) tuplex = tuplex + (a,) print(tuplex)
false
044b162288a9ed08502b6dba05c38fb116111f3b
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Pense_em_Python/cap02/Exercicio_02-2-1.py
394
4.34375
4
# Pratique o uso do interpretador do Python como uma calculadora # 1. O volume de uma esfera com raio r é de 4/3 pi r ^ 3. # Calcule o volume de uma esfera em que o raio é dado pelo usuário # dica: 1 metro cúbico = 1000 litros raio = float(input("digite o valor do raio\n")) volume = (4 * 3.14 * (raio ** 3))/3 print(f'{volume:.2f} metros cúbicos ou {volume * 1000:2.3f} litros') # 2.
false
8e8eb256191f0f58bb08a672b23337919db8d55f
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap07/Exercicio_07-06.py
689
4.15625
4
""" Escreva um programa que leia três strings. Imprima o resultado da substituição na primeira, dos caracteres da segunda pelos da terceira. """ string1 = input("Digite a primeira String") string2 = input("Digite a segunda String") string3 = input("Digite a terceira String") if len(string2) == len(string3): resultado = "" for i in string1: posicao = string2.find(i) if posicao != -1: resultado += string3[posicao] else: resultado += i if resultado == " ": print("Todos os caracteres foram removidos") else: print(f'{resultado}') else: print("A segunda e a terceira Strings devem ter o mesmo tamanho")
false
0095d6b7437be4309a964d7e13e4b323dfc803e4
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap07/Exercicio_07-02.py
329
4.125
4
""" * Escreva um programa que leia duas strings e gere uma terceira com * os caracteres comuns às duas strings lidas. """ string1 = input("Insira a primeira String ") string2 = input("Insira a segunda String ") L =[] for i in string1: for j in string2: if i == j: L.append(i) print(f'{", ".join(L)}')
false
097613cf683631893c17cd6fee257791908d046f
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap05/Exercicio_05-22.py
1,051
4.1875
4
""" Escreva um programa que exiba uma lista de opções(menu): adição, subtração, divisão, multiplicação e sair. Imprima a tabuada da operação escolhida. Repita até que a opção saída seja escolhida. """ while True: print("Escolha a opção equivalente a operação desejada") opcao = int(input(''' ADIÇÃO = 1 SUBTRAÇÃO = 2 DIVISÃO = 3 MULTIPLICAÇÃO = 4 SAÍDA = 5 ''')) if opcao == 5: break elif opcao >= 1 and opcao < 5: num = int(input("Qual tabuada deseja resolver?" )) tabuada = 1 while tabuada <=10: if opcao == 1: print(f'{num} + {tabuada} = {num + tabuada}') elif opcao == 2: print(f'{num} - {tabuada} = {num - tabuada}') elif opcao == 3: print(f'{num} / {tabuada} = {num / tabuada}') elif opcao == 4: print(f'{num} * {tabuada} = {num * tabuada}') tabuada +=1 else: print("a opção digitada não é válida")
false
8aa1345b44241869ed8e8a6770e5a187d5e9d607
timetoady/pythonBits1
/cipher_text2.py
306
4.25
4
plain_text = input("Enter a message: ") distance = int(input("Enter the distance value: ")) code = "" for ch in plain_text: ordvalue = ord(ch) cipher_value = ordvalue + distance if cipher_value > ord('~'): cipher_value = ord(' ') + distance - 1 code += chr(cipher_value) print(code)
false
b1c34dfcd2f1c0ccedc19b71f18f56d8868a6543
jeffclough/handy
/patch-cal
2,605
4.34375
4
#!/usr/bin/env python3 import argparse,os,sys from datetime import date,timedelta def month_bounds(year,month): """Return a tuple of two datetime.date instances whose values are the first and last days of the given month.""" first=date(year,month,1) if month==12: last=date(year+1,1,1) else: last=date(year,month+1,1) last-=timedelta(1) return (first,last) def counted_week_day(year,month,nth,day_of_week): """Return a datetime.date object expressing the nth day_of_week in the given year and month. Year and month are simply the numbers of the year and month in question. nth is an integer from 1 to 5. day_of_week is 0 (for Monday) through 6 (for Sunday). So counted_week_day(2018,10,2,1) returns datetime.date(2018,10,9) because that is the 2nd tuesday in October of 2018. If the nth day_of_week of the given year and month does not exist, a value of None is returned. """ # Get the first and last days of the given month. first,last=month_bounds(year,month) # Compute the position within the month of the nth day_of_week in the # given month. first_day=first.weekday() nth_day=7*(nth-1)+((day_of_week-first_day+7)%7)+1 if nth_day<=last.day: result=date(year,month,nth_day) else: result=None return result def show_patch_groups(year,month): """Send the calendar for the given month to standard output.""" # Make a (day number)->(day name) dictionary that numbers ordinary # days but assigns patch group names to our "Patch Thursdays." For # the sake of algorithmic regularity, we also need "blank" days # before the first day of the month. first,last=month_bounds(year,month) days=dict([ (d,'%2d'%d) for d in range(first.day,last.day+1) ]) pt=counted_week_day(year,month,2,1) # Microsoft's "Patch Tuesday." days[(pt+timedelta(2)).day]=' A' days[(pt+timedelta(9)).day]=' B' days[(pt+timedelta(16)).day]=' C' days[(pt+timedelta(21)).day]=' D' days.update(dict([(d,' ') for d in range(0,-6,-1)])) # Write the heading for this month's calendar. print(first.strftime('%B').center(21)) first_sunday=counted_week_day(year,month,1,6) print(' '.join([d.strftime('%A')[:2] for d in [first_sunday+timedelta(dd) for dd in range(7)]])) # Write the body of the this month's calendar. skip_days=(first.weekday()+1)%7-1 day_list=[days[d] for d in range(-skip_days,last.day+1)] while day_list: print(' '.join(day_list[:7])) del day_list[:7] print() for month in range(12): show_patch_groups(2019,month+1) #for month in range(12): # print counted_week_day(2018,month+1,2,1)
true
b30026b349867c47c5b5b3624b8445847228de29
AbhinavAshish/ctci-python
/Data Structures/solution1_2.py
499
4.28125
4
#Implement a function which reverses a string #Approach use a temporary variable and replace. Solution in n def reverseString (inputStr) : inputString= list(inputStr) for index in range(0,len(inputString)/2): temp = inputString[index] inputString[index]= inputString[len(inputString)-1-index] inputString[len(inputString)-1-index] = temp inputStr ="".join(inputString) print inputStr return #inputString = "" inputString= raw_input("Enter the String :") reverseString(inputString)
true
bb56d7c2c701f8a8526438cc68f97078a9bb2b66
smksevov/Grokking-the-coding-interview
/two pointers/comparing strings containing backspaces.py
1,397
4.3125
4
# Given two strings containing backspaces (identified by the character ‘#’), # check if the two strings are equal. # Example: # Input: str1="xy#z", str2="xzz#" # Output: true # Explanation: After applying backspaces the strings become "xz" and "xz" respectively. # O(M+N) where ‘M’ and ‘N’ are the lengths of the two input strings respectively. # space:O(1) def comparing_string_contain_backspaces(str1, str2): pointer1, pointer2 = len(str1) - 1, len(str2) - 1 while pointer1 >= 0 and pointer2 >= 0: i1 = get_next_valid_index(str1, pointer1) i2 = get_next_valid_index(str2, pointer2) if i1 < 0 and i2 < 0: return True if i1< 0 or i2 < 0: return False if str1[i1] != str2[i2]: return False pointer1 = i1 - 1 pointer2 = i2 - 1 return True def get_next_valid_index(str, index): backspace_count = 0 while index >= 0: if str[index] == '#': backspace_count += 1 elif backspace_count > 0: backspace_count -= 1 else: break index -= 1 return index print(comparing_string_contain_backspaces("xy#z", "xzz#")) print(comparing_string_contain_backspaces("xy#z", "xyz#")) print(comparing_string_contain_backspaces("xp#", "xyz##")) print(comparing_string_contain_backspaces("xywrrmp", "xywrrmu#p"))
true
4958f912d9d158a4bec20790b7d608a9c018f68a
smksevov/Grokking-the-coding-interview
/bitwise XOR/two single numbers.py
771
4.15625
4
# In a non-empty array of numbers, every number appears exactly twice except two numbers that appear only once. # Find the two numbers that appear only once. # Example 1: # Input: [1, 4, 2, 1, 3, 5, 6, 2, 3, 5] # Output: [4, 6] # Input: [2, 1, 3, 2] # Output: [1, 3] # O(N) space: O(1) def find_two_single_numbers(arr): n1xn2 = 0 for num in arr: n1xn2 ^= num rightmost_set_bit = 1 while rightmost_set_bit & n1xn2 == 0: rightmost_set_bit <<= 1 num1, num2 = 0, 0 for num in arr: if num & rightmost_set_bit == 0: num1 ^= num else: num2 ^= num return [num1, num2] print(find_two_single_numbers([1, 4, 2, 1, 3, 5, 6, 2, 3, 5])) print(find_two_single_numbers([2, 1, 3, 2]))
true
d3ea31721c808160ccb18f5b5f7616d0399927ff
Oroko/python-project
/pay.py
428
4.1875
4
# A program to prompt the user for hours and rate per hour to compute gross pay hours = input('Enter Hours:') hourly_rate = input('Enter Hourly Rate:') overtime_hrs = input('Enter Overtime hours:') regular_pay = float(hours) * float(hourly_rate) if float(overtime_hrs)==0: print(regular_pay) elif float(overtime_hrs)>0: print(regular_pay + (float(hourly_rate)*1.5*float(overtime_hrs) )) print("Thank you for your work!")
true
cda5bd086248bd8cb906e6a7f7af16d0cdc98b2c
bretonne/workbook
/src/Chapter6/ex128.py
1,404
4.53125
5
# Exercise 128: Reverse Lookup # (Solved—40 Lines) # Write a function named reverseLookup that finds all of the keys in a dictionary # that map to a specific value. The function will take the dictionary and the value to # search for as its only parameters. It will return a (possibly empty) list of keys from # the dictionary that map to the provided value. # Include a main program that demonstrates the reverseLookup function as part # of your solution to this exercise. Your program should create a dictionary and then # show that the reverseLookup function works correctly when it returns multiple # keys, a single key, and no keys. Ensure that your main program only runs when # the file containing your solution to this exercise has not been imported into another # program. def getInputs(): flightMarkets = {} line = input() while line != "" : tokens = line.split(",") if (len(tokens)==2): flightMarkets[tokens[0]] = tokens[1] line = input() return flightMarkets def findFlightsForMarket(connection, flightMarkets): flights = [] for flight, market in flightMarkets.items(): if (connection==market): flights.append(flight) return flights def main(): flightMarkets = getInputs() connection = input("Connection:") flights = findFlightsForMarket(connection, flightMarkets) print(flights) main()
true
fb5f09e30b07839d8dc63a0a28eb89ce1372e85c
bretonne/workbook
/src/Chapter6/ex136.py
1,305
4.1875
4
# Exercise 136:Anagrams Again # (48 Lines) # The notion of anagrams can be extended to multiple words. For example, “William # Shakespeare” and “I am a weakish speller” are anagrams when capitalization and # spacing are ignored. # 66 6 Dictionary Exercises # Extend your program from Exercise 135 so that it is able to check if two phrases # are anagrams. Your program should ignore capitalization, punctuation marks and # spacing when making the determination. def isAnagrams(word1, word2): letterMap = {} for letter in word1: if letter in letterMap: letterMap[letter] += 1 else: letterMap[letter] = 1 for letter in word2: if letter in letterMap: letterMap[letter] -= 1 else: return False for count in letterMap.values(): if count > 0: return False return True def trim(word:str): trimmed = [] for letter in word: if (letter.isalpha()): trimmed.append(letter.lower()) wholeword = "".join(trimmed) print(wholeword) return wholeword def main(): word1 = input("sentence 1:") word2 = input("sentence 2:") trimmed1=trim(word1) trimmed2 = trim(word2) print("Is Anagrams:", isAnagrams(trimmed1, trimmed2)) main()
true
95be2a49b9ada465c8495de39c0149eb490d6699
covcom/122COM_sorting_algorithms
/lab_sorting.py
2,636
4.15625
4
#!/usr/bin/python3 def bubble_sort( sequence ): # COMPLETE ME - Green task return sequence def selection_sort( sequence ): # COMPLETE ME - Yellow task return sequence def quick_sort( sequence ): # COMPLETE ME - Yellow task return sequence def quick_sort_inplace( sequence, start=None, end=None ): # COMPLETE ME - Red task return sequence def merge_sort( sequence ): # COMPLETE ME - Red task return sequence if __name__ == '__main__': import random, copy, sys class Test(object): def __init__(self, n, f ): self.name = n self.function = f self.success = False sortingAlgorithms = [ Test('bubblesort', bubble_sort), Test('selection sort', selection_sort), Test('quicksort', quick_sort), Test('quick inplace', quick_sort_inplace), Test('merge sort', merge_sort)] # ============================================== # This is the small collection of numbers test # ============================================== # generate 10 random numbers between -100 and 100 so we can see that it's working smallNumbers = [ random.randint(-100,100) for i in range(10) ] # print out the small numbers print( 'SMALL SEQUENCE TEST' ) print( 'starting numbers:', smallNumbers ) # sort the small numbers smallCorrect = sorted( smallNumbers ) print( 'correctly sorted:', smallCorrect ) for test in sortingAlgorithms: result = test.function( copy.copy(smallNumbers) ) print( '%s:' % test.name.rjust(16), result ) # record if the test was a success test.success = result == smallCorrect for test in sortingAlgorithms: print( test.name, "worked" if test.success else "failed" ) print() # ============================================== # This is the big collection of numbers test # ============================================== # generate 5000 random numbers so we can profile our code bigNumbers = [ random.random() for i in range(5000) ] print( 'BIG SEQUENCE TEST' ) # sort the big numbers bigCorrect = sorted( bigNumbers ) for test in sortingAlgorithms: if not test.success: continue result = test.function(bigNumbers) test.sucess = result == bigCorrect for test in sortingAlgorithms: print( test.name, "worked" if test.success else "failed" ) sys.exit( len([ test for test in sortingAlgorithms if test.success ]) )
true
30718fec059ba9171c0a3118afe7035976d9dd48
pythonmentor/johann-session-20190320
/input.py
402
4.1875
4
def int_input(message, min, max): """Asks user to enter an integer between min and max.""" while True: n = input(message) if n.isdigit(): n = int(n) else: continue if min <= n <= max: return n user_input = int_input("Entrez un nombre entre 10 et 20: ", 10, 20) print("L'utilisateur a choisi le nombre:", user_input)
false
61d5bc282770b82855ad904bc889e1eb64d09087
pranayvwork/mypy
/stringsDemo.py
775
4.25
4
message = 'My Wolrd' print(message) #apostrophe myString = "Cat's world" print(myString) #multi line string literal longString = """This is a multi line string spanning to the second line. """ print(longString) #find the length of string print(len(myString)) #upper or lower print(myString[6:].upper()) #count method print(myString.count('r')) #replace method print(myString.replace('Cat\'s', 'Bobby\'s')) print(myString) greeting = "hello" name = "john" #concat string message = greeting + ", " + name print(message) #formatted string message = '{}, {}. Welcome!'.format(greeting, name) print(message) #using formatting with f strings message = f'{greeting}, {name.upper()}. Welcome!' print(message) #find what all methods can be applied on a variable print(dir(message))
true
53d6b7d3dfd2f467ac972b119af3fbd40a4e64db
BhagyashreeKarale/more-exercise
/cipher2.0.py
1,951
4.1875
4
# Cipher 2.0 # Encrypt function ek message input leta hai aur firr uss message ko encrypt karta hai. # Encrypt karne ke liye yeh har character ko 3 character aage wale character se change kar deta hai. # Aisa karne ke liye yeh har character ki ascii value ko 3 se increase kar deta hai. # Jaise: v ki ASCII value 118 hai, agar hum isse 3 se increase kar de tab yeh 121 ho jayegi. # Jo ki 'y' ki ascii value hai. ASCII value nikalne ke liye hum ord() ka use karte hai. # Aur ascii value ko string mei convert karne ke liye chr function ka use karte hai. # Jaise: ascii_value = ord("b")+3 # 118 print(ascii_value) string_value = chr(ascii_value) # v print(string_value) # Decrypt function encrypt function ka ultaa hai. # Yeh value ko 3 se incresae karne ki jagah 3 se kam kar deta hai. # Topics covered # semantic/syntactic problems in if/else # problems in while loop # def encrypt(message): # encrypt_message="" # message=list(message) # for i in message: # ascii_message = [ord(char)+3 for char in message] # encrypt_message = [ chr(char) for char in ascii_message] # print (''.join(encrypt_message)) # def decrypt(): # ascii_message = [ord(char) for char in message] # decrypt_message = [ chr(char) for char in ascii_message] # print (''.join(decrypt_message)) # flag = True # while flag == True: # choice = input("What do you want to do? \n1. Encrypt a message 2. Decrypt a message \nEnter 'e' or 'd' respectively!:\n") # message = input("Enter your message:\n") # if choice == 'e': # encrypt(message) # play_again = input("Do you want to try agian?(y/n):\n") # if play_again == 'y': # continue # else: # break # elif choice == 'd': # decrypt(message) # play_again = input("Do you want to play again? (y/n)") # if play_again == 'y': # continue # else: # break
false
592c5a195ee4892d0f59525431184e53b40c7d54
Muhammad-Salman-Hassan/Python_Basic
/DSA_2.py
2,315
4.1875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Structure to store node pair onto stack class snode: def __init__(self, l, r): self.l = l self.r = r ''' Helper function that allocates a new node with the given data and None left and right pointers. ''' def newNode(data): new_node = Node(data) return new_node ''' Given a binary tree, print its nodes in inorder''' def inorder(node): if (not node): return; ''' first recur on left child ''' inorder(node.left); ''' then print the data of node ''' print(node.data, end=' '); ''' now recur on right child ''' inorder(node.right); ''' Function to merge given two binary trees''' def MergeTrees(t1, t2): if (not t1): return t2; if (not t2): return t1; s = [] temp = snode(t1, t2) s.append(temp); n = None while (len(s) != 0): n = s[-1] s.pop(); if (n.l == None or n.r == None): continue; n.l.data += n.r.data; if (n.l.left == None): n.l.left = n.r.left; else: t=snode(n.l.left, n.r.left) s.append(t); if (n.l.right == None): n.l.right = n.r.right; else: t=snode(n.l.right, n.r.right) s.append(t); return t1; # Driver code if __name__=='__main__': ''' Let us construct the first Binary Tree 1 / \ 2 3 / \ \ 4 5 6 ''' root1 = newNode(1); root1.left = newNode(2); root1.right = newNode(3); root1.left.left = newNode(4); root1.left.right = newNode(5); root1.right.right = newNode(6); root2 = newNode(4); root2.left = newNode(1); root2.right = newNode(7); root2.left.left = newNode(3); root2.right.left = newNode(2); root2.right.right = newNode(6); root3 = MergeTrees(root1, root2); print("The Merged Binary Tree is:"); inorder(root3)
true
16526d38dbdc2ee31a40de3dbdf48362aac10d36
gokadroid/Python3Examples
/applesOranges.py
2,022
4.1875
4
#!/bin/python3 import math import os import random import re import sys # Complete the countApplesAndOranges function below. def countApplesAndOranges(s, t, a, b, apples, oranges): applesCount=0 orangeCount=0 for i in range(0,len(apples)): if apples[i] > 0 and apples[i]+a >= s and apples[i]+a<=t: applesCount+=1 for i in range(0,n): if oranges[i] < 0 and oranges[i]+b >= s and oranges[i]+b<=t: orangeCount+=1 print(applesCount) print(orangeCount) if __name__ == '__main__': st = input().split() s = int(st[0]) t = int(st[1]) ab = input().split() a = int(ab[0]) b = int(ab[1]) mn = input().split() m = int(mn[0]) n = int(mn[1]) apples = list(map(int, input().rstrip().split())) oranges = list(map(int, input().rstrip().split())) countApplesAndOranges(s, t, a, b, apples, oranges) #Sam's house has an apple tree and an orange tree that yield an abundance of fruit. In the diagram below, the red region denotes his house, where is the start point, and is the endpoint. The #apple tree is to the left of his house, and the orange tree is to its right. You can assume the trees are located on a single point, where the apple tree is at point , and the orange tree is at #point . #When a fruit falls from its tree, it lands units of distance from its tree of origin along the -axis. A negative value of means the fruit fell units to the tree's left, and a positive value of #means it falls units to the tree's right. #Given the value of for apples and oranges, determine how many apples and oranges will fall on Sam's house (i.e., in the inclusive range )? #For example, Sam's house is between and . The apple tree is located at and the orange at . There are apples and oranges. Apples are thrown units distance from , and units distance. Adding #each apple distance to the position of the tree, they land at . Oranges land at . One apple and two oranges land in the inclusive range
false
ac18bb5814d50470d24a021c012c39f6cce5e813
judecafranca/PYTHON
/PALINDROME.py
318
4.3125
4
def isPalindrome(): string = input('Enter a string: ') string1 = string[::-1] if string[0] == string[(len(string)-1)]\ and string[1:(len(string)-2)] == string1[1:(len(string)-2)]: print('It is a palindrome') else: print('It is not a palindrome') isPalindrome()
true
48a33d647557269a36e6e6508f2921bba66f0b76
arnjr1986/Curso-Python-3
/ex_039_Alistamento.py
795
4.15625
4
"""LER O ANO DE NASC. DE UM JOVEM E INFORMAR: - SE AINDA VAI SE ALISTAR AO SERVIÇO MILITAR - SE É A HORA DE SE ALISTAR - SE JA PASSOU O TEMPO DE ALISTAMENTO -MOSTRAR QUANTO TEMPO FALTA OU QUE PASSOU DO PRAZO""" from datetime import date nasc = int(input('Digite o ano de Nascimento: ')) alist = int(18) ano = date.today().year if ano - nasc == alist: print('Você tem {}anos'.format(ano-nasc)) print('Você deve se alistar este ano') elif ano - nasc < alist: print('Você tem {}anos'.format(ano - nasc)) print('Você não precisa se alistar ainda faltam {} anos'.format(alist - (ano-nasc))) elif ano - nasc > alist: print('Você tem {}anos'.format(ano - nasc)) print('Já passou o prazo de alistamento há {} anos '.format((ano-nasc) - alist))
false
da112b4679ad6e09910ecd900df4d153a4f4b7a2
arnjr1986/Curso-Python-3
/ex_026_conta_Posiçao.py
536
4.25
4
"""Ler uma frase e mostrar quantas vezes aparece a letra 'a' em que posição ela aparece a primeira vez e em qual posição ela aparece pela ultima vez""" frase = str(input('Digite uma frase: ')).upper().strip()#Maiusculas e sem espaços print('A letra *A* aparece {} vezes na frase.'.format(frase.count('A')))#count conta print('A primeira letra *A* apareceu na posição {}.'.format(frase.find('A')+1))#+1 p/ adequar print('A última letra *A* apareceu na posição {}.'.format(frase.rfind('A'))+1)#Começa da direita
false
62697abe7952f1da294fa61d81e77fc3b08721c9
arnjr1986/Curso-Python-3
/ex_009_tab.py
563
4.15625
4
#Tabuada num = int(input('Digite um numero para ver sua tabuada: ')) print('-'*12) print('{} x {:2} = {}'.format(num, 1,num*1)) print('{} x {:2} = {}'.format(num, 2,num*2)) print('{} x {:2} = {}'.format(num, 3,num*3)) print('{} x {:2} = {}'.format(num, 4,num*4)) print('{} x {:2} = {}'.format(num, 5,num*5)) print('{} x {:2} = {}'.format(num, 6,num*6)) print('{} x {:2} = {}'.format(num, 7,num*7)) print('{} x {:2} = {}'.format(num, 8,num*8)) print('{} x {:2} = {}'.format(num, 9,num*9)) print('{} x {} = {}'.format(num, 10,num*10)) print('-'*12)
false
ef431b986c659ee6943577f8606b75db0ca1e8d5
leonardotdleal/python-basic-course
/primitive-variables/primitive-variables.py
428
4.15625
4
# PRIMITIVE VARIABLES IN PYTHON # # String name = 'Leonardo Leal' # Integer age = 25 # Float height = 1.68 # Boolean student = True print(name) print(age) print(height) print(student) # None (is similar to null in others languages) working = None print(working) # OPERATIONS # new_age = age + 2 name_and_city = name + ' Joinville' print(new_age) print(name_and_city) height_with_cap = height + 0.023 print(height_with_cap)
true
a2b927ab8854238ee6c16fbcc6dd94f6a6869c27
krishnapratapmishra/PythonScripts
/bitwise.py
333
4.125
4
#Manipulating Bits """ | OR & AND ~ NOT ^ XOR << Shift Left >> Shift Right """ #Swap the values without third variable a=10 b=5 print('a =' ,a ,'\tb =',b) #1010 ^ 0101 = 1111 (decimal 15) a=a^b #1111 ^ 0101 = 1010 (decimal 10) b= a^b #1111 ^ 1010 = 0101 a=a^b print('a=',a,'\tb=',b)
false