blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1af15c312f75e507b4acb77abc76b25ff8022318
hackettccp/CIS106
/SourceCode/Module5/returning_data1.py
815
4.15625
4
""" Demonstrates returning values from functions """ def main() : #Prompts the user to enter a number. Assigns the user's #input (as an int) to a variable named num1 num1 = int(input("Enter a number: ")) #Prompts the user to enter another number. Assigns the user's #input (as an int) to a variable named num2 num2 = int(input("Enter another number: ")) #Passes the num1 and num2 variables as arguments to the printsum #function. Assign the value returned to a variable called total total = printsum(num1, num2) #Prints the value of total print("The total is", total) #A function called printsum that accepts two arguments. #The function adds the arguments together and returns the result. def printsum(x, y) : #Returns the sum of x and y return x + y #Calls main function main()
true
c359aae7e1cd194eedb023b580f34e42b7663c27
hackettccp/CIS106
/SourceCode/Module2/mixed_number_operations.py
1,699
4.46875
4
""" Demonstrates arithmetic with mixed ints and floats. Uncomment each section to demonstrate different mixed number operations. """ #Example 1 - Adding ints together. #Declares a variable named value1 and assigns it the value 10 value1 = 10 #Declares a variable named value2 and assigns it the value 20 value2 = 20 #Declares a variable named total1 #Assigns the sum of value1 and value2 to total1 #total1's data type will be int total1 = value1 + value2 #Prints the value of total1 print(total1) #********************************# print() #Example 2 - Adding a float and int together """ #Declares a variable named value3 and assigns it the value 90.5 value3 = 90.5 #Declares a variable named value4 and assigns it the value 40 value4 = 20 #Declares a variable named total2 #Assigns the sum of value3 and value3 to total2 #total2's data type will be float total2 = value3 + value4 #Prints the value of total2 print(total2) """ #********************************# print() #Example 3 - Adding floats together """ #Declares a variable named value5 and assigns it the value 15.6 value5 = 15.6 #Declares a variable named value6 and assigns it the value 7.5 value6 = 7.5 #Declares a variable named total3 #Assigns the sum of value5 and value6 to total3 #total3's data type will be float total3 = value5 + value6 #Prints the value of total3 print(total3) """ #********************************# print() #Example 4 - Multiple operands """ #Declares a variable named result #Assigns the sum of total1, total2, and total3 to result #result's data type will be float (int + float + float = float) result = total1 + total2 + total3 #Prints the value of result print(result) """
true
188486bfabc4f36413579d6d1af0aaae3da63681
hackettccp/CIS106
/SourceCode/Module10/entry_demo.py
504
4.125
4
#Imports the tkinter module import tkinter #Main Function def main() : #Creates the window test_window = tkinter.Tk() #Sets the window's title test_window.wm_title("My Window") #Creates an entry field that belongs to test_window test_entry = tkinter.Entry(test_window, width=10) #Packs the entry field onto the window test_entry.pack() #Enters the main loop, displaying the window #and waiting for events tkinter.mainloop() #Calls the main function/starts the program main()
true
6e470e6f8219a39ebdb2b862ea9bf85c7710c576
alexbehrens/Bioinformatics
/rosalind-problems-master/alg_heights/FibonacciNumbers .py
372
4.21875
4
def Fibonacci_Loop(number): old = 1 new = 1 for itr in range(number - 1): tmpVal = new new = old old = old + tmpVal return new def Fibonacci_Loop_Pythonic(number): old, new = 1, 1 for itr in range(number - 1): new, old = old, old + new return new print(Fibonacci_Loop(13)) print(Fibonacci_Loop_Pythonic(13))
true
5af688c66904d3d6b0ad57fbb008c93d2797ddd8
alexeahn/UNC-comp110
/exercises/ex06/dictionaries.py
1,276
4.25
4
"""Practice with dictionaries.""" __author__ = "730389910" # Define your functions below # Invert function: by giving values, returns a flip of the values def invert(first: dict[str, str]) -> dict[str, str]: """Inverts a dictionary.""" switch: dict[str, str] = {} for key in first: value: str = first[key] switch[value] = key return switch # Favorite color: sort different colors based on what people like the most def favorite_color(colors: dict[str, str]) -> str: """Gives the most frequently listed color.""" favorite: str = "" for key in colors: value: str = colors[key] favorite = value return favorite # Count: shows how many times a certain key was given def count(find: list[str]) -> dict[str, int]: """Counts how many times a string is presented.""" i: int = 0 final: dict[str, int] = {} while i < len(find): key = find[i] if key in final: final[key] += 1 else: final[key] = 1 i += 1 return final f: str = "blue" g: str = "silver" h: str = "gold" link: list[str] = ["fish", "bird", "dog", "fish"] print(invert({g: f})) print(favorite_color({"Alex": f, "Jeff": f, "Joe": g})) print(count(link))
true
43fff8b5123088e2fa7416157b729b0ddb3542a8
cassjs/practice_python
/practice_mini_scripts/math_quiz_addition.py
1,687
4.25
4
# Program: Math Quiz (Addition) # Description: Program randomly produces a sum of two integers. User can input the answer # and recieve a congrats message or an incorrect message with the correct answer. # Input: # Random Integer + Random Integer = ____ # Enter your answer: # Output: # Correct = Congratulations! # Incorrect = The correct answer is ____ # Program Output Example: # Correct # 22 + 46 = ___ # Enter your answer: 68 # Congratulations! # Incorrect # 75 + 16 = ___ # Enter your answer: 2 # The correct answer is 91. # Pseudocode: # Main Module # from numpy import random # Set num1 = random.randint(100) # Set num2 = random.randint(100) # Display num1, '+', num2, '= ___ ' # Set correctAnswer = num1 + num2 # Set userAnswer = getUserAnswer() # Call checkAnswer(userAnswer, correctAnswer) # End Main # Module getUserAnswer(): # Set userAnswer = int(input('Enter your answer: ')) # Return userAnswer # Module checkAnswer(userAnswer, correctAnswer): # If userAnswer == correctAnswer: # Display 'Congratulations!' # Else: # Display 'The correct answer is ', correctAnswer, '.', sep='' # End checkAnswer # Call Main def main(): from numpy import random num1 = random.randint(100) num2 = random.randint(100) print(num1, '+', num2, '= ___ ') correctAnswer = num1 + num2 userAnswer = getUserAnswer() checkAnswer(userAnswer, correctAnswer) def getUserAnswer(): userAnswer = int(input('Enter your answer: ')) return userAnswer def checkAnswer(userAnswer, correctAnswer): if userAnswer == correctAnswer: print('Congratulations!') else: print('The correct answer is ', correctAnswer, '.', sep='') main()
true
0970f57aa338249ee6466c1dadadeee769acf7c6
MurphyStudebaker/intro-to-python
/1-Basics.py
2,086
4.34375
4
""" PYTHON BASICS PRACTICE Author: Murphy Studebaker Week of 09/02/2019 --- Non-Code Content --- WRITING & RUNNING PROGRAMS Python programs are simply text files The .py extension tells the computer to interperet it as Python code Programs are run from the terminal, which is a low level interaction with the computer You must be in the directory of your program in order to run the file correctly Switch directories by typing: cd <PATH/TO/YOUR/FILE> (path can be found by right clicking your file and copying the full path) Once in the right directory, type python (or python3 for Macs) and then the name of your file EXAMPLE: python MyProgram.py NAMING CONVENTIONS Variable names should be lower_case, cannot contain any python keywords, and must be descriptive of what the variable represents OPERATORS + Addition - Subtraction * Multiplication / Division // Rounded Division ** Exponent (ex 2**2 is 2 to the power of 2) % Modulo aka Integer Remainder < Less than == Equal to > Greater than <= less than or equal to >= greater than or equal to != not equal to = assignment (setting a value to a variable) TYPES int Integer 8, 0, -1700 float Decimal 8.0, .05, -42.5 str String "A character", "30", "@#$!!adgHHJ" bool Boolean True, False """ """ NOW FOR THE CODE """ # GETTING INPUT AND OUTPUTTING TO CONSOLE # input is always a string # saving what the user types in to the variable "name" name = input("Enter your name: ") print("Hello, " + name) """ MODULES Modules are libraries of code written by other developers that make performing certain functions easier. Commonly used modules are the math module (has constants for pi and e and sqrt() functions) and the random module (randomly generate numbers) """ import random user_id = random.randint(100, 1000) print("Hello, " + name + "! Your ID is " + str(user_id)) # MATHEMATICAL OPERATIONS import math radius = float(input("Radius: ")) circ = 2 * math.pi * radius print("The circumference is " + str(circ))
true
874769f6eddcea51823c926e4b520e6cc0bbcf89
IfDougelseSa/cursoPython
/exercicios_seccao4/46.py
266
4.125
4
# Digitos invertidos num = int(input('Digite o numero com 3 digitos: ')) primeiro_numero = num % 10 resto = num // 10 segundo_numero = resto % 10 resto = resto //10 terceiro_numero = resto % 10 print(f'{primeiro_numero}{segundo_numero}{terceiro_numero}')
false
7ea222e7fee925a91e1e9cd3781545759e1f44c6
IfDougelseSa/cursoPython
/exercicios_seccao4/47.py
307
4.1875
4
# Numero por linha x = int(input("Digite o numero: ")) quarto_numero = x % 10 resto = x // 10 terceiro_numero = resto % 10 resto = resto // 10 segundo_numero = resto % 10 resto = resto // 10 primeiro_numero = resto % 10 print(f'{primeiro_numero}\n{segundo_numero}\n{terceiro_numero}\n{quarto_numero}')
false
f721cd2800a98b3e5eec010e698bb4e07f0d8de2
sudoabhinav/competitive
/hackerrank/week-of-code-36/acid-naming.py
544
4.15625
4
# https://www.hackerrank.com/contests/w36/challenges/acid-naming def acidNaming(acid_name): first_char = acid_name[:5] last_char = acid_name[(len(acid_name) - 2):] if first_char == "hydro" and last_char == "ic": return "non-metal acid" elif last_char == "ic": return "polyatomic acid" else: return "not an acid" if __name__ == "__main__": n = int(raw_input().strip()) for a0 in xrange(n): acid_name = raw_input().strip() result = acidNaming(acid_name) print result
false
a3c3790812f74749f601c0075b115fbe2a296ca1
sudoabhinav/competitive
/hackerrank/algorithms/strings/pangrams.py
232
4.125
4
# https://www.hackerrank.com/challenges/pangrams from string import ascii_lowercase s = raw_input().strip().lower() if len([item for item in ascii_lowercase if item in s]) == 26: print "pangram" else: print "not pangram"
true
dfd5901190b3715f8b3727b9600518bed7b29a36
jdalichau/classlabs
/letter_removal.py
982
4.1875
4
#CNT 336 Spring 2018 #Jaosn Dalichau #jdalichau@gmail.com #help with .replace syntax found it the book 'how to think like a computer scientist' interactive edition #This code is designed to take an input name and remove vowels of any case n = input('Enter your full name: ') #input statement for a persons full name if n == ('a') or ('e') or ('i') or ('o') or ('u'): #If statement declaring lower case values n = n.replace('a','')#remove a n = n.replace('e', '')#remove e n = n.replace('i','')#remove i n = n.replace('o','')#remove o n = n.replace('u','')#remove u if n == ('A') or ('E') or ('I') or ('O') or ('U'):#second if statement declaring upper case values n = n.replace('A','')#remove A n = n.replace('E', '')#remove E n = n.replace('I','')#remove I n = n.replace('O','')#remove O n = n.replace('U','')#remove U print(n)#print the input with or without replaced values
false
6ad233abf66a03c2690d6450f9a54f56d83048ed
sripadaraj/pro_programs
/python/starters/biggest_smallest.py
1,015
4.1875
4
print "The program to print smallest and biggest among three numbers" print "_____________________________________________________________" a=input("enter the first number") b=input("enter the second number") c=input("enter the third number") d=input("enter the fourth number") if a==b==c==d : print "all are equal " else : if a>=b and a>=c and a>=d: big=a if a<=b and a<=c and a<=d: small=a if b>=a and b>=c and b>=d: big=b if b<=a and b<=c and b<=d: small=b if c>=a and c>=b and c>=d: big=c if c<=a and c<=b and c<=d: small=c if d>=a and d>=b and d>=c: big=d if d<=a and d<=b and d<=c: small=d print "_______________________________________________________________" print "the biggest among ",a,",",b,",",c,",",d,"is :\n" print big print "the smallest among ",a,",",b,",",c,",",d,"is :\n" print "smallest",small print "_______________________________________________________________"
false
b6bd22d9d207e9cd75d3f06e4e9e43d3b80af360
Shijie97/python-programing
/ch04/8-function(3).py
685
4.1875
4
# !user/bin/python # -*- coding: UTF-8 -*- def func(a, b = 2, c = "hello"): # 默认参数一定是从最后一个开始往左连续存在的 print(a, b, c) func(2, 100) # 覆盖了b = 2 i =5 def f(arg = i): print(i) i = 6 f() # 6 # 在一段程序中,默认值只被赋值一次,如果参数中存在可变数据结构,会进行迭代 def ff(a, L = []): L.append(a) return L print(ff(1)) # [1] print(ff(2)) # [1, 2] print(ff(3)) # [1, 2 ,3] # 不想迭代的话,就如下所示 def fff(a, L = None): if L is None: L = [] L.append(a) return L print(fff(1)) # [1] print(fff(2)) # [2] print(fff(3)) # [3]
false
01edc69712cc340ab98aab6edef608483102deda
Shijie97/python-programing
/ch05/2-list(2).py
499
4.125
4
# !user/bin/python # -*- coding: UTF-8 -*- from collections import deque lst = [100, 1, 2, 3, 2] # 列表当做stack使用 lst.append(5) # push print(lst) lst.pop() # pop print(lst) # 列表当做queue用 queue = deque(lst) print(queue) queue.append(5) # 入队 deque([0, 1, 2, 3, 2]) print(type(queue)) # <class 'collections.deque'> print(queue) res = queue.popleft() # 出队,并返回出队的元素 print(res) print(queue) print(list(queue)) # 强制转化成list结构
false
78b8f148a5404d3522e7b9944f810095793c4411
aquibjamal/hackerrank_solutions
/write_a_function.py
323
4.25
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 21:41:35 2019 @author: aquib """ def is_leap(year): leap = False # Write your logic here if year%4==0: leap=True if year%100==0: leap=False if year%400==0: leap=True return leap
false
e8cff56a53e29a80d047e999918b43deff019c3e
sauravsapkota/HackerRank
/Practice/Algorithms/Implementation/Beautiful Days at the Movies.py
713
4.15625
4
#!/bin/python3 import os # Python Program to Reverse a Number using While loop def reverse(num): rev = 0 while (num > 0): rem = num % 10 rev = (rev * 10) + rem num = num // 10 return rev # Complete the beautifulDays function below. def beautifulDays(i, j, k): count = 0 for num in range(i, j + 1): rev = reverse(num) if (abs(num - rev) % k) == 0: count += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') ijk = input().split() i = int(ijk[0]) j = int(ijk[1]) k = int(ijk[2]) result = beautifulDays(i, j, k) fptr.write(str(result) + '\n') fptr.close()
true
1ae7cdf0c2e2b51586428e3627ee4244e9650cab
eduardrich/Senai-2.1
/3.py
529
4.1875
4
#Definição da lista Val = [] #Pede para inserir os 20 numeros para a media for c in range(0,20): Val.append ( int(input("Digite aqui os valores para a média: ")) ) #detalhamento da soma e conta dos numeros dentro da lista SomVal = sum(Val) NumVal = len(Val) #Tira a media MedVal = SomVal / NumVal print("Media da lista: ") print(MedVal) #Numero Max dentro da lista MaxVal = max(Val) print("Numero Max da lista:") print(MaxVal) #Numero Min dentro da lista MinVal = min(Val) print("Numero Min da lista") print(MinVal)
false
3fa2fe6caf2a0cfda09a745dc8c7fceb7d381e5a
YayraVorsah/PythonWork
/lists.py
1,673
4.4375
4
names = ["John","Kwesi","Ama","Yaw"] print(names[-1]) #colon to select a range of items names = ["John","Kwesi","Ama","Yaw"] print(names[::2]) names = ["John","Kwesi","Ama","Yaw"] names[0] ="Jon" #the list can be appended print(names) numbers = [3,4,9,7,1,3,5,] max = numbers[0] for number in numbers: if number > max: max = number print(max) print("2 D L I S T S") #MACHINE LEARNING AND MATRICS(RECTANGULAR ARRAY OF NUMBERS) #MATRIX = [LIST] matrix = [ # EACH ITEM REPRESENTS ANOTHER LIST [1, 2, 3], [4, 5, 6], [7, 8, 9], ] print(matrix[0]) matrix = [ # EACH ITEM REPRESENTS ANOTHER LIST [1, 2, 3], [4, 5, 6], [7, 8, 9], ] for row in matrix: for item in row: print(item) # list methods # numbers = [3,4,5,9,7,1,3,5,] # numbers.append(20) # TO ADD THE NUMBER TO THE LIST # numbers.insert(0,8) # INSERTED AT THE INDEX YOU DETERMINE # numbers.remove(1) # numbers.clear() #REMOVES EVERYTHING IN THE LIST # # numbers.pop() #LAST NUMBER IS REMOVED FROM THE LIST # #print(numbers.index(3)) #shows what number is set at that index # #print(50 in numbers) # to check if it is present in the list --- generates a boolean # print(numbers.count(5)) # numbers.sort() sorts out the list in ascending order # numbers.reverse() sorts in descending order # numbers.copy() to copy the list numbers = [2,2,4,6,3,4,6,1] uniques = [] for number in numbers: if number not in uniques: uniques.append(number) print(uniques)
false
f2cacc2f354655e601273d4a2946a2b27258624d
YayraVorsah/PythonWork
/conditions.py
1,769
4.1875
4
#Define variable is_hot = False is_cold = True if is_hot: #if true for the first statement then print print("It's a hot day") print("drink plenty of water") elif is_cold: # if the above is false and this is true then print this print("It's a cold day") print("Wear warm clothes") else: # else you print this if both statements are false print("It's a good day") print("Enjoy your day") print("EXERCISE") house_price = 1000000 good_credit = True bad_credit = False if good_credit: downpay = house_price//10 print("your downpayment : $" + str(downpay)) else : downpay = house_price//20 print("Your downpay is bad ") # if good_credit: # print("Your down payment is " + good_credit) print("LOGICAL OPERATORS") hasHighIncome = True hasGoodCredit = True if hasHighIncome and hasGoodCredit: #Both Conditions need to be true to execute print("Eligible for Loan") #even if one statement is false(It all becomes false due to the AND operator) else: print("Not eligible for Loan") hasHighIncome = True hasGoodCredit = False if hasHighIncome or hasGoodCredit: #At least One condition needs to be true to execute print("Eligible for Loan and other goods") #even if one statement is false it will execute because of the OR operator) else: print("Not eligible for Loan") print("NOT OPERATOR") #has good credit and not a criminal record good_credit = True criminalRecord = False # the not operator would turn this to True if good_credit and not criminalRecord: # and not (criminalRecord = False) === True print("you are good to go")
true
881a8e4b1aa1eaed9228782eef2440097c2cb301
siyangli32/World-City-Sorting
/quicksort.py
1,439
4.125
4
#Siyang Li #2.25.2013 #Lab Assignment 4: Quicksort #partition function that takes a list and partitions the list w/ the last item #in list as pivot def partition(the_list, p, r, compare_func): pivot = the_list[r] #sets the last item as pivot i = p-1 #initializes the two indexes i and j to partition with j = p while not j == r: #function runs as long as j has not reached last object in list if compare_func(the_list[j], pivot): #takes in compare function to return Boolean i += 1 #increments i before j temp = the_list[i] #switches i value with j value the_list[i] = the_list[j] the_list[j] = temp j += 1 #increments j temp = the_list[r] #switches pivot with the first object larger than pivot the_list[r] = the_list[i+1] the_list[i+1] = temp return i+1 #returns q = i+1 (or pivot position) #quicksort function takes in the partition function and recursively sorts list def quicksort(the_list, p, r, compare_func): if p < r: #recursive q = partition(the_list, p, r, compare_func) quicksort(the_list, p, q-1, compare_func) quicksort(the_list, q+1, r, compare_func) return the_list #sort function sorts the entire list using quicksort def sort(the_list, compare_func): return quicksort(the_list, 0, len(the_list)-1, compare_func)
true
150810f760c409533200b7252912130cc72e792b
aiman88/python
/Introduction/case_study1.py
315
4.1875
4
""" Author - Aiman Date : 6/Dec/2019 Write a program which will find factors of given number and find whether the factor is even or odd. """ given_number=9 sum=1 while given_number>0: sum=sum*given_number given_number-=1 print(sum) if sum%10!=0: print("odd number") else: print("Even number")
true
764b1f8af7fee5c6d0d1707ab6462fc1d279be36
dadheech-vartika/Leetcode-June-challenge
/Solutions/ReverseString.py
863
4.28125
4
# Write a function that reverses a string. The input string is given as an array of characters char[]. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # You may assume all the characters consist of printable ascii characters. # Example 1: # Input: ["h","e","l","l","o"] # Output: ["o","l","l","e","h"] # Example 2: # Input: ["H","a","n","n","a","h"] # Output: ["h","a","n","n","a","H"] # Hide Hint #1 # The entire logic for reversing a string is based on using the opposite directional two-pointer approach! # SOLUTION: class Solution(object): def reverseString(self, s): def helper(left,right): if left < right: s[left], s[right] = s[right], s[left] helper(left + 1, right - 1) helper(0, len(s) - 1)
true
ca042af11712f32c4b089da67c4a9dcfecd6000d
darkblaro/Python-code-samples
/strangeRoot.py
1,133
4.25
4
import math ''' getRoot gets a number; calculate a square root of the number; separates 3 digits after decimal point and converts them to list of numbers ''' def getRoot(nb): lsr=[] nb=math.floor(((math.sqrt(nb))%1)*1000) #To get 3 digits after decimal point ar=str(nb) for i in ar: lsr.append(int(i)) return lsr ''' getPower gets a number; calculate a power of the number; and converts the result to list of numbers ''' def getPower(num): lsp=[] num=int(math.pow(num,2)) ar=str(num) for i in ar: lsp.append(int(i)) return lsp ''' isStrange gets a number; calls to two functions above and gets from them two lists of numbers; after that compares two lists ''' def isStrange(nb): ls1=getRoot(nb) ls2=getPower(nb) for i1 in ls1: for i2 in ls2: if i1==i2: return True return False if __name__ == '__main__': number=int(input("Enter a number")) if isStrange(number): print(f'{number} has strange root') else: print(f'{number} doesn\'t have strange root')
true
c0c9303b5127be01a420a033e2d0b6dcbc9e1f2d
chskof/HelloWorld
/chenhs/object/demo7_Override.py
470
4.21875
4
""" 方法重写(覆盖): 如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法 """ # 定义父类 class Parent: def myMethod(self): print('调用父类方法') class Child(Parent): def myMethod(self): print('调用子类方法') c = Child() # 创建子类对象 c.myMethod() # 调用子类重写的方法 super(Child, c).myMethod() # 用子类对象调用父类已被覆盖的方法
false
01b8496d29a0a14957447204d655e441254aeb75
worasit/python-learning
/mastering/generators/__init__.py
1,836
4.375
4
""" `A generator` is a specific type of iterator taht generates values through a function. While traditional methods build and return a `list` of iterms, ad generator will simply `yield` every value separately at the moment when they are requested by the caller. Pros: - Generators pause execution completely until the next value is yielded, which make them completely lazy. - Generators have no need to save values. Whereas a traditional function would require creating a `list` and storing all results until they are returned, a generator only need to store a single value - Generators have infinite size. There is no requirement to stop at a certain point These preceding benefits come at a price, however. The immediate results of these benefits are a few disadvantage Cons: - Until you are done processing, you never know how many values are left; it could even be infinite. This make usage dangerous in some cases; executing `list(some_infinite_generator)` will run out of memory - You cannot slice generators - You cannot get specific items without yielding all values before that index - You cannot restart a generator. All values are yielded exactly one ================= Coroutines =============== Coroutiens are functions that allow for multitasking without requiring multiple threads or processes. Whereas generators can only yield values from the caller while it is still running. While this technique has a few limiations, if it suits your purpose, it can result in great performance at a very little cost. The topics covered in this chapter are: - The characteristics and uses of generators - Generator comprehensions - Generator functions - Generator classes - Buldled generators - Coroutines """
true
b3c14db3a26d5d6e122e96fc736c8266e907ed97
lfvelascot/Analysis-and-design-of-algorithms
/PYTHON LOG/tuplas.py
1,022
4.125
4
tupla1=("Hola","Mi",25,"nombre",25) print("Elemento en la posicion 2 : ",tupla1[2]) print("///////") #Convertir una tupla a lista lista=list(tupla1) print("Tupla convertirda en lista\n",lista) print("///////") ##Convetir una lista a tupla tuplar=tuple(lista) print("Lista convertida en tupla\n",tuplar) print("///////") ## Buscar un valor en una tupla print("Hola" in tupla1) print("///////") ##Saber cuantas veces ets aun elemento en una lista print("Cuantas veces esta 25 en la tupla? ",tupla1.count(25)) print("///////") ##Saber la longitud de una tupla print("Longitud de la tupla : ",len(tupla1)) print("///////") #Tupla unitaria tuplaunitaria=(258,) print("Tupla de un solo elemento ",tuplaunitaria) print(len(tuplaunitaria)) print("///////") # Tupla sin parentesis tuplan = 10,20,30,40 print("Tupla sin parentesis : ",tuplan) print("///////") #Distribucion de valores de una tupla en variables nombre,dia,mes,agnio,cosa=tupla1 print(nombre) print(dia) print(mes) print("///////")
false
c03dd868f24eec310e537c5c224b9627b469a811
rileyworstell/PythonAlgoExpert
/twoNumSum.py
900
4.21875
4
""" Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If not two numbers sum up to the target sum, the function should return an empty array. Note that the target sum has to be obtained by summing two different integers in the array; you can't add a single integer to itself in order to obtain the target sum. You can assume there will be at most one pair of numbers summing up to the target sum. """ class Car: def __init__(self, year): self.color = "Red" self.year = year Mustang = Car(1997) print(Mustang.color) print(Mustang.year) dict1 = { "brand": "Nike", "color": "Red" } mydict = dict1 print(mydict["brand"]) arr = [[x for x in range(10)] for _ in range(10)] print(arr)
true
c79ba3a6834fbb5a0f8d5c2ebabe0d4f6f790452
mwongeraE/python
/spellcheck-with-inputfile.py
904
4.15625
4
def spellcheck(inputfile): filebeingchecked=open(inputfile,'r') spellcheckfile=open("words.txt",'r') dictionary=spellcheckfile.read().split() checkedwords=filebeingchecked.read().split() for word in checkedwords: low = 0; high=len(dictionary)-1 while low <= high: mid=(low+high)//2 item=dictionary[mid] if word == item: break elif word < item: high=mid-1 else: low=mid+1 else: yield word def main(): print("This program accepts a file as an input file and uses a spell check function to \nidentify any problematic words that are not found in a common dictionary.") inputfile=input("Enter the name of the desired .txt file you wish to spellcheck:") for word in spellcheck(inputfile): print(word) main()
true
89038721966e0c3974e91a3c58db4c6245ffa354
robwalker2106/100-Days
/day-18-start/main.py
1,677
4.1875
4
from turtle import Turtle, Screen from random import randint, choice don = Turtle() #don.shape('turtle') don.color('purple3') #don.width(10) don.speed('fastest') screen = Screen() screen.colormode(255) def random_color(): """ Returns a random R, G, B color. :return: Three integers. """ r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) return r, g, b def spirograph(circles, radius): """ Creates a spirograph with the inputted amount of circles, each with random line colors and equal radius size. :param circles: int :param radius: int :return: """ angles = 360 / circles for _ in range(circles): don.setheading(don.heading() + angles) don.pencolor(random_color()) don.circle(radius) spirograph(120, 150) # def short_walk(): # """ # Creates a short walk with a random color and direction. There are three choices for the direction. # (Left, Straight, or Right). # :return: None # """ # not_backwards = [-90, 0, 90] # current = int(don.heading()) # don.setheading(current + choice(not_backwards)) # don.pencolor(random_color()) # don.forward(15) # # # for _ in range(200): # short_walk() # def draw_shape(sides): # """ # Draws a shape with equal N sides. # :param sides: int # :return: None # """ # r = randint(1, 255) # b = randint(1, 255) # g = randint(1, 255) # # for _ in range(sides): # don.pencolor((r, g, b)) # don.forward(100) # don.right(360 / sides) # for i in range(3, 11): # draw_shape(i) screen.screensize(600, 600) screen.exitonclick()
true
a3337bde5cf7d0b0712a15f23d2ab63fed289c2f
nickdurbin/iterative-sorting
/src/searching/searching.py
1,860
4.3125
4
def linear_search(arr, target): # Your code here # We simply loop over an array # from 0 to the end or len(arr) for item in range(0, len(arr)): # We simply check if the item is equal # to our target value # If so, then simply return the item if arr[item] == target: return item # If the target does not exist in our array # Return -1 which equates to not found return -1 # not found # Write an iterative implementation of Binary Search def binary_search(arr, target): # Your code here # We need the beginning of the array # So we create a variable and start at zero start = 0 # Next we need to find the end of the array # Create a variable use the length - 1 end = len(arr) - 1 # Next we create a loop that runs as long as the start # and the end are NOT the same and start is LESS THAN # the value of end while start <= end: # Here we create the middle value # We simply add the start + end and then divide # By two to find the median value or middle middle = (start + end) // 2 # If our middle value is the target we are searching for # simply return the middle value if arr[middle] == target: return middle # Else if the middle value is less than our target value # We do not need any of the array values before our middle # So we make the start our middle value + 1 elif arr[middle] < target: start = middle + 1 # Else if the middle is greater than the target # we work backwards and make our mid value # equal to our end value and subtract one else: end = middle - 1 # If the target value is not in the array # return -1, which is not found return -1 # not found
true
c346a76f33f96248e4782304636a32c12238c6aa
adilawt/Tutorial_2
/1_simpsons_rule.py
672
4.15625
4
# ## Tutorial2 Question3 ## a) Write a python function to integrate the vector(in question #2) using ## Simpson's Rule # import numpy as np def simpsonsrule(f, x0, xf, n): if n & 1: print ("Error: n is not a even number.") return 0.0 h = float(xf - x0) / n integral = 0.0 x = float(x0) for i in range(0, n / 2): integral += f(x) + (2.0 * f(x + h)) x += 2 * h integral = (2.0 * integral) - f(x0)+f(x0) integral = h * integral / 3.0 return integral def f(x): #f(x) = np.cos(x) return np.cos(x) x0=0.0; xf=np.pi/2 N = (10,30,100,300,1000) for n in N: print(simpsonsrule(f, x0, xf, n))
true
ab1a0c5e0f29e91a4d2c49a662e3176f4aa158f5
salihbaltali/nht
/check_if_power_of_two.py
930
4.1875
4
""" Write a Python program to check if a given positive integer is a power of two """ def isInt(x): x = abs(x) if x > int(x): return False else: return True def check_if_power_of_two(value): if value >= 1: if value == 1 or value == 2: return True else: while value != 2: value /= 2 if isInt(value) == False : return False return True else: if value == 0: return False while value < 1: value *= 2 if value == 1: return True else: return False while True: number = float(input("Please Enter the Number: ")) print(number) if check_if_power_of_two(number): print("{} is the power of 2".format(number)) else: print("{} is not the power of 2".format(number))
true
89994b56da945167c927ad2617a5b9cbfc2d4a6b
rkovrigin/crypto
/week2.py
2,872
4.25
4
""" In this project you will implement two encryption/decryption systems, one using AES in CBC mode and another using AES in counter mode (CTR). In both cases the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. For CBC encryption we use the PKCS5 padding scheme discussed in the lecture (14:04). While we ask that you implement both encryption and decryption, we will only test the decryption function. In the following questions you are given an AES key and a ciphertext (both are hex encoded ) and your goal is to recover the plaintext and enter it in the input boxes provided below. For an implementation of AES you may use an existing crypto library such as PyCrypto (Python), Crypto++ (C++), or any other. While it is fine to use the built-in AES functions, we ask that as a learning experience you implement CBC and CTR modes yourself. Question 1 CBC key: 140b41b22a29beb4061bda66b6747e14 CBC Ciphertext 1: 4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81 """ from Cryptodome.Cipher import AES from Cryptodome import Random from Cryptodome.Util import Counter import codecs keys = [] ciphers = [] keys.append(codecs.decode("140b41b22a29beb4061bda66b6747e14", 'hex')) keys.append(codecs.decode("140b41b22a29beb4061bda66b6747e14", 'hex')) keys.append(codecs.decode("36f18357be4dbd77f050515c73fcf9f2", 'hex')) keys.append(codecs.decode("36f18357be4dbd77f050515c73fcf9f2", 'hex')) ciphers.append(codecs.decode("4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81", "hex")) ciphers.append(codecs.decode("5b68629feb8606f9a6667670b75b38a5b4832d0f26e1ab7da33249de7d4afc48e713ac646ace36e872ad5fb8a512428a6e21364b0c374df45503473c5242a253", "hex")) ciphers.append(codecs.decode("69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc388d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329", "hex")) ciphers.append(codecs.decode("770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa0e311bde9d4e01726d3184c34451", "hex")) block_size = 16 def decrypt_cbc(key, cypherText): iv = cypherText[:block_size] ct1 = cypherText[block_size:] obj = AES.new(key, AES.MODE_CBC,iv) padded_str = obj.decrypt(ct1) padding_amount = ord(padded_str[len(padded_str)-1:]) return padded_str[:-padding_amount] def decrypt_ctr(key, cypherText): iv = cypherText[:block_size] ct1 = cypherText[block_size:] ctr = Counter.new(block_size * 8, initial_value=int(codecs.encode(iv, 'hex'), 16)) obj = AES.new(key, AES.MODE_CTR, counter=ctr) padded_str = obj.decrypt(ct1) return padded_str for key, cipher in zip(keys[:2], ciphers[:2]): out = decrypt_cbc(key, cipher) print(out) for key, cipher in zip(keys[2:], ciphers[2:]): out = decrypt_ctr(key, cipher) print(out)
true
0c40f14af82893bc8ccce60259424a98aaf28574
Wintus/MyPythonCodes
/PrimeChecker.py
608
4.15625
4
'''Prime Checker''' def is_prime(n): '''check if interger n is a prime''' n = abs(int(n)) # n is a pesitive integer if n < 2: return False elif n == 2: return True # all even ns aren't primes elif not n & 1: # bit and return False else: # for all odd ns for x in range(3, int(n ** .5) + 1, 2): if n % x == 0: return False else: return True if __name__ == '__main__': # test ns = (1, 2, 3, 29, 49, 95, 345, 999979, 999981) # FTTTFFFTF for n in ns: print(n, is_prime(n))
false
1350fcd3baa866a02f5db2c066420eaa77e00892
BrasilP/PythonOop
/CreatingFunctions.py
1,404
4.65625
5
# Creating Functions # In this exercise, we will review functions, as they are key building blocks of object-oriented programs. # Create a function average_numbers(), which takes a list num_list as input and then returns avg as output. # Inside the function, create a variable, avg, that takes the average of all the numbers in the list. # Call the average_numbers function on the list [1, 2, 3, 4, 5, 6] and assign the output to the variable my_avg. # Print out my_avg. # Create function that returns the average of an integer list def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) # divide by length of list return avg # Take the average of a list: my_avg my_avg = average_numbers([1, 2, 3, 4, 5, 6]) # Print out my_avg print(my_avg) # 3.5 # Creating a complex data type # In this exercise, we'll take a closer look at the flexibility of the list data type, by creating a list of lists. # In Python, lists usually look like our list example below, and can be made up of either simple strings, integers, # or a combination of both. list = [1, 2] # In creating a list of lists, we're building up to the concept of a NumPy array. # Create a variable called matrix, and assign it the value of a list. # Within the matrix list, include two additional lists: [1,2,3,4] and [5,6,7,8]. # Print the matrix list. matrix = [[1, 2, 3, 4], [5, 6, 7, 8]] print(matrix)
true
566ff9db1680e613ef013e6918d274b1382c2934
codethat-vivek/NPTEL-Programming-Data-Structures-And-Algorithms-Using-Python-2021
/week2/RotateList.py
646
4.28125
4
# Third Problem: ''' A list rotation consists of taking the first element and moving it to the end. For instance, if we rotate the list [1,2,3,4,5], we get [2,3,4,5,1]. If we rotate it again, we get [3,4,5,1,2]. Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotations. If k is not positive, your function should return l unchanged. Note that your function should not change l itself, and should return the rotated list. ''' # SOLUTION - def rotatelist(l,k): if k <= 0: return l ans = [0]*len(l) for i in range(len(l)): ans[i] = l[(i+k)%len(l)] return ans
true
1ff1fadb88d860e4d2b97c5c38668bcc880c607c
morzen/Greenwhich1
/COMP1753/week7/L05 Debugging/02Calculator_ifElifElse.py
1,241
4.40625
4
# this program asks the user for 2 numbers and an operation +, -, *, / # it applies the operation to the numbers and outputs the result def input_and_convert(prompt, conversion_fn): """ this function prompts the user for some input then it converts the input to whatever data-type the programmer has requested and returns the value """ string = input(prompt) number = conversion_fn(string) return number def output(parameter1, parameter2): """ this function prints its parameters as strings """ parameter1_str = str(parameter1) parameter2_str = str(parameter2) print(parameter1_str + parameter2_str) number1 = input_and_convert(" First number: ", int) number2 = input_and_convert("Second number: ", int) operation = input_and_convert("Operation [+, -, *, /]: ", str) if operation == "+": combination = number1 + number2 elif operation == "-": combination = number1 - number2 elif operation == "*": combination = number1 * number2 elif operation == "/": combination = number1 / number2 else: # the user has made a mistake :( combination = "ERROR ... '" + operation + "' unrecognised" output("Answer: ", combination) print() input("Press return to continue ...")
true
c2e8208d3f33abd0ba15b7e1a51a13c54a0b2135
SerenaPaley/WordUp
/venv/lib/python3.8/WordUp.py
1,231
4.28125
4
# Serena Paley # March, 2021 from getpass import getpass def main(): print('Welcome to Word Up') secret_word = getpass('Enter the secret word') current_list = ["_"] * len(secret_word) letter_bank = [] guess = "" while "_" in current_list: print_board(current_list) get_letter(guess, letter_bank) print_letter_bank(letter_bank) print() guess = input("Guess a letter ") check_letter(secret_word, guess, current_list) print_board(current_list) print() print("Congratulations, the word was " + secret_word) def print_board(current_list): for i in current_list: print(i, end=" ") def check_letter(secret_word, guess,current_list): k = 0; while k < len(secret_word): if guess == secret_word[k]: current_list[k] = guess k = k + 1 else: k = k + 1 if guess not in secret_word: print (guess + " is not in the secret word") def get_letter(guess, letter_bank): letter_bank.append(guess) def print_letter_bank(letter_bank): print() print("Used Letters:" ,end="") for j in letter_bank: print (j, end=" ") if __name__ == "__main__": main()
false
86f0b87b8e1aa0178656a4d418774926376a23d0
cindy3124/python
/testerhome_pratice/pytest_practice/pytest_bubble.py
376
4.15625
4
#! /usr/bin/env python # coding=utf-8 import random def bubble_sort(nums): for i in range(len(nums)-1): for j in range(len(nums)-i-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] print(nums) return random.choice([nums, None, 10]) if __name__ == '__main__': print(bubble_sort([3, 1, 7, 4, 0, 8, 6]))
false
36e7cd8cc96264f50e49f9cd2b778fc642434312
GaryZhang15/a_byte_of_python
/002_var.py
227
4.15625
4
print('\n******Start Line******\n') i =5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s) a = 'hello'; print(a) b = \ 5 print(b) print('\n*******End Line*******\n')
true
a09f9fe6aa0663cf8143ca71d01553918d6d35a1
Sana-mohd/fileQuestions
/S_s_4.py
298
4.34375
4
#Write a Python function that takes a list of strings as an argument and displays the strings which # starts with “S” or “s”. Also write a program to invoke this function. def s_S(list): for i in list: if i[0]=="S" or i[0]=="s": print(i) s_S(["sana","ali","Sara"])
true
a32ad588efb25dad5d64dcf2a29be6e697d5cfdd
Andrewlearning/Leetcoding
/leetcode/String/434m. 字符串中的单词数.py
976
4.25
4
""" 统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。 示例: 输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。 """ class Solution(object): def countSegments(self, s): """ :type s: str :rtype: int """ if not s and len(s) == 0: return 0 p = 0 count = 0 # 去掉前面空格,移动到第一个单词 while p < len(s) and s[p] == " ": p += 1 while p < len(s): count += 1 # s[p]在单词里的话,则继续移动p while p < len(s) and s[p] != " ": p += 1 # s[p]不在单词里,移动p while p < len(s) and s[p] == " ": p += 1 return count
false
ed28b398a00b09708cd6cadebe4ce5342d16466b
Andrewlearning/Leetcoding
/leetcode/Random/478m. 在圆内随机生成点(拒绝采样).py
1,711
4.25
4
""" 给定圆的半径和圆心的 x、y 坐标,写一个在圆中产生均匀随机点的函数 randPoint 。 说明: 输入值和输出值都将是浮点数。 圆的半径和圆心的 x、y 坐标将作为参数传递给类的构造函数。 圆周上的点也认为是在圆中。 randPoint 返回一个包含随机点的x坐标和y坐标的大小为2的数组。 示例 1: 输入: ["Solution","randPoint","randPoint","randPoint"] [[1,0,0],[],[],[]] 输出: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]] """ import random class Solution(object): def __init__(self, radius, x_center, y_center): """ :type radius: float :type x_center: float :type y_center: float """ self.center = (x_center, y_center) self.radius = radius def randPoint(self): # 矩形的原点坐标(最左下角的点) ractangle_x0 = self.center[0] - self.radius ractangle_y0 = self.center[1] - self.radius while True: # x,y是在矩形范围内随机生成的点的坐标 x = ractangle_x0 + random.random() * 2 * self.radius y = ractangle_y0 + random.random() * 2 * self.radius # 假如x,y距离圆心得距离超过半径,说明点不在圆的范围以内 if (self.center[0] - x) ** 2 + (self.center[1] - y) ** 2 <= self.radius ** 2: return [x, y] # 思路 https://leetcode-cn.com/problems/generate-random-point-in-a-circle/solution/zai-yuan-nei-sui-ji-sheng-cheng-dian-by-leetcode/ # 代码:https://leetcode-cn.com/problems/generate-random-point-in-a-circle/solution/478-zai-yuan-nei-sui-ji-sheng-cheng-dian-by-haoyuh/
false
ddc89b17a98a81a0e4b2141e487c0c2948d0621a
lfr4704/python_practice_problems
/algorithms.py
1,579
4.375
4
import sys; import timeit; # Big-O notation describes how quickly runtime will grow relative to the input as the input gets arbitrarily large. def sum1(n): #take an input of n and return the sume of the numbers from 0 to n final_sum = 0; for x in range(n+1): # this is a O(n) final_sum += x return final_sum def sum2(n): return (n*(n+1))/2 # this is a O(n**2) # using setitem t = timeit.Timer() print 'TIMEIT:' print "sum1 is " + str(sum1(100)) + " and the time for sum1 " + str(t.timeit(sum1(100))) print "sum2 is " + str(sum2(100)) + " and time for sum2 " + str(t.timeit(sum2(100))) #O(1) constant def func_constant (values): ''' print first item in a list of value ''' print values[0] func_constant([1,2,3,4,5,6,7]) # no matter how big the list gets the output will always be constant (1) #O(n) Linear is going to be a little more computational than a constant (will take longer) def func_lin (lst): ''' takes in list and prints out all values ''' for val in lst: print val func_lin([1,2,3,4,5,6,7]) #O(n^2) Quadratic def func_quadratic(lst): #prints pairs for every item in list for item_1 in lst: for item_2 in lst: print (item_1, item_2) lst = [1,2,3] print func_quadratic(lst) #this will always have to do an n * n so it will be Quadratic as n grows # time complexity vs. space complexity def memory(n): for x in range(n): # time complexity O(n) print ('memory') # space complexity O(1) - becuase memory is a constant, never changes memory(4)
true
edbe86de9667f66d3cdcdcd120ff76986ab4137e
Schuture/Data-structure
/图算法/图搜索.py
2,937
4.125
4
class Node(): # 单向链表节点 def __init__(self): self.color = 'white' self.d = float('Inf') #与中心点的距离 self.pi = None # 图中的父节点 self.next = None # 只能赋值Node() ''' 循环队列,调用方式如下: Q = Queue() Q.enqueue(5) 往队尾加一个元素 Q.dequeue() 删除队头元素''' class Queue(): def __init__(self): self.queue = [0 for i in range(100)] # 初始化100个队列空位 self.head = 0 self.tail = 0 # 所有元素后的第一个空位 self.length = len(self.queue) self.full = False self.empty = True def enqueue(self,x): self.empty = False #只要调用这个函数,无论原来队列是否为空,都不再为空 if self.full==True: print('Queue overflow!') return self.queue[self.tail] = x if self.tail==self.length-1: self.tail = 0 # 队列末尾被填满 else: self.tail += 1 if self.head==self.tail: # 放完这个元素后队列满了 self.full = True def dequeue(self): self.full = False # 只要调用这个函数,无论原来队列是否为满,都不再为满 if self.empty==True: print('Queue underflow!') return x = self.queue[self.head] if self.head==self.length-1: self.head = 0 else: self.head += 1 if self.head==self.tail: # 取出这个元素后队列空了 self.empty = True return x # 无向图中的节点 nodeR = Node() nodeS = Node() nodeT = Node() nodeU = Node() nodeV = Node() nodeW = Node() nodeX = Node() nodeY = Node() V = set((nodeR,nodeS,nodeT,nodeU,nodeV,nodeW,nodeX,nodeY)) #所有节点 # 边,表示节点能通向的隔壁节点 adjacentR = [nodeS,nodeV] adjacentS = [nodeR,nodeW] adjacentT = [nodeU,nodeW,nodeX] adjacentU = [nodeT,nodeX,nodeY] adjacentV = [nodeR] adjacentW = [nodeS,nodeT,nodeX] adjacentX = [nodeW,nodeT,nodeU,nodeY] adjacentY = [nodeX,nodeU] Adj = {nodeR:adjacentR, nodeS:adjacentS, nodeT:adjacentT, nodeU:adjacentU, nodeV:adjacentV, nodeW:adjacentW, nodeX:adjacentX, nodeY:adjacentY} def BFS(s): # 从点s开始搜索 for vertex in V-set([s]): # 搜索前先清空之前赋予的属性 vertex.color = 'white' vertex.d = float('Inf') vertex.pi = None s.color = 'gray' s.d = 0 s.pi = None Q = Queue() Q.enqueue(s) while Q.empty == False: u = Q.dequeue() #检查点u的邻点 print(u.d) for v in Adj[u]: if v.color == 'white': # 只看仍然没有搜索到的点 v.color = 'gray' v.d = u.d + 1 v.pi = u Q.enqueue(v) u.color = 'black' BFS(nodeS)
false
4459792eff08ed45ddf0bec5cb0337a44e6515ae
olexandrvaitovich/homework
/module7.py
232
4.21875
4
def calculate_sqr(n): """ Calculate squre of a positive integer recursively using n^2 = (n-1)^2 + 2(n-1)+ 1 formula """ if n == 1: return 1 else: return calculate_sqr(n - 1) + 2 * (n - 1) + 1
false
350caa2ceff6bd5a7a05be797bd316c736410ffe
richard1230/NLP_summary
/python字符串操作/1清除与替换.py
1,041
4.34375
4
str1 = " hello world, hello, my name is Richard! " print(str1) #去除首尾所有空格 print(str1.strip()) #去除首部所有空格 print(str1.lstrip()) #去除尾部所有空格 print(str1.rstrip()) #也可以去掉一些特殊符号 print(str1.strip().rstrip('!')) #方法可以组合使用 先去掉首尾空格 在去掉尾部! #注意不能直接str.rstrip('!'),因为此时str的尾部是空格,得先去掉空格再去叹号。 #字符串替换 print(str1) print(str1.replace('hello','how do you do')) #将所有hello都替换为hoe do you do str2 = " 大家好,我是萌妹子, " print(str2) #去除空格和特殊符号 print(str2.strip().lstrip().rstrip(',')) #字符串替换 print(str2.replace('萌妹子','Richard')) #替换为空串'' 相当于删除 print(str2.replace('大家好,','')) # hello world, hello, my name is Richard! # how do you do world, how do you do, my name is Richard! # 大家好,我是萌妹子, # 大家好,我是萌妹子 # 大家好,我是Richard, # 我是萌妹子,
false
01d9030aa89da902667a6ea05a45bbd9761162ef
DerekHunterIcon/CoffeeAndCode
/Week_1/if_statements.py
239
4.1875
4
x = 5 y = 2 if x < y: print "x is less than y" else print "x is greater than or equal to y" isTrue = True if isTrue: print "It's True" else: print "It's False" isTrue = False if isTrue: print "It's True" else: print "It's False"
true
f2ed037552b3a8fdd37b776d5b9df5709b0e494e
SamWaggoner/125_HW6
/Waggoner_hw6a.py
2,742
4.1875
4
# This is the updated version that I made on 7/2/21 # This program will ask input for a list then determine the mode. def determinemode(): numlist = [] freqlist = [] print("Hello! I will calculate the longest sequence of numbers in a list.") print("Type your list of numbers and then type \"end\".") num = (input("Please enter a number: ")) def CheckNum(num): try: num = int(num) return True except ValueError: return False while CheckNum(num) != False: numlist.append(int(num)) num = ((input("Please enter a number: "))) print(numlist) currFreq = 1 modeNum = -1 maxNumOccurrences = 1 for i in range(len(numlist)-2): if numlist[i] == numlist[i+1]: currFreq += 1 if currFreq > maxNumOccurrences: maxNumOccurrences = currFreq modeNum = numlist[i] else: currFreq = 1 if len(numlist) == 0: print("There is no mode, the list provided is empty.") elif modeNum == -1: print("There is no mode, all of the numbers occur an equal number of times.") else: print("The mode is " + str(modeNum) + " which occurred " + str(maxNumOccurrences) + " times.") determinemode() while input("Would you like to find another mode from a new list? (Type \"yes\"): ") == "yes": determinemode() print("Okay, glad I could help!") # This is the original program that I made while in school as homework. # File: hw6a.py # Author: Sam Waggoner # Date: 10/25/2020 # Section: 1006 # E-mail samuel.waggoner@maine.edu # Description: # Create a count for the largest number of subsequent numbers entered by the user. # Collaboration: # I did not discuss this assignment with anyone other than the course staff. (I # got help from Matt.) # def main(): # numlist = [] # freqlist = [] # print("Hello! I will calculate the longest sequence of numbers in a list.") # print("Type your list of numbers and then type end.") # num = (input("Please enter a number: ")) # while num!= "end": # numlist.append(int(num)) # num = ((input("Please enter a number: "))) # print(numlist) # freq = 1 # currfreq = 1 # numfreq = 0 # for i in range(len(numlist)-1): # if numlist[i] == numlist[i+1]: # currfreq += 1 # if currfreq > freq: # freq = currfreq # currfreq = 1 # numfreq = numlist[i] # print("The most frequent number was "+str(numfreq)+" which was printed "+str(freq)+" times.") # main()
true
35f1a4243a2a56315eee8070401ee4f8dc38bf9c
JordanJLopez/cs373-tkinter
/hello_world_bigger.py
888
4.3125
4
#!/usr/bin/python3 from tkinter import * # Create the main tkinter window window = Tk() ### NEW ### # Set window size with X px by Y px window.geometry("500x500") ### NEW ### # Create a var that will contain the display text text = StringVar() # Create a Message object within our Window window_message = Message(window, textvariable = text) # Set the display text text.set("HELLO WORLD") # Compile the message with the display text ### NEW ### ## Notable .config Attributes: # anchor: Orientation of text # bg: Background color # font: Font of text # width: Width of text frame # padx: Padding on left and right # pady: Padding on top and bottom # and more! window_message.config(width=500, pady=250, font=("Consolas", 60), bg = 'light blue') ### NEW ### window_message.pack() # Start the window loop window.mainloop() exit()
true
4df8eadf0fe84ff3b194ac562f24a94b778a2588
Zioq/Algorithms-and-Data-Structures-With-Python
/7.Classes and objects/lecture_3.py
2,395
4.46875
4
# Special methods and what they are # Diffrence between __str__ & __repr__ """ str() is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. if __repr__ is defined, and __str__ is not, the object will behave as though __str__=__repr__. This means, in simple terms: almost every object you implement should have a functional __repr__ that’s usable for understanding the object. Implementing __str__ is optional """ class Student: def __init__(self, first, last, courses=None ): self.first_name = first self.last_name = last if courses == None: self.courses = [] else: self.courses = courses def add_course(self, new_course): if new_course not in self.courses: self.courses.append(new_course) else: print(f"{self.first_name} is already enrolled in the {new_course} course") def remove_course(self, remove_course): if remove_course in self.courses: self.courses.remove(remove_course) else: print(f"{remove_course} not found") def __len__(self): return len(self.courses) def __repr__(self): return f"Sturdent('{self.first_name}', '{self.last_name}', '{self.courses}')" def __str__(self): return f"First name: {self.first_name.capitalize()}\nLast name: {self.last_name.capitalize()}\nCourses: {', '.join(map(str.capitalize, self.courses))}" courses_1 = ['python', 'go', 'javascript'] courses_2 = ['java', 'go', 'c'] # Create new object of class robert = Student("Robert", "Han") john = Student("John", "Smith",courses_2) print(robert.first_name, robert.last_name, robert.courses) print(john.first_name, john.last_name, john.courses) # Add new course using a method john.add_course("java") robert.add_course("PHP") print(robert.first_name, robert.last_name, robert.courses) # Remove course using a method john.remove_course("c") john.remove_course("c") john.remove_course("python") print(john.first_name, john.last_name, john.courses) # use __str__ method print(robert) print(john) # use __dict__ method print(robert.__dict__) # use repre method print(repr(robert)) print(repr(john)) # use len functionality print(len(robert)) # return how many courses robert enrolled.
true
835fff2341216766489b87ac7682ef49a47fb713
Zioq/Algorithms-and-Data-Structures-With-Python
/1.Strings,variables/lecture_2.py
702
4.125
4
# concatenation, indexing, slicing, python console # concatenation: Add strings each other message = "The price of the stock is:" price = "$1110" print(id(message)) #print(message + " " +price) message = message + " " +price print(id(message)) # Indexing name = "interstella" print(name[0]) #print i # Slicing # [0:5] first num is start point, second num is stop point +1, so it means 0~4 characters print(name[0:5]) # print `inter` #[A:B:C] -> A: Start point, B: Stop +1, C: Step size nums ="0123456789" print(nums[2:6]) # output: 2345 print(nums[0:6:2]) # output: 024 print(nums[::2]) # output : 02468 print(nums[::-1]) # -1 mena backward step so, it will reverse the array. output: 9876543210
true
9123640f03d71649f31c4a6740ba9d1d3eca5caf
Zioq/Algorithms-and-Data-Structures-With-Python
/17.Hashmap/Mini Project/project_script_generator.py
1,946
4.3125
4
# Application usage ''' - In application you will have to load data from persistent memory to working memory as objects. - Once loaded, you can work with data in these objects and perform operations as necessary Exmaple) 1. In Database or other data source 2. Load data 3. Save it in data structure like `Dictionary` 4. Get the data from the data structure and work with process data as necessary 5. Produce output like presentation or update data and upload to the Database etc In this project we follow those steps like this 1. Text file - email address and quotes 2. Load data 3. Populate the AlgoHashTable 4. Search for quotes from specific users 5. Present the data to the console output ''' # Eamil address and quotes key-value data generator from random import choice from string import ascii_lowercase as letters list_of_domains = ['yaexample.com','goexample.com','example.com'] quotes = [ 'Luck is what happens when preparation meets opportunity', 'All cruelty springs from weakness', 'Begin at once to live, and count each separate day as a separate life', 'Throw me to the wolves and I will return leading the pack'] def generate_name(lenght_of_name): return ''.join(choice(letters) for i in range(lenght_of_name)) def get_domain(list_of_domains): return choice(list_of_domains) def get_quotes(list_of_quotes): return choice(list_of_quotes) def generate_records(length_of_name, list_of_domains, total_records, list_of_quotes): with open("data.txt", "w") as to_write: for num in range(total_records): key = generate_name(length_of_name)+"@"+get_domain(list_of_domains) value = get_quotes(quotes) to_write.write(key + ":" + value + "\n") to_write.write("mashrur@example.com:Don't let me leave Murph\n") to_write.write("evgeny@example.com:All I do is win win win no matter what!\n") generate_records(10, list_of_domains, 100000, quotes)
true
517611d9663ae87acdf5fed32099ec8dcf26ee76
Zioq/Algorithms-and-Data-Structures-With-Python
/20.Stacks and Queues/stack.py
2,544
4.25
4
import time class Node: def __init__(self, data = None): ''' Initialize node with data and next pointer ''' self.data = data self.next = None class Stack: def __init__(self): ''' Initialize stack with stack pointer ''' print("Stack created") # Only add stack pointer which is Head self.stack_pointer = None # Push - can only push (add) an item on top of the stack (aka head or stack pointer) def push(self,x): ''' Add x to the top of stack ''' if not isinstance(x, Node): x = Node(x) print (f"Adding {x.data} to the top of stack") # If the Stack is empty, set the stack point as x, which is just added. if self.is_empty(): self.stack_pointer = x # If the Stack has some Node else: x.next = self.stack_pointer self.stack_pointer = x # Pop - can only remove an item on top of the stack (aka head or stack pointer) def pop(self): if not self.is_empty(): print("Removing node on top of stack") curr = self.stack_pointer self.stack_pointer = self.stack_pointer.next curr.next = None return curr.data else: return "Stack is empty" def is_empty(self): '''return True if stack is empty, else return false''' return self.stack_pointer == None # peek - view value on top of the stack (aka head or stack pointer) def peek(self): '''look at the node on top of the stack''' if not self.is_empty(): return self.stack_pointer.data def __str__(self): print("Printing Stack state...") to_print = "" curr = self.stack_pointer while curr is not None: to_print += str(curr.data) + "->" curr = curr.next if to_print: print("Stack Pointer") print(" |") print(" V") return "[" + to_print[:-2] + "]" return "[]" my_stack = Stack() print("Checking if stack is empty:", my_stack.is_empty()) my_stack.push(1) time.sleep(2) my_stack.push(2) print(my_stack) time.sleep(2) my_stack.push(3) time.sleep(2) my_stack.push(4) time.sleep(2) print("Checking item on top of stack:", my_stack.peek()) time.sleep(2) my_stack.push(5) print(my_stack) time.sleep(2) print(my_stack.pop()) time.sleep(2) print(my_stack.pop()) print(my_stack) time.sleep(2) my_stack.push(4) print(my_stack) time.sleep(2)
true
0be4e99dbd9d44d1e06064a98e038fae55dec91f
oilbeater/projecteuler
/Multiples_of_3_and_5.py
1,058
4.125
4
''' Created on 2013-10-24 @author: oilbeater Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' import timeit def sol1(): return sum((i for i in range(1000) if i % 3 == 0 or i % 5 == 0)) def sol2(): threes = sum((i * 3 for i in range(1000 / 3 + 1))) fives = sum((i * 5 for i in range(1000 / 5))) fifteens = sum((i * 15 for i in range(1000 / 15 + 1))) return threes + fives - fifteens def sol3(): threes = (1 + 1000 / 3) * 3 * (1000 / 3) / 2 fives = (1 + 1000 / 5 - 1) * 5 / 2 * (1000 / 5 - 1) fifteens = (1 + 1000 / 15) * 15 * (1000 / 15) / 2 return threes + fives - fifteens print str(sol1()) print str(sol2()) print str(sol3()) print timeit.timeit('sol1()', "from __main__ import sol1", number=100000) print timeit.timeit('sol2()', "from __main__ import sol2", number=100000) print timeit.timeit('sol3()', "from __main__ import sol3", number=100000)
false
0d624fefe156321ad52de0d0c4ae42e9cf04d781
XZZMemory/xpk
/Question13.py
1,007
4.15625
4
'''输入2个正整数lower和upper(lower≤upper≤100),请输出一张取值范围为[lower,upper]、且每次增加2华氏度的华氏-摄氏温度转换表。 温度转换的计算公式:C=5×(F−32)/9,其中:C表示摄氏温度,F表示华氏温度。 输入格式: 在一行中输入2个整数,分别表示lower和upper的值,中间用空格分开。 输出格式: 第一行输出:"fahr celsius" 接着每行输出一个华氏温度fahr(整型)与一个摄氏温度celsius(占据6个字符宽度,靠右对齐,保留1位小数)。只有摄氏温度输出占据6个字符, 若输入的范围不合法,则输出"Invalid."。 ''' lower, upper = input().split() lower, upper = int(lower), int(upper) if lower <= upper and upper <= 100: print("fahr celsius") while lower <= upper: result = 5 * (lower - 32) / 9.0 print("{:d}{:>6.1f}".format(lower, result)) # 只有摄氏温度输出占6个字符 lower += 2 else: print("Invalid.")
false
76a3faf2f22c74922f3a9a00b3f2380ad878b633
XZZMemory/xpk
/Question12.py
593
4.15625
4
'''本题要求将输入的任意3个整数从小到大输出。 输入格式: 输入在一行中给出3个整数,其间以空格分隔。 输出格式: 在一行中将3个整数从小到大输出,其间以“->”相连。''' a, b, c = input().split() a, b, c = int(a), int(b), int(c) # 小的赋值给变量a,大的赋值给变量b if a > b: temp = a a = b b = temp if c < a: print(str(c) + "->" + str(a) + "->" + str(b)) else: # c<a if c < b: print(str(a) + "->" + str(c) + "->" + str(b)) else: print(str(a) + "->" + str(b) + "->" + str(c))
false
002c584b14e9af36fe9db5858c64711ec0421533
PaulSayantan/problem-solving
/CODEWARS/sum_of_digits.py
889
4.25
4
''' Digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. ''' import unittest def digitalRoot(n:int): if n < 10 and n > 0: return n add = 0 while n != 0: add += n % 10 n = n // 10 if add > 9: return digitalRoot(int(add)) else: return int(add) class digitRootTest(unittest.TestCase): def test1(self): self.assertEqual(digitalRoot(16), 7) def test2(self): self.assertEqual(digitalRoot(942), 6) def test3(self): self.assertEqual(digitalRoot(132189), 6) def test4(self): self.assertEqual(digitalRoot(493193), 2) if __name__ == "__main__": unittest.main()
true
96487cf3863ed2216c6ad83109b16e98c8955b3c
SeesawLiu/py
/abc/func/first_class_functions.py
2,150
4.34375
4
# Functions Are Objects # ===================== def yell(text): return text.upper() + '!' print(yell('hello')) bark = yell print(bark('woof')) # >>> del yell # >>> yell('hello?') # NameError: name 'yell' is not defined # >>> bark('hey') # HEY print(bark.__name__) # Functions Can Be Stored In Data Structures # ========================================== funcs = [bark, str.lower, str.capitalize] print(funcs) for f in funcs: print(f, f("hi there")) print(funcs[0]("yo man")) # Functions Can Be Passed To Other Functions # ========================================== def greet(func): greeting = func("Hi, I'm Python") print(greeting) greet(yell) def whisper(text): return text.lower() + '...' greet(whisper) print(map(yell, ['Hi', 'Hey', 'hi'])) # Functions Can Be Nested # ======================= def speak(text): def whisper(t): return t.lower() + '...' return whisper(text) print(speak("hi man")) # >>> whisper('Yo') # NameError: "name 'whisper' is not defined" # # >>> speak.whisper # AttributeError: "'function' object has no attribute 'whisper'" def get_speak_func(volume): def whisper(text): return text.lower() + '...' def yell(text): return text.upper() + '!' if volume > 0.5: return yell else: return whisper print(get_speak_func(0.3)) print(get_speak_func(0.6)) speak_func = get_speak_func(0.8) print(speak_func("oooooooooh")) # Functions Can Capture Local State # ================================= def get_speak_func2(text, volume): def whisper(): return text.lower() + '...' def yell(): return text.upper() + '!' if volume > 0.5: return yell else: return whisper print(get_speak_func2("bitch", 0.9)()) def make_adder(n): def add(x): return x + n return add plus_3 = make_adder(3) plus_5 = make_adder(5) print(plus_3(4)) print(plus_5(4)) # Objects Can Behave Like Functions # ================================= class Adder: def __init__(self, n): self.n = n def __call__(self, x): return self.n + x plus_3 = Adder(3) print(plus_3(7))
false
f99bcedd6bed96991fb8fdf06eba27708ef867b1
dks1018/CoffeeShopCoding
/2021/Code/Python/DataStructures/dictionary_practice1.py
1,148
4.25
4
myList = ["a", "b", "c", "d"] letters = "abcdefghijklmnopqrstuvwxyz" numbers = "123456789" newString = " Mississippi ".join(numbers) print(newString) fruit = { "Orange":"Orange juicy citrus fruit", "Apple":"Red juicy friend", "Lemon":"Sour citrus fruit", "Lime":"Green sour fruit" } veggies = { "Spinach":"Katia does not like it", "Brussel Sprouts":"No one likes them", "Brocolli":"Makes people gassy" } veggies.update(fruit) print(veggies) superDictionary = fruit.copy() superDictionary.update(veggies) print(superDictionary) while True: user_input = str(input("Enter Fruit or Veggie: ")) if user_input == "quit": break if user_input in superDictionary or fruit or veggies: print(superDictionary.get(user_input)) if user_input not in superDictionary and fruit and veggies: print("Hey that item is not in the list, but let me add it for you!!") fruit_veggie = str(input("Enter your Fruit or Veggie: ")) desc = str(input("Enter the taste: ")) superDictionary[fruit_veggie] = desc print(superDictionary[fruit_veggie])
true
1c4e7bf09af67655c22846ecfc1312db04c3bfe1
dks1018/CoffeeShopCoding
/2021/Code/Python/Tutoring/Challenge/main.py
967
4.125
4
import time # You can edit this code and run it right here in the browser! # First we'll import some turtles and shapes: from turtle import * from shapes import * # Create a turtle named Tommy: tommy = Turtle() tommy.shape("turtle") tommy.speed(10) # Draw three circles: draw_circle(tommy, "green", 50, 0, 100) draw_circle(tommy, "green", 50, 0, 200) draw_circle(tommy, "blue", 50, 75, 25) draw_circle(tommy, "red", 50, -75, 25) # Draw three Squares draw_square(tommy, "green", 50, -50, -200) draw_square(tommy, "green", 50, -50, -300) draw_square(tommy, "blue", 50, 50, -200) draw_square(tommy, "red", 50, -150, -200) # Write a little message: tommy.penup() tommy.goto(0,-50) tommy.color("black") tommy.write("Darius's New Python Challenge", None, "center", "16pt 20") tommy.goto(0,-80) # Try changing draw_circle to draw_square, draw_triangle, or draw_star #The turtle program is finished turtle.done() #Dont close out GUI for (x) seconds #time.sleep(10)
true
760537b38c1899088736d0f4a3ba3d27fe3a29c5
dks1018/CoffeeShopCoding
/2021/Code/Python/Searches/BinarySearch/BinarySearch.py
1,779
4.15625
4
low = 1 high = 1000 print("Please think of a number between {} and {}".format(low, high)) input("Press ENTER to start") guesses = 1 while low != high: print("\tGuessing in the range of {} and {}".format(low, high)) # Calculate midpoint between low adn high values guess = low + (high - low) // 2 high_low = input("My guess is {}. Should I guess Higher or Lower?" "Enter h or l or c if my guess was correct " .format(guess)).casefold() if high_low == "h": # Guess higher.The low end of the range becomes 1 greater than the guess. low = guess + 1 elif high_low == "l": # Guess lower.The high end of the range becomes one less than the guess high = guess - 1 elif high_low == "c": print("I got it in {} guesses!".format(guesses)) break else: print("Please enter h,l, or c") guesses += 1 else: print("You thought of the number {}".format(low)) print("I got it in {} guesses".format(guesses)) #I am choosing 129 # with 1000 number what I want to do is be able to guess the users number within 10 guesses # to do this i need to continue to devide in half the high form the low # then establish a new high and low # if the number is 22 and the high is 100 and low is 0 first computer says # 1 is you number 50? higher or lower # lower, so high is 100-1 / 2 equals 49.5 rounded down high now equals 49 low now equals 0 # 2 is the number 25 or higher or lower # lower so high is 49-1 / 2 is 24 # 3 is you number 12, # it is higher so lower = guess + 1 # lower is 13 high is 24 # 4 is you number 18, # no high # 5 lower is 19, is your number 21 # no high lower equals 22 high equals 24 # 6 is your number 23, no lower # 7 your number is 22
true
6ebdc47b984d3f9b7b65663b2ba01f9b54fc7edf
dks1018/CoffeeShopCoding
/2021/Code/Python/Exercises/Calculator2.py
1,480
4.1875
4
# Variable statements Number1 = input("Enter your first number: ") Number2 = input("Enter your second number: ") NumberAsk = input("Would you like to add a third number? Y or N: ") if NumberAsk == str("Y"): Number3 = input("Please enter your third number: ") Operation = input("What operation would you like to perform on these numbers? +, -, *, or /? ") # Operations Sum = (int(Number1) + int(Number2)) # noinspection PyUnboundLocalVariable Sum2 = (int(Number1) + int(Number2) + int(Number3)) Difference = (int(Number1) - int(Number2)) Difference2 = (int(Number1) - int(Number2) - int(Number3)) Product = (int(Number1) * int(Number2)) Product2 = (int(Number1) * int(Number2) * int(Number3)) Quotient = (int(Number1) / int(Number2)) Quotient2 = (int(Number1) / int(Number2) / int(Number3)) # Variable operations Addition = "+" Subtraction = "-" Multiplication = "*" Division = "/" # Conditionals if Operation == str("+") and NumberAsk == str("N"): print(Sum) if Operation == str("+") and NumberAsk == str("Y"): print(Sum2) if Operation == str("-") and NumberAsk == str("N"): print(Difference) if Operation == str("-") and NumberAsk == str("Y"): print(Difference2) if Operation == str("*") and NumberAsk == str("N"): print(Product) if Operation == str("*") and NumberAsk == str("Y"): print(Product2) if Operation == str("/") and NumberAsk == str("N"): print(Quotient) if Operation == str("/") and NumberAsk == str("Y"): print(Quotient2)
true
7b98a668260b8d5c0b729c6687e6c0a878574c9d
ajanzadeh/python_interview
/games/towers_of_hanoi.py
1,100
4.15625
4
# Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: # 1) Only one disk can be moved at a time. # 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. # 3) No disk may be placed on top of a smaller disk. # Take an example for 2 disks : # Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'. # # Step 1 : Shift first disk from 'A' to 'B'. # Step 2 : Shift second disk from 'A' to 'C'. # Step 3 : Shift first disk from 'B' to 'C'. # # The pattern here is : # Shift 'n-1' disks from 'A' to 'B'. # Shift last disk from 'A' to 'C'. # Shift 'n-1' disks from 'B' to 'C'. def tower(n,source,helper,dest): if n == 1: print("move disk",n, "from", source,"to",dest) return else: tower(n-1,source,dest,helper) print("move disk",n,"from",source,"to", dest) tower(n-1,helper,source,dest) tower(5,"a","b","c")
true
ca091bae52a3e79cece2324fe946bc6a52ca6c2f
mrmuli/.bin
/scripts/python_datastructures.py
2,019
4.15625
4
# I have decided to version these are functions and operations I have used in various places from mentorship sessions # articles and random examples, makes it easier for me to track on GitHub. # Feel free to use what you want, I'll try to document as much as I can :) def sample(): """ Loop through number range 1 though 11 and multiply by 2 """ total = 0 # to be explicit about even numbers, you can add a step to range as: range(2,11,2) for number in range(2, 101, 2): # If the number is 4, skip and continue if number == 4: continue total += number # Calculate the product of number and 2 product = number * 2 # Print out the product in a friendly way print(number, '* 2 = ', product) # sample() def password_authenticate(): """ A very simple way to validate or authenticate """ # set random value and Boolean check. (This is subject to change, on preference.) user_pass = "potato" valid = False while not valid: password = input("Please enter your password: ") if password == user_pass: print("welcome back user!") valid = True else: print("Wrong password, please try again.") print("bye!") # password_authenticate() # use of pass, continue and break def statements_demo(): for number in range(0, 200): if number == 0: continue elif number % 3 != 0: continue elif type(number) != int: break else: pass print(number) # statements_demo() def nested_example(): for even in range(2, 11, 2): for odd in range(1, 11, 2): val = even + odd print(even, "+", odd, "=", val) print(val) # nested_example() def randome_args(*args): for value in args: if type(value) == int: continue print(value) # randome_args(1,2,3,4,"five","six","seven",8,"nine",10)
true
356122c10a2bb46ca7078e78e991a08781c46254
KingHammer883/21.Testing-for-a-Substring-with-the-in-operator.py
/21.Testing-for-Substring-With-the-in-operator.py
752
4.40625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 18, 2019 File: Testing for a Substring with the in operator @author: Byen23 Another problem involves picking out strings that contains known substrings. FOr example you might wnat to pick out filenames with a .txt extension. A slice would work for this but using Python's in operator is the right operand is the string to be searched. The operator in returns True if the target string is somewhere in teh search string, or False otherwise. The next code segment traverses a list of filenames and prints just the filenames taht have a .txt extension: """ filelist = ["myfile.txt", "myprogram.exe", "yourfile.txt"] for fileName in filelist: if ".txt" in fileName: print(fileName)
true
0606ac38799bfe01af2feda28a40d7b863867569
PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch
/12. Downloading data from input/downloading-data.py
260
4.15625
4
print("Program that adds two numbers to each other") a = int(input("First number: ")) b = int(input("Second number: ")) #CASTING allows you to change ONE type of variable to another type of variable print("Sum of a =", a, "+", "b =", b, "is equal to", a + b)
true
9dbcec24d2b156aa7f69a8bf1e65ade631e0eea3
sdelpercio/cs-module-project-recursive-sorting
/src/sorting/sorting.py
2,202
4.1875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [None] * elements # Your code here while None in merged_arr: if not arrA: popped = arrB.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif not arrB: popped = arrA.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif arrA[0] < arrB[0]: popped = arrA.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped elif arrB[0] < arrA[0]: popped = arrB.pop(0) first_instance = merged_arr.index(None) merged_arr[first_instance] = popped else: continue return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # base case if len(arr) == 0 or len(arr) == 1: return arr # recursive case elif len(arr) == 2: return merge([arr[0]], [arr[1]]) else: middle = (len(arr) - 1) // 2 left = arr[:middle] right = arr[middle:] return merge(merge_sort(left), merge_sort(right)) 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): swapped = False while True: swapped = False for i in range(start, end): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] swapped = True if swapped == False: break return arr def merge_sort_in_place(arr, l, r): # base case if l < r: middle = l + (r - l) // 2 merge_sort_in_place(arr, l, middle) merge_sort_in_place(arr, middle + 1, r) merge_in_place(arr, l, middle, r) return arr
true
0684f210b036b64b9821110bdb976908deeca8ca
Guilherme758/Python
/Estrutura Básica/Exercício i.py
374
4.375
4
# Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. # C = 5 * ((F-32) / 9). fahrenheit = float(input("Informe a temperatura em graus fahrenheit: ")) celsius = 5 * (fahrenheit-32)/9 if celsius.is_integer() == True: celsius = int(celsius) print("A temperatura em celsius é:", f'{celsius}ºC')
false
d4393db248c28cafa20467c616da8428496550fb
Guilherme758/Python
/Estrutura Básica/Exercício j.py
332
4.25
4
# Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit. celsius = float(input('Passe a temperatura em celsius: ')) fahrenheit = 9*(celsius/5)+32 if fahrenheit.is_integer() == True: fahrenheit = int(fahrenheit) print("A temperatura em fahrenheit é:", f'{fahrenheit}ºF')
false
e0f808f1c93b832eeb29f9133a86ce99dbbe678d
NuradinI/simpleCalculator
/calculator.py
2,097
4.40625
4
#since the code is being read from top to bottom you must import at the top import addition import subtraction import multiplication import division # i print these so that the user can see what math operation they will go with print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") #this is a while loop, different from the for loop in that it will not run 'x' amount of times, #a while loop runs as a set of code if the condition defined is true # here i create the while loop by writing while and then true so that the code statements below #only execute when true, i add the : to start it up while True: #here i define the variable Userchoice, then i put the input function which allows for user input # i give the user a choice to enter values UserChoice = input("Choose (1,2,3,4): ") #if the users choice is 1 2 3 4 run this code if UserChoice in ('1', '2', '3', '4'): #the code that is run is a input in which the first number is a variable that stores the users input num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) #if the userschoice is equal to one, print the value of num1 concatonate with a string that shows #that the content was added and concatonate with a = and then run the function that acc does the math #that is now called back so the value of x, y is now the variables num1 and num2 if UserChoice == '1': print(num1, "+", num2, "=", addition.addNum(num1, num2)) elif UserChoice == '2': print(num1, "-", num2, "=", subtraction.subtractNum(num1, num2)) elif UserChoice == '3': print(num1, "*", num2, "=", multiplication.multiplyNum(num1, num2)) elif UserChoice == '4': print(num1, "/", num2, "=", division.divideNum(num1, num2)) #we use the break to stop the code, otherwise the if the conditions remain true the code #will run up again, its basically a period i think break else: #if they dont chose any print invalid input print("pick a num 1 - 4 silly ")
true
8ba9f444797916c33a00ce7d7864b1fa60ae6f24
Bongkot-Kladklaen/Programming_tutorial_code
/Python/Python_basic/Ex24_UserInput.py
271
4.1875
4
#* User Input """ Python 3.6 uses the input() method. Python 2.7 uses the raw_input() method. """ #* Python 3.6 username = input("Enter username:") print("Username is: " + username) #* Python 2.7 username = raw_input("Enter username:") print("Username is: " + username)
true
dc6515bb3acd810a8e1d86aa59033b660a368594
Yibangyu/oldKeyboard1
/1023.py
381
4.1875
4
#!/usr/bin/python import re preg = input() string = input() result_string = '' preg = preg.upper() + preg.lower() if '+' in preg: preg = preg+'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if preg: for char in string: if char in preg: continue else: result_string = result_string + char print(result_string) else: print(string)
false
fe462e3d26b866c500619db330b4e7c027189f85
Grigorii60/geekbrains_DZ
/task_1.py
730
4.15625
4
name = input('Как твое имя? : ') print(f'Привет {name}, а мое Григорий.') age = int(input('А сколько тебе лет? : ')) my_age = 36 if age == my_age: print('Мы ровестники!') elif age > my_age: print(f'{name} ты старше меня на {age - my_age} лет.') else: print(f'{name} ты младше меня на {my_age - age} лет.') result = input('Надеюсь я понял задание и сделал все верно? : ') if result == ["Да", "да", "Yes", "yes"]: print(f'{name} отлично, тогда я перехожу к следующему!') else: print(f'{name} жаль, но я обещаю стараться!)))')
false
d982dbcd9d34ecfd77824b309e688f9e077093d5
gcvalderrama/python_foundations
/DailyCodingProblem/phi_montecarlo.py
1,292
4.28125
4
import unittest # The area of a circle is defined as πr ^ 2. # Estimate π to 3 decimal places using a Monte Carlo method. # Hint: The basic equation of a circle is x2 + y2 = r2. # we will use a basic case with r = 1 , means area = π ^ 2 and x2 + y2 <=1 # pi = The ratio of a circle's circumference to its diameter # https://www.youtube.com/watch?v=PLURfYr-rdU import random def get_rand_number(min_value, max_value): """ This function gets a random number from a uniform distribution between the two input values [min_value, max_value] inclusively Args: - min_value (float) - max_value (float) Return: - Random number between this range (float) """ range = max_value - min_value choice = random.uniform(0, 1) return min_value + range * choice def estimate(): square_points = 0 circle_points = 0 for i in range(1000000): x = get_rand_number(0, 1) y = get_rand_number(0, 1) dist = x ** 2 + y ** 2 if dist <= 1: circle_points += 1 square_points += 1 pi = 4 * (circle_points / square_points) return pi class Test(unittest.TestCase): def test_monte_carlo(self): print(estimate()) if __name__ == "__main__": unittest.main()
true
24cf6864b5eb14d762735a27d79f96227438392f
ramalldf/data_science
/deep_learning/datacamp_cnn/image_classifier.py
1,545
4.28125
4
# Image classifier with Keras from keras.models import Sequential from keras.layers import Dense # Shape of our training data is (50, 28, 28, 1) # which is 50 images (at 28x28) with only one channel/color, black/white print(train_data.shape) model = Sequential() # First layer is connected to all pixels in original image model.add(Dense(10, activation='relu', input_shape=(784,))) # 28x28 = 784, so one input from every pixel # More info on the Dense layer args: https://keras.io/api/layers/core_layers/dense/ # First arg is units which corresponds to dimensions of output model.add(Dense(10, activation='relu')) model.add(Dense(10, activation='relu')) # Unlike hidden layers, output layer has 3 for output (for 3 classes well classify) # and a softmax layer which is used for classifiers model.add(Dense(3, activation='softmax')) # Model needs to be compiled before it is fit. loss tells it to optimize for classifier model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # Prepare data (needs to be tabular so 50 rows and 784 cols) train_data = train_data.reshape((50, 784)) # Fit model # To avoid overfiting we set aside 0.2 of images for validation set # We'll send data through NN 3 times (epochs) and test on that validation set model.fit(train_data, train_labels, validation_split=0.2, epochs=3) # Evaluate on test set that's not evaluation set using the evaluation function test_data = test_data.reshape((10, 784)) model.evaluate(test_data, test_labels)
true
60b60160f8677cd49552fedcf862238f9128f326
Prash74/ProjectNY
/LeetCode/1.Arrays/Python/reshapematrix.py
1,391
4.65625
5
""" You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Explanation: The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. Example 2: Input: nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] Explanation: There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. Note: The height and width of the given matrix is in range [1, 100]. The given r and c are all positive. """ def matrixReshape(nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ if r*c != len(nums)*len(nums[0]): return nums nums = [i for item in nums for i in item] val = [] for i in range(0, len(nums), c): val.append(nums[i:i+c]) return val nums = [[1, 2], [3, 4]] r = 1 c = 4 print matrixReshape(nums, r, c)
true
ea57b522f2bd14f19df61477c8141c238401f1b8
DavidCasa/tallerTkinter
/Ejercicio4.py
559
4.125
4
############## EJERCICIOS 4 ################ from tkinter import * root = Tk() v = IntVar() #Es un pequeño menú, en el cual se aplica Radiobuttons para hacer la selección de opciones Label(root, text="""Choose a programming language:""", justify = LEFT, padx = 20).pack() Radiobutton(root, text="Python", padx = 20, variable=v, value=1).pack(anchor=W) Radiobutton(root, text="Perl", padx = 20, variable=v, value=2).pack(anchor=W) mainloop()
false
3d999f7baa9c6610b5b93ecf59506fefd421ff86
Minglaba/Coursera
/Conditions.py
1,015
4.53125
5
# equal: == # not equal: != # greater than: > # less than: < # greater than or equal to: >= # less than or equal to: <= # Inequality Sign i = 2 i != 6 # this will print true # Use Inequality sign to compare the strings "ACDC" != "Michael Jackson" # Compare characters 'B' > 'A' # If statement example age = 19 #age = 18 #expression that can be true or false if age > 18: #within an indent, we have the expression that is run if the condition is true print("you can enter" ) #The statements after the if statement will run regardless if the condition is true or false print("move on") # Condition statement example album_year = 1990 if(album_year < 1980) or (album_year > 1989): print ("Album was not made in the 1980's") else: print("The Album was made in the 1980's ") # Write your code below and press Shift+Enter to execute album_year = 1991 if album_year < 1980 or album_year == 1991 or album_year == 1993: print(album_year) else: print("no data")
true
f256746a37c0a050e56aafca1315a517686f96c8
luxorv/statistics
/days_old.py
1,975
4.3125
4
# Define a daysBetweenDates procedure that would produce the # correct output if there was a correct nextDay procedure. # # Note that this will NOT produce correct outputs yet, since # our nextDay procedure assumes all months have 30 days # (hence a year is 360 days, instead of 365). # def isLeapYear(year): if year%4 != 0: return False elif year%100 !=0: return True elif year%400 !=0: return False else: return True def daysInMonth(month, year): daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month == 2 and isLeapYear(year): daysOfMonths[month-1] += 1 return daysOfMonths[month-1] def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < daysInMonth(month, year): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def daysBetweenDates(year1, month1, day1, year2, month2, day2): """Returns the number of days between year1/month1/day1 and year2/month2/day2. Assumes inputs are valid dates in Gregorian calendar, and the first date is not after the second.""" # YOUR CODE HERE! days = 0 second_date = (year2, month2, day2) first_date = (year1, month1, day1) assert not first_date > second_date while first_date < second_date: days += 1 first_date = nextDay(*first_date) return days def test(): test_cases = [((2012,1,1,2012,2,28), 58), ((2012,1,1,2012,3,1), 60), ((2011,6,30,2012,6,30), 366), ((2011,1,1,2012,8,8), 585 ), ((1900,1,1,1999,12,31), 36523)] for (args, answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" test()
true
bf6d09ae3d5803425cf95dd4e53fe62dad41fda0
reveriess/TarungLabDDP1
/lab/01/lab01_f.py
618
4.6875
5
''' Using Turtle Graphics to draw a blue polygon with customizable number and length of sides according to user's input. ''' import turtle sides = int(input("Number of sides: ")) distance = int(input("Side's length: ")) turtle.color('blue') # Set the pen's color to blue turtle.pendown() # Start drawing deg = 360 / sides # Calculate the turn for i in range(sides): turtle.forward(distance) # By using loop, turn and turtle.left(deg) # move the turtle forward turtle.hideturtle() # Hide the turtle/arrow turtle.exitonclick() # Close the window on click event
true
7ebc2621de57aba29a68be3d6dacaa16ebf4c4dc
yywecanwin/PythonLearning
/day03/13.猜拳游戏.py
657
4.125
4
# -*- coding: utf-8 -*- # author:yaoyao time:2019/9/28 import random # 写一个死循环 while True: # 1.从键盘录入一个1-3之间的数字表示自己出的拳 self = int(input("请出拳")) # 2.定义一个变量赋值为1,表示电脑出的拳 computer = random.randint(1,3) print(computer) if((self == 1 and computer == 2) or (self == 2 and computer == 3) or (self == 3 and computer == 1)): print("我又赢了,我妈喊我 回家吃饭了") break elif self == computer: print("平局,我们在杀一盘") else: print("不行了,我要和你杀到天亮") break
false
eb42aaa882346528732e069a8cde5e7ad92155d0
yywecanwin/PythonLearning
/day04/07.字符串常见的方法-查找-统计-分割.py
885
4.25
4
# -*- coding: utf-8 -*- # author:yaoyao time:2019/9/28 s1 = "hello python" # 1.查找"o"在s1中第一次出现的位置:s1.find() print(s1.find("aa")) # -1 print(s1.find("o",6,11)) # 10 print(s1.find("pyt")) # 6 print(s1.rfind("pyt")) # 6 """ index()方法,找不到将会报错 """ # print(s1.index("o", 6, 11)) # print(s1.index("aa")) #统计"o"出现的次数 print(s1.count("o")) print(s1.count("o",6,12)) #分割的方法:s.split(str) s2 = "hello python android" # 分割的结果是一个列表,把分割出来的几部分字符串作为元素放到列表中了 list1 = s2.split(" ") print(list1) # ['hello', 'python', 'android'] print(type(list1)) # <class 'list'> # 这个方法只能分割出三部分:左边部分,自己,右边部分 list2 = s2.partition(" ") print(list2) # ('hello', ' ', 'python android') print(type(list2)) # <class 'tuple'>
false
95ce77d9c77b94715837162ed9e85dac67f64053
yywecanwin/PythonLearning
/day04/15.元组.py
922
4.15625
4
# -*- coding: utf-8 -*- # author:yaoyao time:2019/10/5 """ 元组: 也是一个容器,可以存储多个元素,每一个元素可以是任何类型 元组是一个不可需改的列表,不能用于 增删改查操作,只能用于查询 定义格式: 定义非空元组 元组名 = (元素1,元素2,,,,,) 元组空元组 元组名 = () 定义只有一个元素的元组 元组名 = (元素1,) 什么时候使用元组村粗一组数据? 当那一组数据不允许修改时,需要使用元组存储 """ tuple1 = ("冬冬", "柳岩", "美娜") print(tuple1) # ('冬冬', '柳岩', '美娜') print(type(tuple1)) # <class 'tuple'> # 根据索引得到元组中的元素: 元组名[索引] print(tuple1[0]) print(tuple1[1]) print(tuple1[2]) # 定义只有一个元素的元组 tuple2 = (10,) print(tuple2) print(type(tuple2))
false
2c2b4f56fc3f3c0c76ba69866da852edcfbf8186
Anshikaverma24/to-do-app
/to do app/app.py
1,500
4.125
4
print(" -📋YOU HAVE TO DO✅- ") options=["edit - add" , "delete"] tasks_for_today=input("enter the asks you want to do today - ") to_do=[] to_do.append(tasks_for_today) print("would you like to do modifications with your tasks? ") edit=input("say yes if you would like edit your tasks - ") if edit=="yes": add=input("say yes if you would like add some more tasks - ") if add=="yes": added=input("enter the task you would like to add - ") to_do.append(added) delete=input('say yes if you would like delete your tasks - ') for i in range(len(to_do)): print(to_do[i]) if delete=="yes": delte=input("enter the task you want to delete - ") to_do.remove(delte) for i in range(len(to_do)): print(to_do[i]) print("NUMBER OF TASKS YOU HAVE TO DO TODAY") i=0 tasks=0 while i<len(to_do): tasks=tasks+1 i+=1 print(tasks) done_tasks=int(input("enter the total number of tasks that you have completed : ")) in_progress=int(input("enter the number of tasks which are in progress : ")) not_done=int(input("enter the number of tasks which you haven't done : ")) status=[done_tasks , in_progress , not_done] i=0 sum=0 while i<len(status): sum=sum+status[i] print(sum) i+=1 if sum>len(to_do): print("your tasks is more than total number of tasks, please check the tasks once") elif sum<len(to_do): print("your tasks is less than the total number of tasks,please check the tasks once") else: print("your schedule have been set")
true
6fd57771b4a4fdbd130e6d408cd84e02f89f48a4
Jayasuriya007/Sum-of-three-Digits
/addition.py
264
4.25
4
print ("Program To Find Sum of Three Digits") def addition (a,b,c): result=(a+b+c) return result a= int(input("Enter num one: ")) b= int(input("Enter num one: ")) c= int(input("Enter num one: ")) add_result= addition(a,b,c) print(add_result)
true
2da2d69eb8580ba378fac6dd9eff065e2112c778
sk24085/Interview-Questions
/easy/maximum-subarray.py
898
4.15625
4
''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array. Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nums = [1] Output: 1 Example 3: Input: nums = [5,4,-1,7,8] Output: 23 ''' class Solution: def maxSubArray(self, nums: List[int]) -> int: # sliding window len_nums = len(nums) if len_nums == 1: return nums[0] cur_sum, max_so_far, i, j = 0, -99999999, 0, 1 while(i<len_nums): cur_sum += nums[i] if cur_sum > max_so_far: max_so_far = cur_sum if cur_sum <= 0: cur_sum = 0 i += 1 return max_so_far
true
daa21099590ab6c4817de8135937e9872d2eb816
sk24085/Interview-Questions
/easy/detect-capital.py
1,464
4.34375
4
''' We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital, like "Google". Given a string word, return true if the usage of capitals in it is right. Example 1: Input: word = "USA" Output: true Example 2: Input: word = "FlaG" Output: false ''' class Solution: def allUpper(self,str): for char in str: ascii_code = ord(char) if ascii_code <65 or ascii_code >90: return False print('returning true') return True def allLower(self,str): for char in str: ascii_code = ord(char) if ascii_code <97 or ascii_code >122: return False return True def detectCapitalUse(self, word: str) -> bool: # case when only one letter exists if len(word) == 1: return True # get the first capital letter firstCapital = word[0].isupper() # get the second caspital letter secondCapital = word[1].isupper() # conditions if firstCapital and secondCapital: # all others should be upper return self.allUpper(word[1:]) elif firstCapital: return self.allLower(word[1:]) else: return self.allLower(word[1:])
true
bca49786c266839dc0da317a76d6af24b20816e5
mtahaakhan/Intro-in-python
/Python Practice/input_date.py
708
4.28125
4
# ! Here we have imported datetime and timedelta functions from datetime library from datetime import datetime,timedelta # ! Here we are receiving input from user, when is your birthday? birthday = input('When is your birthday (dd/mm/yyyy)? ') # ! Here we are converting input into birthday_date birthday_date = datetime.strptime(birthday, '%d/%m/%Y') # ! Here we are printing birthday date print('Birthday: ' + str(birthday_date)) # ! Here we are again just asking one day before from timedelta one_day = timedelta(days=1) birthday_eve = birthday_date - one_day print('Day before birthday: ' + str(birthday_eve)) # ! Now we will see Error Handling if we receive birthday date in spaces or ashes.
true
2937f2007681af5aede2a10485491f8d2b5092cf
mtahaakhan/Intro-in-python
/Python Practice/date_function.py
649
4.34375
4
# Here we are asking datetime library to import datetime function in our code :) from datetime import datetime, timedelta # Now the datetime.now() will return current date and time as a datetime object today = datetime.now() # We have done this in last example. print('Today is: ' + str(today)) # Now we will use timedelta # Here, from timedelta we are getting yesterdays date time one_day = timedelta(days=1) yesterday = today - one_day print('Yesterday was: ' + str(yesterday)) # Here, from timedelta we are getting last weeks date time one_week = timedelta(weeks=1) last_week = today - one_week print('Last week was: ' + str(last_week))
true
e797aa24ce9fbd9354c04fbbf853ca63e967c827
xtdoggx2003/CTI110
/P4T2_BugCollector_AnthonyBarnhart.py
657
4.3125
4
# Bug Collector using Loops # 29MAR2020 # CTI-110 P4T2 - Bug Collector # Anthony Barnhart # Initialize the accumlator. total = 0 # Get the number of bugs collected for each day. for day in range (1, 6): # Prompt the user. print("Enter number of bugs collected on day", day) # Input the number of bugs. bugs = int (input()) # Add bugs to toal. total = total + bugs # Display the total bugs. print("You have collected a total of", total, "bugs") # Psuedo Code # Set total = 0 # For 5 days: # Input number of bugs collected for a day # Add bugs collected to total number of bugs # Display the total bugs
true
6e7401d2ed0a82b75f1eaec51448f7f20476d46e
xtdoggx2003/CTI110
/P3HW1_ColorMix_AnthonyBarnhart.py
1,039
4.40625
4
# CTI-110 # P3HW1 - Color Mixer # Antony Barnhart # 15MAR2020 # Get user input for primary color 1. Prime1 = input("Enter first primary color of red, yellow or blue:") # Get user input for primary color 2. Prime2 = input("Enter second different primary color of red, yellow or blue:") # Determine secondary color and error if not one of three listed colors if Prime1 == "red" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "red": print("orange") elif Prime1 == "blue" and Prime2 == "yellow" or Prime1 == "yellow" and Prime2 == "blue": print("green") elif Prime1 == "blue" and Prime2 == "red" or Prime1 == "red" and Prime2 == "blue": print("purple") else: print("error") # Pseudocode # Ask user to input prime color one # Ask user to imput prime color two # Only allow input of three colors Red, Yellow, Blue # Determine the secondary color based off of user input # Display secondary color # Display error if any color outside of given perameters is input
true
c3ffa8b82e2818647adda6c69245bbc9841ffd76
tsuganoki/practice_exercises
/strval.py
951
4.125
4
"""In the first line, print True if has any alphanumeric characters. Otherwise, print False. In the second line, print True if has any alphabetical characters. Otherwise, print False. In the third line, print True if has any digits. Otherwise, print False. In the fourth line, print True if has any lowercase characters. Otherwise, print False. In the fifth line, print True if has any uppercase characters. Otherwise, print False.""" s = "6$%^#" alph = False alphanumeric = False digits = False lowercase = False uppercase = False if len(s) < 1000: for l in s: if l.isalpha(): alph = True if l.isdigit(): digits = True if l.isalnum(): alphanumeric = True if l.islower(): lowercase = True if l.isupper(): uppercase = True print(alphanumeric) print(alph) print(digits) print(lowercase) print(uppercase)
true
4d1605f77acdf29ee15295ba9077d47bc3f62607
zakwan93/python_basic
/python_set/courses.py
1,678
4.125
4
# write a function named covers that accepts a single parameter, a set of topics. # Have the function return a list of courses from COURSES # where the supplied set and the course's value (also a set) overlap. # For example, covers({"Python"}) would return ["Python Basics"]. COURSES = { "Python Basics": {"Python", "functions", "variables", "booleans", "integers", "floats", "arrays", "strings", "exceptions", "conditions", "input", "loops"}, "Java Basics": {"Java", "strings", "variables", "input", "exceptions", "integers", "booleans", "loops"}, "PHP Basics": {"PHP", "variables", "conditions", "integers", "floats", "strings", "booleans", "HTML"}, "Ruby Basics": {"Ruby", "strings", "floats", "integers", "conditions", "functions", "input"} } def covers(courses): answer = [] for key,value in COURSES.items(): if value.intersections(courses): answer.append(key) return answer # Create a new function named covers_all that takes a single set as an argument. # Return the names of all of the courses, in a list, where all of the topics # in the supplied set are covered. # For example, covers_all({"conditions", "input"}) would return # ["Python Basics", "Ruby Basics"]. Java Basics and PHP Basics would be excluded # because they don't include both of those topics. def covers_all(topics): answer = [] for course,value in COURSES.items(): if (value & topics) == topics: answer.append(course) return answer
true
6ce838e30b83b79bd57c65231de2656f63945486
prashant2109/django_login_tas_practice
/python/Python/oops/polymorphism_info.py
2,144
4.40625
4
# Method Overriding # Same method in 2 classes but gives the different output, this is known as polymorphism. class Bank: def rateOfInterest(self): return 0 class ICICI(Bank): def rateOfInterest(self): return 10.5 if __name__ == '__main__': b_Obj = Bank() print(b_Obj.rateOfInterest()) ##############################################################################################33 # Polymorphism with class class Cat: def __init__(self, name): self.name = name def info(self): print(f'My name is {self.name}. I belong to cat family.') def make_sound(self): print('meow') class Dog: def __init__(self, name): self.name = name def info(self): print(f'My name is {self.name}. I belong to Dog family.') def make_sound(self): print('Bark') cat = Cat('kitty') dog = Dog('tommy') # Here we are calling methods of 2 different class types with common variable 'animal' for animal in (cat, dog): print(animal.info()) print(animal.make_sound()) ############################################################################################################# class India(): def capital(self): print("New Delhi") def language(self): print("Hindi and English") class USA(): def capital(self): print("Washington, D.C.") def language(self): print("English") obj_ind = India() obj_usa = USA() for country in (obj_ind, obj_usa): country.capital() country.language() ######################################################################################################## class Bird: def intro(self): print("There are different types of birds") def flight(self): print("Most of the birds can fly but some cannot") class parrot(Bird): def flight(self): print("Parrots can fly") class penguin(Bird): def flight(self): print("Penguins do not fly") obj_bird = Bird() obj_parr = parrot() obj_peng = penguin() obj_bird.intro() obj_bird.flight() obj_parr.intro() obj_parr.flight() obj_peng.intro() obj_peng.flight()
true
f7b7853e9332ef9fd2a5c16733f1908c00ea2a04
redoctoberbluechristmas/100DaysOfCodePython
/Day03 - Control Flow and Logical Operators/Day3Exercise3_LeapYearCalculator.py
826
4.375
4
#Every year divisible by 4 is a leap year. #Unless it is divisible by 100, and not divisible by 400. #Conditional with multiple branches year = int(input("Which year do you want to check? ")) if(year % 4 == 0): if(year % 100 == 0): if(year % 400 == 0): print("Leap year.") else: print("Not leap year.") else: print("Leap year.") else: print("Not leap year.") #Refactored using more condense conditional statement. #"If a year is divisible by 4, and it is either not divisible by 100, or is not not divisible by 100 but is # divisible by 400, then it is a leap year. Otherwise, it is not a leap year." if(year % 4 == 0) and ((not year % 100 == 0) or (year % 400 == 0)): #if(year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0)): print("Leap year.") else: print("Not leap year.")
true
d167ac2865745d4e015ac1c8565dd07fba06ef4d
redoctoberbluechristmas/100DaysOfCodePython
/Day21 - Class Inheritance/main.py
777
4.625
5
# Inheriting and modifying existing classes allows us to modify without reinventing the wheel.add class Animal: def __init__(self): self.num_eyes = 2 def breathe(self): print("Inhale, exhale.") class Fish(Animal): def __init__(self): super().__init__() # The call to super() in the initializer is recommended, but not strictly required. def breathe(self): # Extend an inherited method. Running this will produce "Inhale, exhale" \n "doing this underwater." Wont' totally override the method. super().breathe() print("doing this underwater.") def swim(self): print("moving in water.") nemo = Fish() nemo.swim() # Inherit methods. nemo.breathe() # Inherit attributes. print(nemo.num_eyes)
true
d999a0fd4f5a5516a6b810e76852594257174245
redoctoberbluechristmas/100DaysOfCodePython
/Day08 - Functions with Parameters/cipherfunctions.py
846
4.125
4
alphabet = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] def caesar(start_text, shift_amount, cipher_direction): output_text = "" # Will divide the shift amount to fit into length of alphabet. shift_amount = shift_amount % 26 if cipher_direction == "decode": shift_amount *= -1 for char in start_text: if char in alphabet: start_index = alphabet.index(char) end_index = start_index + shift_amount output_text += alphabet[end_index] else: output_text += char print(f"The {cipher_direction}d text is {output_text}.")
true
9006fe1d04ceee567b8ced73bddd2562d0239fb8
zhartole/my-first-django-blog
/python_intro.py
1,313
4.21875
4
from time import gmtime, strftime def workWithString(name): upper = name.upper() length = len(name) print("- WORK WITH STRING - " + name * 3) print(upper) print(length) def workWithNumber(numbers): print('- WORK WITH NUMBERS') for number in numbers: print(number) if number >= 0: print("--positive val") else: print("--negative val") def addItemToDictionary(key,value): dictionaryExample = {'name': 'Olia', 'country': 'Ukraine', 'favorite_numbers': [90, 60, 90]} dictionaryExample[key] = value print('- WORK WITH DICTIONARY') print(dictionaryExample) def workWithFor(): for x in range(0, 3): print("We're in for ") def workWithWhile(): x = 1 while (x < 4): print("Were in while") x += 1 def showBasicType(): text = "Its a text" number = 3 bool = True date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) print(text) print(number) print(bool) print(date) def hi(name): print('Hi ' + name + '!' + ' Lets show you a few example of Python code') def init(): hi('Victor') workWithString("Igor") workWithNumber([1, 5, 4, -3]) addItemToDictionary('new', 'child') workWithFor() workWithWhile() showBasicType() init()
true