blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
88ba861d7a6c7ff3825b520ad528791feaba7f53
cleysondiego/curso-de-python-dn
/semana_1/exercicios_aula_1/Exercicio06.py
939
4.21875
4
#Exercicio 06 #Faça um programa que pergunte o preço de tres produtos e informe qual o produto voce deve comprar #Sabendo que a decisao e sempre pelo mais barato produto1 = float(input('Digite o preço do produto 1: ')) produto2 = float(input('Digite o preço do produto 2: ')) produto3 = float(input('Digite o preço do produto 3: ')) if produto1 < produto2 and produto3 and produto1: print('Compre o produto 1') elif produto2 < produto1 and produto3: print('Compre o produto 2') elif produto3 < produto1 and produto2: print('Compre o produto 3') elif produto1 == produto2 and produto1 and produto2 < produto3: print('Compre o produto 1 ou 2') elif produto1 == produto3 and produto1 and produto3 < produto2: print('Compre o produto 1 ou 3') elif produto2 == produto3 and produto2 and produto3 < produto1: print('Compre o produto 2 ou 3') else: print('Todos os preços são iguais!!')
false
6300156f3f57f4d2073073bf57d1fe09ea9a6108
march-pt-python/instructor_wes
/python_fundamentals/algos.py
2,034
4.46875
4
# Create a function to generate Fibonacci numbers. In this famous mathematical sequence, each number is the sum of the previous two, starting with values 0 and 1. Your function should accept one argument, an index into the sequence (where 0 corresponds to the initial value, 4 corresponds to the value four later, etc). Examples: fibonacci(0) = 0 (given), fibonacci(1) = 1 (given), fibonacci(2) = 1 ( fib(0) + fib(1) , or 0+1), fibonacci(3) = 2 ( fib(1) + fib(2) , or 1+1), fibonacci(4) = 3 (1+2), fibonacci(5) = 5 (2+3), fibonacci(6) = 8 (3+5), fibonacci(7) = 13 (5+8), etc. # start with 0 and 1 # what does it mean to start with 0 and 1? # store 0 and 1 in a list # store 0 and 1 in separate variables # to get to the next number, add previous 2 numbers together # how can I know which numbers are the 2 previous numbers? # what does it mean to "get to" the next number? # current = a + b # a = b # b = current # stop when I have idx + 1 total values # how do I stop? # how do I start? def fibonacci(idx): if idx <= 1: return idx a = 0 b = 1 for i in range(idx - 1): current = a + b a = b b = current return current # print(fibonacci(100)) # print(fibonacci(1)) # print(fibonacci(0)) def fibonacci_with_list(idx): results = [0, 1] if idx <= 1: return results[idx] for i in range(2, idx + 1): results.append(results[i - 1] + results[i - 2]) return results[len(results) - 1] # print(fibonacci_with_list(7)) # print(fibonacci_with_list(1)) # print(fibonacci_with_list(0)) def rfib(index): if(index == 0): return 0 elif(index == 1): return 1 else: return rfib(index-1) + rfib(index-2) # print(rfib(100)) # print(rfib(1)) # print(rfib(0)) def recurfib(idx, a=0, b=1): if idx == 0: return a return recurfib(idx - 1, b, a + b) print(recurfib(100)) print(recurfib(1)) print(recurfib(0))
true
190a408a32e6e4d247d7a4eb5d3700ad308c07b0
godsman-yang/hongong-python
/03-2-3.py
1,122
4.125
4
# 사용자에게 태어난 연도를 입력받아 띠를 출력하는 프로그램을 작성해 주세요. # 작성 시 입력받은 연도를 12로 나눈 나머지를 사용합니다. # 나머지가 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11일때 각각 원숭이, 닭, 개, 돼지, 쥐, 소, 범, 토끼, 용, 뱀, 말, 양띠입니다. str_input = input("태어난 해를 입력해 주세요> ") birth_year = int(str_input) if(birth_year%12) == 0: print("원숭이 띠입니다.") elif(birth_year%12) == 1: print("닭 띠입니다.") elif(birth_year%12) == 2: print("개 띠입니다.") elif(birth_year%12) == 3: print("돼지 띠입니다.") elif(birth_year%12) == 4: print("쥐 띠입니다.") elif(birth_year%12) == 5: print("소 띠입니다.") elif(birth_year%12) == 6: print("범 띠입니다.") elif(birth_year%12) == 7: print("토끼 띠입니다.") elif(birth_year%12) == 8: print("용 띠입니다.") elif(birth_year%12) == 9: print("뱀 띠입니다.") elif(birth_year%12) == 10: print("말 띠입니다.") elif(birth_year%12) == 11: print("양 띠입니다.")
false
eb7c1863f9164fde7473e88067651e6faa016cbf
lemonshark12/Portfolio
/Reverse String.py
1,304
4.1875
4
def play(): input = raw_input("Select one of the following:\n'1' for reverse_string,\n'2' for reverse_string_with_stack, or\n'3' for reverse_sort\n>> ") while True: if input == '1': reverse_string() break if input == '2': reverse_string_with_stack() break if input == '3': reverse_short() break else: print "invalid entry. Good bye!" break def reverse_string(): s = raw_input("Type the thing you want to reverse\n>> ") st = [] for i in s: st.append(i) ts = st[::-1] print "".join(ts) print "this was reverse_string" #reverse_string() def reverse_string_with_stack(): s = raw_input("Type the thing you want to reverse using a stack\n>> ") st = [] ts = [] for i in s: st.append(i) while len(st) != 0: ts.append(st.pop()) print "".join(ts) print "this was reverse_string_with_stack" #reverse_string_with_stack() def reverse_short(): s = raw_input("Type the thing you want to reverse using the short version\n>> ") st = [] for i in s: st.append(i) st.reverse() print ''.join(st) print "this was reverse_short" #reverse_short() play()
false
e2328b14316c0524ad099de5f132c5adc7211969
etothemanders/Exercise05
/lettercounter.py
914
4.40625
4
"""Write a program, lettercount.py, that opens a file named on the command line and counts how many times each letter occurs in that file. Your program should then print those counts to the screen, in alphabetical order.""" from sys import argv def get_file_contents(): filename = argv[1] f = open(filename, "r") text = f.read() f.close() return text def count_letters(text): text = text.lower() letter_counts = [ 0 for x in range(256) ] for letter in text: char = ord(letter) letter_counts[char] += 1 return letter_counts def print_counts(letter_counts): for index, count in enumerate(letter_counts): if index >= ord('a') and index <= ord('z'): print count def main(): text = get_file_contents() counts = count_letters(text) print_counts(counts) if __name__ == "__main__": main()
true
ccef3fbbc1e1ad6a33b2792a0dae04c842607c2a
MMmichaelMM/NumericalAnalysis
/Ieee754_2.py
1,659
4.375
4
# Python program to convert # IEEE 754 floating point representation # into real value # Function to convert Binary # of Mantissa to float value. def convertToInt(mantissa_str): # variable to make a count of negative power of 2. power_count = -1 # variable to store float value of mantissa. mantissa_int = 0 # Iterations through binary number. Standard form of # Mantissa is 1.M so we have 0.M therefore we are taking # negative powers on 2 for conversion. for i in mantissa_str: # Adding converted value of binary bits in every # iteration to float mantissa. mantissa_int += (int(i) * pow(2, power_count)) # count will decrease by 1 as we move toward right. power_count -= 1 # returning mantissa in 1.M form. return (mantissa_int + 1) ieee_32 = '1|10000000|00100000000000000000000' # First bit will be sign bit. sign_bit = int(ieee_32[0]) # Next 8 bits will be exponent Bits in Biased form. exponent_bias = int(ieee_32[2: 10], 2) # In 32 Bit format bias value is 127 so to have # unbiased exponent subtract 127. exponent_unbias = exponent_bias - 127 # Next 23 Bits will be mantissa (1.M format) mantissa_str = ieee_32[11:] # Function call to convert 23 binary bits into # 1.M real no. form mantissa_int = convertToInt(mantissa_str) # The final real no. obtained by sign bit, mantissa and Exponent. real_no = pow(-1, sign_bit) * mantissa_int * pow(2, exponent_unbias) # Printing the obtained real value of floating Point Representation. print("The float value of the given IEEE-754 representation is :", real_no)
true
17a54bb60eda2927e3815e1d76d0853ad4b74f54
Iamrhema/Projects
/Python/disappear.py
734
4.28125
4
#This program removes specific characters from a string #User enters input userInput = input("Enter any phrase or word: ") userReplacer = input ("Enter any variable\s you want to remove from your word(separated by comma()): ").lower() #The code repeats so thta the process can be run more than once so thta each chracter can be removed throughout the phrase. for i in userReplacer: if i in userInput: #this code adds the all the characters the user wants to remove so thta its possible for user to add more than character to be removed. # the replace(i,'') replaces the characters eneterd by the user with an empty space userInput = userInput.replace(i,'') #End result prints print(userInput)
true
8b8d0ab7c974a410702a726d28bfb9d69ddf9ca8
Iamrhema/Projects
/Python/counting.py
369
4.125
4
#This program counts all the characters in string. #Collections in Python are containers that are used to store collections of data, for example, list, dict, set, tuple etc. import collections #user enters their input. userInput = input("Enter any word or phrase: ") #all characyers in the string is counted and printed out print(collections.Counter(userInput))
true
98d34d4b3d6144467246ed5351febfbd846f7202
HarunMbaabu/MaProD-Murang-a-University-of-Technology-CodingCHALLENGE
/count_characters/count.py
575
4.1875
4
""" Define a string. Define and initialize a variable count to 0. Iterate through the string till the end and for each character except spaces, increment the count by 1. To avoid counting the spaces check the condition i.e. string[i] != ' '. """ string = "Mathematics and Programming"; count = 0; #Counts each character except space for i in range(0, len(string)): if(string[i] != ' '): count = count + 1; #Displays the total number of characters present in the given string print("Total number of characters in a string: " + str(count));
true
debd010631fd43f8eed3c27ef817ce957c1ba896
dongbo910220/leetcode_
/Linked List/92. Reverse Linked List II Medium.py
1,507
4.1875
4
''' Reverse a linked list from position m to n. Do it in one-pass. Note: 1 ≤ m ≤ n ≤ length of list. Example: Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL ''' ''' Success Details Runtime: 16 ms, faster than 81.81% of Python online submissions for Reverse Linked List II. Memory Usage: 11.8 MB, less than 100.00% of Python online submissions for Reverse Linked List II. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head pm = dummy # pre = dummy for i in range(m - 1): pm = pm.next pre = pm pm = pm.next end = dummy for i in range(n): end = end.next end = end.next k = n - m if k == 0: return head # k == 1? p1 = pm p2 = pm.next p3 = pm.next.next p1.next = end # tail connection for i in range(k): if p3: p2.next = p1 p1 = p2 p2 = p3 p3 = p3.next else: p2.next = p1 p1 = p2 p2 = p3 pre.next = p1 return dummy.next
true
c417696001825689fdbe6c28bae9dea7bb8671bc
dongbo910220/leetcode_
/Tree/106. Construct Binary Tree from Inorder and Postorder Traversal Medium.py
1,628
4.28125
4
''' Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] Return the following binary tree: 3 / \ 9 20 / \ 15 7 ''' ''' Success Details Runtime: 184 ms, faster than 26.29% of Python online submissions for Construct Binary Tree from Inorder and Postorder Traversal. Memory Usage: 87.1 MB, less than 7.14% of Python online submissions for Construct Binary Tree from Inorder and Postorder Traversal. ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder or not postorder: return None root_val = postorder[-1] root = TreeNode(root_val) postorder.pop() inorder_idx = inorder.index(root_val) root.left = self.buildTree(inorder[:inorder_idx], postorder[:inorder_idx]) root.right = self.buildTree(inorder[inorder_idx + 1:], postorder[inorder_idx:]) return rootGiven a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 Accepted 311,710 Submissions 663,268
true
9e6653fc9a1a55c4204ece9ab6166fc9af3d9b04
dongbo910220/leetcode_
/array/55. Jump Game Medium.py
2,395
4.125
4
''' Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. ''' class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) final_pos = n - 1 pos = 0 return self.jumpEachStep(nums, pos, final_pos) def jumpEachStep(self, nums, pos, final_pos): if pos >= final_pos: return True if nums[pos] == 0: return False ans = False for footstep in range(nums[pos], 0, -1): ans1 = self.jumpEachStep(nums, pos + footstep, final_pos) if ans == 1: return True ans = ans or ans1 return ans # a = Solution() # b = [3,2,1,0,4] # c = [8,2,4,4,4,9,5,2,5,8,8,0,8,6,9,1,1,6,3,5,1,2,6,6,0,4,8,6,0,3,2,8,7,6,5,1,7,0,3,4,8,3,5,9,0,4,0,1,0,5,9,2,0,7,0,2,1,0,8,2,5,1,2,3,9,7,4,7,0,0,1,8,5,6,7,5,1,9,9,3,5,0,7,5] # d = [1,2,2,6,3,6,1,8,9,4,7,6,5,6,8,2,6,1,3,6,6,6,3,2,4,9,4,5,9,8,2,2,1,6,1,6,2,2,6,1,8,6,8,3,2,8,5,8,0,1,4,8,7,9,0,3,9,4,8,0,2,2,5,5,8,6,3,1,0,2,4,9,8,4,4,2,3,2,2,5,5,9,3,2,8,5,8,9,1,6,2,5,9,9,3,9,7,6,0,7,8,7,8,8,3,5,0] # print("solution1", a.canJump(d)) # for i, j in enumerate(b, -1): # print(i, j) class Solution_1(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) final_pos = n - 1 pos = 0 lastPos = final_pos for i in range(final_pos - 1, -1, -1): if i + nums[i] >= lastPos: lastPos = i if lastPos == 0: return True else: return False a = Solution_1() b = [3,2,1,0,4] c = [2,3,1,1,4] # print("solution2", a.canJump(d)) # d = [[1,3],[2,6],[8,10],[15,18]] # # for i, term in enumerate(d): # c, d = term # print(c, d) # print(i) a, b , c = 0, 0, 0 print(c)
true
62c266241fbcfebcb6fb5da4bf5bcf51f31395e7
ibrahMuhammed/Khansole_academy_starter
/khansole_academy_starter.py
942
4.28125
4
""" File: khansole_academy.py ------------------------- Khansole Academy is a program that teaches users how to add by asking users to input answers for the addition of two randomly generating integers between 10 and 99 inclusive. The program returns feedback based on the User's answers. """ import random # use code below to generate a random integer between 30 and 50 for example #print(random.randint(30, 50)) # ********************************** YOUR CODE GOES BELOW HERE ********************************************************* attempt=0 while attempt!=3: number1=random.randint(20,50) number2=random.randint(21,60) add=number1+number2 print(number1 ,'+',number2) ans=int(input("Enter your answer:")) if ans==add: attempt=attempt+1 print("You have ans ", attempt , "in a row") else: print("The correct answer is ", add) attempt=0 print("You have mastered it !")
true
3c6f88bc594662471c37688a26c72b3b5f663c0a
Williama0558/cti110
/M5T2_BugCollector_WilliamsAaron.py
1,434
4.625
5
#CTI-110 #Bug Collector #Aaron Williams #10/05/2017 #This program keeps track of the amount of bugs collected over a period of time. #This method keeps tracks of bugs collected using for loop statements. def mainFor(): total = 0 #Defines how many times the loop will run. for day in range(1, 8): print('Enter how many bugs were collected for day',day,': ') #Section where user inputs how many bugs were collected in a day. bugsCollected = int(input()) #Variable that keeps track of how many bugs have been collected so far. total += bugsCollected print('You collected',total,'bugs over',day,'days.') #This method keeps track of bugs collected using while loop statements. def mainWhile(): total = 0 day = 1 #Defines how many times the loop will have to run. while day <= 7: print('Enter how many bugs were collected for day',day,': ') #Section where user inputs how many bugs were collected in a day. bugsCollected = int(input()) #Variable that keeps track of how many bugs have been collected so far. total += bugsCollected #Advances the day in the loop by one each time it is used. day += 1 #Makes sure that the day displayed at the end of the loop is correct. day -= 1 print('You collected',total,'bugs over',day,'days') mainWhile() mainFor()
true
8b1feb4d53d97d54217cdd30de9f54126b5e5214
Williama0558/cti110
/M6HW2_WilliamsAaron.py
1,227
4.21875
4
#CTI-110 #M6HW2 - Guessing Game #Aaron Williams #11/29/17 #This program generates a random number that the user has to guess. import random def main(): print('Welcome to the Random Number Guesser') print('') playGame() userChoice = input('Do you want to play again? y/n: ') #Replays the game if the user enters in 'y' if userChoice == 'y': main() else: print('Thanks for playing!') def playGame(): userGuess = True #Generates the random number number = random.randint(0,100) guesses = 0 #Runs the loop until the user guesses the right number while userGuess != number: userGuess = int(input('Please guess a random whole number: ')) if userGuess > number: print('Your guess was too high') print('') #Keeps track of how many guesses the user took guesses += 1 elif userGuess < number: print('Your guess was too low') print('') guesses += 1 else: print('You guessed correctly.') guesses += 1 print('It took',guesses,'guesses to get the right number') main()
true
9a771372d1d078a76ec66e1206b7b204f8d169f1
ESQG/calculator2
/calculator.py
1,347
4.125
4
""" calculator.py Using our arithmetic.py file from Exercise02, create the calculator program yourself in this file. """ from arithmetic import * # Your code goes here def main(): while True: user_input = raw_input("> ") tokens = user_input.split() try: if tokens[0] == 'q': quit() else: numbers = map(int, tokens[1:]) if tokens[0] == '+': print reduce(add, numbers) elif tokens[0] == '-': print reduce(subtract, numbers) elif tokens[0] == '*': print reduce(multiply, numbers) elif tokens[0] == '/': print reduce(divide, numbers) elif tokens[0] == 'square': print square(int(tokens[1])) elif tokens[0] == 'cube': print cube(int(tokens[1])) elif tokens[0] == 'pow' or tokens[0] == '**' or tokens[0] == 'exp': print reduce(power, numbers) elif tokens[0] == 'mod' or tokens[0] == '%': print reduce(mod, numbers) else: print "I don't understand" except: print "This doesn't work" if __name__ == '__main__': main()
true
47c7ec627e83e5e29a6f24242a2828304476d75b
Saraabd7/OOP-Basics
/Animal_class.py
1,367
4.375
4
# Define our animal class # Sudo code: # Looks / characteristics of every animal # name, age, colour heart, brain # Behaviours / Methods of every animal # Eat, sleep, reproduce, potty, make_sound class Animal(): # define behaviours and characteristics def __init__(self, name, age, color): # define the characteristics of every animal self.name = name self.age = age self.colour = color self.heart = True self.brain = True # defining the method .eat(), .sleep(). .reproduce(), .potty(), .make_sound() def eat(self): return 'Nom nom nom' def sleep(self): return 'zzzZzZZzZZZz' def reproduce(self): return 'Need some privacy' def potty(self): return 'About to let last night\'s food out' def make_sound(self): return 'woof' # To call methods, we need an object of this class # creating an instance of class animal ringo = Animal('Ringo', 44, 'Green') #creates instance of class animal and assigns to variable ringo # checking and printing the instance print(ringo) print(type(ringo)) # calling methods on instance of animal print(ringo.eat()) print(ringo.potty()) print(ringo.sleep()) # Check the attribute of an instance print(ringo.name, ringo.age) # second animal mini = Animal('John', 92, 'Pink') print(mini.name, mini.age, mini.sleep())
true
41c4abfac9377aed5643bffd02ad8ba23e656fdc
TheRealJo/interactive_programming_in_python
/w2/rpsls.py
1,889
4.15625
4
# Rock-paper-scissors-lizard-Spock template #Made by Codeskulptor (codeskulptor.org) # LINK TO THE PROGRAM # http://www.codeskulptor.org/#user10_yUTZuvXdQ2_3.py # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random def number_to_name(number): if number == 0: return "rock" elif number == 1: return "Spock" elif number == 2: return "paper" elif number == 3: return "lizard" elif number == 4: return "scissors" else: return -1 def name_to_number(name): if name == "rock": return 0 elif name == "Spock": return 1 elif name == "paper": return 2 elif name == "lizard": return 3 elif name == "scissors": return 4 else: return -1 def rpsls(name): player_number = name_to_number(name) print "Player chooses", name comp_number = random.randrange(0,5) print "Computer chooses", number_to_name(comp_number) difference = (player_number - comp_number) % 5 if difference == 3 or difference == 4: print "Computer wins.\n" return elif difference == 1 or difference == 2: print "Player wins.\n" return elif difference == 0: print "Draw.\n" return else: print "Error.\n" # test your code rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors") # run example ''' Player chooses rock Computer chooses lizard Player wins. Player chooses Spock Computer chooses paper Computer wins. Player chooses paper Computer chooses scissors Computer wins. Player chooses lizard Computer chooses Spock Player wins. Player chooses scissors Computer chooses rock Computer wins. '''
true
05b5b211ce409a67f0867de8b2c7bb042aa6215a
jegansoftware/Python-program
/7.py
822
4.21875
4
india= raw_input("Are you India? :") if (india=="yes") or (india=="YES") or (india=="Yes"): a=raw_input("Enter Name :") b=input("Enter Age :") c=raw_input("Have you completed Degree ?") d=input("Enter Your Mobile No :") print print s="Name : %s" %a s1="Age : %s" %b s2="Degree: %s" %c s3="Phone : (+91) %s" %d print("Details have been collected from user") kk=raw_input("Do you want to display ? ") if (kk=="Yes") or (kk=="yes") or (kk=="YES"): print(s) print(s1) print(s2) print(s3) else : print("Details were stored in Database") else : print("Indians will be allowed to apply ") print("We confirmed that you aren't indian")
true
d2acb3a92f40c2948cd634ea7bd9cc6d46c09e02
Ryan-Walsh-6/ICS3U-Unit5-04-Python
/cylinder_volume.py
1,306
4.40625
4
#!/usr/bin/env python3 # created by: Ryan Walsh # created on: January 2021 # this program calculates the volume of a cylinder import math def calculate_volume(radius, height): # calculates volume # process & output volume_of_cylinder = (math.pi) * (radius) ** 2 * (height) return volume_of_cylinder def main(): # this program calculates the volume of a cylinder while True: try: radius_from_user = input("Enter the radius of the cylinder (mm):") radius_from_user = float(radius_from_user) height_from_user = input("Enter the height of the cylinder (mm):") print("\n", end="") height_from_user = float(height_from_user) if radius_from_user < 0 or height_from_user < 0: print("Please ensure all values are positive.") print("\n", end="") else: break except Exception: print("Please enter a valid number.") print("\n", end="") # call function volume = calculate_volume(radius_from_user, height_from_user) print("The volume of a cylinder with radius {0}mm and height {1}mm is" " {2:,.2f}mm³".format(radius_from_user, height_from_user, volume)) if __name__ == "__main__": main()
true
e62ebe1ad58a1a91006b130c50fdc5150eab8b3f
Isen-kun/Python-Programming
/Rice Uni Courses/datesProject.py
1,690
4.1875
4
""" Project for Week 4 of "Python Programming Essentials". Collection of functions to process dates """ import datetime def days_in_month(year, month): """ Takes input year and month and returns number of date in the """ date1 = datetime.date(year, month, 1) if month == 12: date2 = datetime.date(year+1, 1, 1) else: date2 = datetime.date(year, month+1, 1) return (date2-date1).days def is_valid_date(year, month, day): """ Takes input of year,month,day and return True if year-month-day is a valid date """ if year >= datetime.MINYEAR and year <= datetime.MAXYEAR: if month >= 1 and month <= 12: if day >= 1 and day <= days_in_month(year, month): return True else: return False else: return False else: return False def days_between(year1, month1, day1, year2, month2, day2): """ Takes input of two sets of year,month,day and return the number of days in between """ if is_valid_date(year1, month1, day1) and is_valid_date(year2, month2, day2): date1 = datetime.date(year1, month1, day1) date2 = datetime.date(year2, month2, day2) differ = (date2-date1).days if(differ >= 0): return differ else: return 0 else: return 0 def age_in_days(year, month, day): """ Takes input of year,month,day and returns the difference from today's """ if is_valid_date(year, month, day): today = datetime.date.today() return days_between(year, month, day, today.year, today.month, today.day) else: return 0
true
af7aafbac8990032b3277181b24f875d307da7a3
Isen-kun/Python-Programming
/Sem_3_Lab/1.12.20/asign1.py
224
4.3125
4
# Factorial of a given number using function n = int(input("Enter a number: ")) def fact(n): mul = 1 while n > 0: mul *= n n -= 1 return mul print("The factorial of the number is:", fact(n))
true
d26c42b2959601579eb4d7ede033af2c72c2bb18
Isen-kun/Python-Programming
/Sem_3_Lab/15.09.20/assign5.py
690
4.125
4
# To print the sum of the series of 1 - 1/3 + 1/9 - 1/27 + 1/81-.........Nth term(Input N) N = int(input("Enter the number of terms: ")) print("Using for Loop:") sum1 = 0 for i in range(N): if i % 2 == 0: print(str(1) + "/" + str(3**i), end=" - ") sum1 += 1/(3**i) else: print(str(1) + "/" + str(3**i), end=" + ") sum1 -= 1/(3**i) print("\nThe Sum is:", sum1) print("") print("Using while Loop:") i = 0 sum2 = 0 while i < N: if i % 2 == 0: print(str(1) + "/" + str(3**i), end=" - ") sum2 += 1/(3**i) else: print(str(1) + "/" + str(3**i), end=" + ") sum2 -= 1/(3**i) i += 1 print("\nThe Sum is:", sum2)
false
9f03819c5195a0cc4dc6f6912cdcc27cb0ba0990
Isen-kun/Python-Programming
/Sem_3_Lab/15.09.20/assign2.py
376
4.34375
4
# To print the sum of the series of 1+2+3+4+.........N(Input N) N = int(input("Enter the nth term: ")) print("Using for Loop:") sum1 = 0 for i in range(1, N+1): print(i, end=" + ") sum1 += i print("\nThe Sum is:", sum1) print("") print("Using while Loop:") i = 1 sum2 = 0 while i <= N: print(i, end=" + ") sum2 += i i += 1 print("\nThe Sum is:", sum2)
false
4ec11363f8bc3527456613c4ba564bbec304dc17
kansi/Trail_Python
/System_prog/p207_Glob_Fnmatch.py
1,467
4.5
4
#!/usr/bin/env python # This module explains the directory traversal and listing contents of a dir. import os # to list the content of a given dir. print os.listdir('/') # below we check that a given item in the list is dir or file for item in os.listdir('/'): if os.path.isfile(item): print "file \t %s" %(item) elif os.path.isdir(item): print "dir \t %s" %(item) else print "unknown \t %s" %(item) # Below we see the basic usage of glob module in python. glob is a module which is # used to list files on the filesystem with names matching a pattern. import glob for item in glob.glob(os.path.join(".", "*")): print item # below is single character wild card for name in glob.glob('./p00?.py'): print name for name in glob.glob('./p0[0-9][0-9]*.py'): print name # When we have a very lage file listing glob is not a good option, so we use # fnmatch import fnmatch # fnmatch() method returns true or false for a given input name and the pattern for item in os.listdir('.'): # to do case-sensitive search use fnmatch.fnmatchcase() if fnmatch.fnmatch(item, 'p00[0-9]*.py') print item # filter() return a list of all the name that matched the given pattern for item in fnmatch.filter(os.listdir('.'), 'p00[0-9]*.py'): print item # below we se how fnmatch internally converts the given pattern to a regex # using the re module pattern = 'p00?_*.py' print 'Pattern :', pattern print 'Regex :', fnmatch.translate(pattern)
true
a77e0644d9aa1af7fbfcd916b76c78fd961a45bb
kansi/Trail_Python
/OOP/p115_OOP_decorators.py
656
4.25
4
#!/usr/bin/env python """ This class shows """ class Date: def __init__(self, month, day, year): self.month = month self.day = day self.year = year def display(self): return "{0}-{1}-{2}".format(self.month, self.day, self.year) @staticmethod def millenium(month, day): return Date(month, day, 2000) new_year = Date(1, 1, 2013) # Creates a new Date object millenium_new_year = Date.millenium(1, 1) # also creates a Date object. # Proof: new_year.display() # "1-1-2013" millenium_new_year.display() # "1-1-2000" isinstance(new_year, Date) # True isinstance(millenium_new_year, Date) # True
false
8cfc8431105082ced8c71770ff074ab9969fd712
SherlockUnknowEn/leetcode
/20-29/24. Swap Nodes in Pairs(Medium)/Swap Nodes in Pairs.py
950
4.125
4
# -*- coding: utf-8 -*- # @Time : 2017/7/20 上午10:55 # @Author : fj # @Site : # @File : Swap Nodes in Pairs.py # @Software: PyCharm # Given a linked list, swap every two adjacent nodes and return its head. # # For example, # Given 1->2->3->4, you should return the list as 2->1->4->3. # # Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ try: prev = head tail = prev.next while True: prev.val, tail.val = tail.val, prev.val prev = tail.next tail = prev.next finally: return head
true
d53265c75f5f4449dbeb97257bd39999f9bbdfa8
theCruelCoder/Tryouts
/tuple.py
1,564
4.34375
4
from collections import namedtuple # 元组 tuple # 一个有序的元素组成的集合 # 使用小括号()表示 # 元组是不可变对象 # 元组的定义和初始化 t = tuple() t = tuple(range(5)) print(t) print(id(t)) print(t[1]) for x in t: print(x) t1 = (1) print(type(t1)) t1 = (1, ) print(type(t1)) t1 = ((1, ), ) * 5 print(t1) t1 = ((1, 2, 3), ) * 5 print(t1) # 以下能不能改 t1 = ([1, 2, 3], ) * 5 t1[0][0] = 100 # t1[0] = [10, 2, 3] 不能改,tuple内存地址不允许修改 # 元组查询,类似列表查询 # index(value, [start, [stop]]) # count(value) # Time complexity: O(n) # len(tuple) # Time complexity: O(1) # 命名元组 namedtuple Point = namedtuple('P', ['x', 'y']) print(Point) p1 = Point(1, 2) print(p1) print(p1.x, p1.y) print(p1[0], p1[1]) Student = namedtuple('stu', 'name age') print(Student) s1 = Student('tom', 20) s2 = Student('jerry', 18) print(s1) print(s2) print(s1.name) print(s1.age) # 定义 # tuple() -> empty tuple # tuple(iterable) -> tuple initialized from iterable's items t = tuple() # 工厂方法 t = () t = tuple(range(1,7,2)) # iterable t = (2,4,6,3,4,2) t = (1,) # 一个元素元组的定义,注意有个逗号 t = (1,) * 5 print(t) t = (1,2,3) * 6 print(t) # 元组元素的访问 # 支持索引(下标) # 正索引:从左至右,从0开始,为列表中每个元素编号 # 负索引:从右至左,从-1开始 # 正负索引不可以超界,否则引发异常IndexError # 元组通过索引访问 # tuple[index], index就是索引, 使用中括号访问 t[1] t[-2]
false
d8887c261fed169d0884807109b489b816050e9d
kaushal-gupta/Python-basic-programs
/stackimplementation.py
1,200
4.21875
4
class Stack: def __init__(self): self.stack=list() def Push(self): item=int(input("\nEnter the item")) self.stack.append(item) def Pop(self): if(len(self.stack)==0): print "Underflow" else: item=self.stack.pop() print "Item deleted is :",item def display(self): if(len(self.stack)==0): print "Stack empty" else: print "[", for a in self.stack: print a," ", print "]" def peek(self): print len(self.stack) bj=Stack() while True: print "\nEnter 1: for push operation:" print "\nEnter 2: for pop operation:" print "\nEnter 3: for displaying the stack:" print "\nEnter 4: for peek" print "\nEnter 5: for Exit:" choice=int(input("Enter your choice:")) if(choice==1): bj.Push() elif(choice==2): bj.Pop() elif(choice==3): bj.display() elif(choice==4): bj.peek() elif(choice==5): break; else: print "Invalid choice"
false
e246fe5098f1acccec53c8fb23c669632feeb052
abhikmp/SomeRandomPyPrograms
/addtocsv.py
444
4.125
4
import csv def addtocsv(lst): with open('filename.csv', 'w') as csvfile: #enter a file name here writer = csv.writer(csvfile) for item in lst: writer.writerow(item) csvfile.close() to_csv = [] lst = "" columns = input("Enter the column-names") print(columns) while(1): lst = input() if lst!="": to_csv.append(lst.rstrip().split()) else: break addtocsv(to_csv) print(to_csv)
true
73975bd2117a2c2562616011b99f57b3f1eb50b3
samar2788/codwars-katas
/overtheroad.py
944
4.1875
4
def over_the_road(address, n): lists = list(range(1,((2*n)+1))) odd = list(filter(lambda x: x%2==1,lists)) even = list(filter(lambda x: x%2==0,lists)) even.reverse() ml = tuple(zip(odd,even)) for x,y in ml: if x==address: return y elif y==address: return x a = over_the_road(4778098276,21582033789) print(a) # def over_the_road(address, n): # ''' # Input: address (int, your house number), n (int, length of road in houses) # Returns: int, number of the house across from your house. # ''' # # this is as much a math problem as a coding one # # if your house is [even/odd], the opposite house will be [odd/even] # # highest number on street is 2n # # Left side houses are [1, 3, ... 2n-3, 2n-1] # # Right side houses are [2n, 2n-2, ... 4, 2] # # Sum of opposite house numbers will always be 2n+1 # return (2*n + 1 - address)
true
a74dabdc8fbe54a5e96f7869432d333eb9150425
SnazzyCatz/Basic-Password-Checker
/q5_p1.py
2,651
4.15625
4
PasswordValidity = False while (PasswordValidity == False): Username = input('Please Enter Your Username') Password = input('Please Enter Your Password') #Checks For Password Length if ((len(Password) < 6) | (len(Password) > 20)): print('Invalid Password, Try Again') continue #Checks for upper, lower, number, and special characters hasUpper = False hasSpecial = False hasNumber = False for character in Password: if character.isupper() == True: hasUpper = True if character.isnumeric() == True: hasNumber = True if ((character.isupper() == False) & (character.islower() == False) & (character.isnumeric() == False)): hasSpecial = True if((hasUpper == False) | (hasNumber == False) | (hasSpecial == False)): print('Invalid Password, Try Again') continue #Checks if two 3 letter substrings match in the password passLength = len(Password) - 1 counter = 0 substringList = [] while (counter <= (passLength - 2)): substringList.append(Password[counter:counter + 3]) counter += 1 if(len(substringList) != len(set(substringList))): print('invalid password, Try Again') continue #Checks if password is a Palindrome isPalindrome = True for i in range(0,int(len(Password)/2)): if Password[i] != Password[len(Password)-i-1]: isPalindrome = False if(isPalindrome == True): print('Invalid Password, Try Again') #Checks if number of unique characters is high enough dupeList = [] for i in range(0,len(Password)): dupeList.append(i) uniqueList = [] for i in dupeList: if i not in uniqueList: uniqueList.append(i) if(len(uniqueList) < (len(Password)/2)): print('Invalid Password, Try Again') continue #Checks if username or reverse of username is in password compList = [] reverseList = [] count = 0 revCount = 0 userLength = len(Username) - 1 reverseUser = Username[::-1] if (len(Username) < len(Password)): while count <= (len(Password) - userLength - 1): compList.append(Password[count:(count + userLength + 1)]) count += 1 if Username in compList: print('Invalid Password, Try Again') continue if reverseUser in compList: print('Invalid Password, Try Again') continue #All Conditions have been met if it reaches this point print('Account Creation Successful') break
true
74822477b918b1eea113f5a61dfa867e26e25676
RajeevSawant/PYthon-Programming
/statement_assessment_test.py
746
4.15625
4
st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0] == 's': print word for x in range(11): if x % 2 == 0: print x lst =[x for x in range(51) if x%3 == 0] print lst str = 'Print every word in this sentence that has an even number of letters' letter = [x for x in str.split() if len(x)%2 == 0] print letter y = len(letter) while y > 0: print "even!" y -= 1 for x in range(101): if x%3 == 0 and x%5 == 0: print "FizzBuzz" elif x%3 == 0: print "Fizz" elif x%5 == 0: print "Buzz" else: print x stri = 'Create a list of the first letters of every word in this string' lstr = [word[0] for word in stri.split()] print lstr
true
3406efbb56e904802ebf76181d695e3721b3dc40
anshi595/Python_codes
/02_Arrays/09_reverseelemofarray.py
204
4.5625
5
#WAP to reverse all the elements of an array arr= [] n= int(input("Enter size of array")) print("Enter elements of array") for i in range(n): x=int(input()) arr.append(x) arr.reverse() print(arr)
true
5b001945a1dad4149f1134f4141b2523dbf1de31
Ganesh-sunkara-1998/Python
/Important codes/zitamine labs question.py
537
4.3125
4
''' functions takes an arguments takes a number and that towards number how many even number are there (or) that number less than how many numbers are even''' # Asked in zetamine labs..... def fun(n): count=0 for i in range(1,n+1): if i%2==0: print("the number is even",i) count+=1 else: print("the number is odd",i) print("how many even numbers are their is:-", count) def main(): n=int(input("enter your number:-")) fun(n) main()
true
115bc8348079d242761066c5c8e7805bccd053df
HaiderParekh/Python-Cloud-Counselage
/CodingQuestion1LP3.py
1,018
4.15625
4
#CODING QUESTIONS:​1 (This code wass executed in Visual Studio Code) ##Read two integers from STDIN and print three lines where: #● The first line contains the sum of the two numbers. #● The second line contains the difference between the two numbers (first - second). #● The third line contains the product of the two numbers. #Input Format #The first line contains the first integer, a. The second line contains the second integer, b ###Constraints #1<_a<_10​10 1<_b<_10​10 #Output Format Print the three lines as explained above #Sample Input 3 2 #Sample Output 5 1 6 a = int(input()) #Take user input for a and b b = int(input()) if 1<=a<=10*10 and 1<=b<=10*10: sum = a+b difference = a-b product = a*b print (sum) #sum of a and b print (difference) #difference between a and b print (product) #product of a and b #End of question 1
true
622ea7f204a4c8e135ccd0a5b689aa40e121f2ae
jicahoo/pythonalgr
/leetcode/232_ImplementQueueUsingStacks.py
1,368
4.21875
4
class Queue(object): def __init__(self): """ initialize your data structure here. """ self.stack_primary = [] self.stack_standby = [] def push(self, x): """ :type x: int :rtype: nothing """ # Move primary stack to stand-by stack while len(self.stack_primary) != 0: peek_val = self.stack_primary[len(self.stack_primary) - 1] self.stack_primary.pop() self.stack_standby.append(peek_val) # Append the element to to be added. self.stack_standby.append(x) # Move standby stack to primary stack while len(self.stack_standby) != 0: peek_val = self.stack_standby[len(self.stack_standby) - 1] self.stack_standby.pop() self.stack_primary.append(peek_val) def pop(self): """ :rtype: nothing """ self.stack_primary.pop() def peek(self): """ :rtype: int """ return self.stack_primary[len(self.stack_primary) - 1] def empty(self): """ :rtype: bool """ return len(self.stack_primary) == 0 if __name__ == '__main__': q = Queue() q.push(1) q.push(2) q.push(3) q.push(4) q.push(5) while not q.empty(): print q.peek() q.pop()
false
939a70f6ca497b8dec81ff5161f28fd52a736bf7
ericjwhitney/pyavia
/examples/solve/dqnm_example.py
1,169
4.3125
4
#!usr/bin/env python3 # Examples of the solution of systems of equations. # Last updated: 21 December 2022 by Eric J. Whitney import numpy as np from pyavia.solve.dqnm import solve_dqnm def linear_system_example(x): """A simple linear system of equations.""" n = len(x) res = [0] * n for i in range(n): for j in range(n): res[i] += (1 + i * j) * x[j] return res def std_problem_1(x): """Standard start point x0 = (0.87, 0.87, ...)""" return [np.cos(x_i) - 1 for x_i in x] def std_problem_3(x): """Standard start point x0 = (0.5, 0.5, ...)""" n = len(x) f = [0.0] * n for i in range(n - 1): f[i] = x[i] * x[i + 1] - 1 f[n - 1] = x[n - 1] * x[0] - 1 return f # Solve one of the above problems at a given size. ndim = 500 x0 = [0.5] * ndim bounds = ([-1] * ndim, [+np.inf] * ndim) x_result = solve_dqnm(std_problem_1, x0=x0, ftol=1e-5, xtol=1e-6, bounds=bounds, maxits=50, order=2, verbose=True) print("\nResult x = " + np.array2string(np.asarray(x_result), precision=6, suppress_small=True, separator=', ', sign=' ', floatmode='fixed'))
true
c900f02dda4d91f4a9e61dca2411e2b069d7ea8f
KSHITIJ-BISHT/Bootcamp-Assignment-2
/circle.py
1,588
4.1875
4
#Calculating area ,perimeter of a crcle and compairing two circles import math class Circle: def __init__(self,radiusOfCircle): self.radiusOfCircle=radiusOfCircle def calculateAreaOfCircle(self): return 2* math.pi *self.radiusOfCircle**2 def calculatePerimeterOfCircle(self): return 2*math.pi*self.radiusOfCircle #Defining less than function def __lt__(self,other): return self.radiusOfCircle<other.radiusOfCircle #Defining less than or equal function def __le__(self,other): return self.radiusOfCircle<=other.radiusOfCircle #Defining equals function def __eq__(self,other): return self.radiusOfCircle==other.radiusOfCircle #Defining not equal function def __ne__(self,other): return self.radiusOfCircle!=other.radiusOfCircle #Defining greater than function def __gt__(self,other): return self.radiusOfCircle>other.radiusOfCircle #Defining greater than or equal function def __ge__(self,other): return self.radiusOfCircle>=other.radiusOfCircle firstCircle=Circle(1) secondCircle=Circle(1) print("Area of circle is:",int(firstCircle.calculateAreaOfCircle())) print("Perimeter of circle is:",(firstCircle.calculatePerimeterOfCircle())) #Comparisions of two objects print("Both circles equal?:",firstCircle==secondCircle) print("Checking for less than or equal?:",firstCircle<=secondCircle) print("Checking for greater than or equal?:",firstCircle>=secondCircle) print("Checking for greater than?:",firstCircle>secondCircle) print("Checking for lesser than?:",firstCircle<secondCircle) print("Checking for not equal?:",firstCircle!=secondCircle)
true
fa1ee062b730d84eb06f1db5ff411b898aa55dc3
fenriquegimenez-zz/practicas-python
/dict_flowers.py
625
4.3125
4
# Let's say you have a dictionary matching your friends' names with their favorite flowers: # favfl = {'Alex': 'field flowers', 'Kate': 'daffodil', # 'Eva': 'artichoke flower', 'Daniel': 'tulip'} # Your new friend Alice likes orchid the most: add this info to the favfl dict and print the dict. # NB: Do not redefine the dictionary itself, just add the new element to the existing one. def run(): favfl = {'Alex': 'field flowers', 'Kate': 'daffodil', 'Eva': 'artichoke flower', 'Daniel': 'tulip'} favfl['Alice'] = 'orchid' print(favfl['Alice']) if __name__ == "__main__": run()
true
4a1acd2671c86ec819bd40268d3f6be496b9cf88
Yashwant077/Python_Mini_Projects
/miniProject2.py
572
4.15625
4
# Project Name: Faulty calculator """ It will incorrectly calculate following 3 calculations: 45*3 = 555 56+9 = 77 56/6 = 4 """ num1 = int(input("Enter First number:: ")) num2 = int(input("Enter Second number:: ")) oper = input("Choose your operation from +,*,/:: ") if oper == "+": print(num1+num2) elif oper =="*": print(num1*num2) elif oper =="/": print(num1/num2) elif oper == "*" and num1 == 45 and num2 == 3: print("555") elif oper == "+" and num1 == 56 and num2 == 9: print("77") elif oper == "/" and num1 == 56 and num2 == 6: print("4")
false
28fb369685e70ef6692dbbecbeefbf9fccca15f1
PiyushBagani15/DSA-Solutions
/Day-1/Permutations.py
978
4.125
4
# Problem Statement: # Write a function that takes in an array of unique integers and returns an # array of all permutations of those integers in no particular order. # If the input array is empty, the function should return an empty array. def permutations(list): if list == [] or len(list) == 1: return [list] else: sub = [] ret_list = [] for i in range(len(list)): list[0],list[i] = list[i],list[0] #swapping 1st element with ith element sub = permutations(list[1:len(list)]) ret_list = ret_list + [[list[0]] + sub[j] for j in range(len(sub))] return ret_list print(permutations([1,2])) '''def powerset(original, newset): if original == []: return [newset] else: res = [] for s in powerset(original[1:], newset+[original[0]]): res.append(s) for s in powerset(original[1:], newset): res.append(s) return res print(powerset([1,2,3], []))'''
true
95d48ae72463ebd0c6c0ab9f80cd3265aa76dc02
shaynelyj/Python
/Calculator.py
1,086
4.4375
4
#A simple calculator to do basic operators + - * / def num_1(): while True: try: num1 = int(input("First Number: ")) except: print("Please input an integer!") else: return num1 def num_2(): while True: try: num2 = int(input("Second Number: ")) except: print("Please input an integer!") else: return num2 def opt_input(): q = "" while not (q == '+' or q == '-' or q == '*' or q == '/'): q = input("Enter an operator - '+, -, *, /': " ) return q def replay(): r = "" while not (r == "y" or r == "n"): r = input("Calculate again? Y or N?: ").lower() return r while True: q = num_1() w = num_2() e = opt_input() if e == "+": print (q+w) elif e == "-": print (q-w) elif e == "*": print (q*w) elif e == "/": print (q/w) r = replay() if r == "y": continue else: print ("Thanks for using!") break
false
eeeba17457eeedf1721366546eb7b90adab8fe1d
lexjox777/Variables
/main.py
1,666
4.15625
4
# # add 'Tee' to variable 'name' # name="Tee" # print(name) #============================ # # assign same values to multiple variables on the same line # a=b=c='cat' # print(a) # print(b) # print(c) # #============================ # reuse variable names, the last assignment is printed # colour ='Red' # colour ='Blue' # print(colour) # #============================ # # legal variable names # firstname="John" # first_name="John" # firs_tname="John" # firstName="John" # firstname2="John" # FIRSTNAME="John" # _first_name="John" #============================ # illegal variable names # first-name="John" # first name="John" # 2firstname="John" #============================ # '''' # Reserved Keywords # '''' # help('keywords') # ==================== # variable types # var= 'Hello World' # print(type(var)) # var = 40 # print(type(var)) # ==================== ''' object identity ''' # score = 400 # identity= id(score) # print(identity) # score variable is saved into the pb by reference # score = 400 # pb=score # print(id(score)) # print(id(pb)) #=========================== # '''' # Object Reference # '''' # both pb and score referencing the same object # pb----> int 100<----score # score =100 # pb=score # print(pb) # print(score) # print(type(score)) # print(type(pb)) #=========================== # pb---------------> 20 # score------------>100 # pb=20 # score=100 # print(type(score)) # print(type(pb)) # print(score) # print(pb) # garbage collection # pb---------->int 20 # score------------> str'Completed' # ------------->int 100 pb=20 score=100 score='Completed' print(type(score)) print(type(pb)) print(pb) print(score)
true
c773b59a5406428d8548c755668616e0e790bf20
uniyalabhishek/LeetCode-Solutions
/Python/longestMountatinSubarray..py
1,022
4.34375
4
# QUESTION : LONGEST MOUNTAIN SUBARRAY. # DESCRIPTION: In this question we have to find the max length of subarray which is a mountain. # Approach : The basic condition for a subarray to be a mountain is that there should be a peak (a largest element). # We can find the peak , and then iterate to the left and to right till our condition is satisfied and then calculate # the length. def longest_mountain_subarray(a): max_len = 0 for i in range(1, len(a) - 1): # Finding peak. if a[i] > a[i + 1] and a[i] > a[i - 1]: # pointer which will move to the left. l = i # pointer which will move to right. r = i while l > 0 and a[l] > a[l - 1]: l -= 1 while r < len(a) - 1 and a[r] > a[r + 1]: r += 1 # calculating max length. max_len = max(max_len, (r - l) + 1) return max_len # Example test case. a = [2, 1, 4, 7, 3, 2, 5] print(longest_mountain_subarray(a))
true
f217b829f1e62f9d69bf2c7edc40b674af5044de
NEvans85/algorithms
/hacker_rank/data_structures/linked_lists/reverse_dbl_linked_list.py
676
4.125
4
# prompt: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem """ Reverse a doubly linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None, prev_node = None): self.data = data self.next = next_node self.prev = prev_node return the head node of the updated list """ def Reverse(head): if not head or not head.next: return head node = head while node.next: prev = node node = node.next prev.next, prev.prev = prev.prev, prev.next node.next, node.prev = node.prev, node.next return node
true
26e929b9925cb9193a63a0da798da215fae3e946
NEvans85/algorithms
/codefights/interveiw_practice/backtracking/nQueens.py
2,741
4.25
4
""" In chess, queens can move any number of squares vertically, horizontally, or diagonally. The n-queens puzzle is the problem of placing n queens on an n × n chessboard so that no two queens can attack each other. Given an integer n, print all possible distinct solutions to the n-queens puzzle. Each solution contains distinct board configurations of the placement of the n queens, where the solutions are arrays that contain permutations of [1, 2, 3, .. n]. The number in the ith position of the results array indicates that the ith column queen is placed in the row with that number. In your solution, the board configurations should be returned in lexicographical order. Example For n = 1, the output should be nQueens(n) = [[1]]. For n = 4, the output should be nQueens(n) = [[2, 4, 1, 3], [3, 1, 4, 2]] This diagram of the second permutation, [3, 1, 4, 2], will help you visualize its configuration: The element in the 1st position of the array, 3, indicates that the queen for column 1 is placed in row 3. Since the element in the 2nd position of the array is 1, the queen for column 2 is placed in row 1. The element in the 3rd position of the array is 4, meaning that the queen for column 3 is placed in row 4, and the element in the 4th position of the array is 2, meaning that the queen for column 4 is placed in row 2. Input/Output [execution time limit] 4 seconds (py3) [input] integer n The size of the board. Guaranteed constraints: 1 ≤ n ≤ 10. [output] array.array.integer All possible distinct board configurations of the placement of the n queens, ordered lexicographically. """ def nQueens(n): placements = [] workingPlacement = [] # this function tests whether a placement is valid def canPlace(rIdx, cIdx): for pcIdx, prIdx in enumerate(workingPlacement): if rIdx == prIdx or abs(cIdx - pcIdx) == abs(rIdx - prIdx): return False return True # This recursive function tests each row for validity, testing the next column if a # placement is valid. When a column contains no valid rows, the previous stack resumes, # testing the next valid row for it's column. When the workingPlacement list is the right # length (n), it is complete and the solution is added to a list to be returned. def testPlacements(cIdx): for rIdx in range(n): if canPlace(rIdx, cIdx): workingPlacement.append(rIdx) if len(workingPlacement) == n: placements.append([el + 1 for el in workingPlacement]) else: testPlacements(cIdx + 1) workingPlacement.pop() testPlacements(0) return placements
true
e7e129a293b1d94c22f8b8f4340cb898a575ed12
jaychovatiya4995/Assignment1MD
/pro20.py
272
4.375
4
# check entered text is palindrome or not str1 = input("Enter text to check it's palindrome or not :") str2 = str1.upper() str3 = str2[::-1] # print(str2) if str2 == str3 : print(f'{str1} is palindrome') else : print(f'{str1} is not palindrome')
true
55254b8b19df7fbbb4747424f6d2b139d2477f33
JTemps1/Python-Playground
/Password Validator.py
1,300
4.28125
4
''' Simple password validator program that will ask the user for a password, then check if it obeys the following conditions: - Must be between 5 and 10 characters long - Must not contain spaces - Must contain at least one number - Must contain at least one special character ''' import string caps = list(string.ascii_uppercase) letters = list(string.ascii_lowercase) ints = list(map(str, range(10))) specs = list(string.punctiation) password = input('Password: ') if len(password) > 10: print('Password too long.\n') elif len(password) < 5: print('Password too short.\n') elif password.count(' ') != 0: print('Password must not contain spaces.\n') else: integers = 0 capitals = 0 specials = 0 for char in password: if char in ints: integers += 1 elif char in caps: capitals += 1 elif char in specs: specials += 1 else: pass if integers == 0: print('Password must contain at least one number.\n') elif capitals == 0: print('Password must contain at least one upper case letter.\n') elif specials == 0: print('Password must contain at least one special character.\n') else: print('Password valid!\n')
true
37bc0804a716badcb0134b492bea46c862d8a23f
fangshulin2517/Python
/判断身材是否合理.py
619
4.125
4
weight=float(input("请输入您的体重(kg):")) height=float(input("请输入您的身高(m):")) bmi=weight/(height*height) if bmi<18.5: print("您的BMI指数为:"+str(bmi)) print("您的体重过轻,该多吃吃哟!") if bmi>=18.5 and bmi<24.9: print("您的BMI指数为:"+str(bmi)) print("您的体重正常,请继续保持哟!") if bmi>=24.9 and bmi<29.9: print("您的BMI指数为:" + str(bmi)) print("您的体重偏胖,是时候跑起来了!") if bmi>=29.9: print("您的BMI指数为:" + str(bmi)) print("您的体重过重,跑的不能停!")
false
e6e331d9edbe6412b15b641f116b9707c2a239e6
dbuedo/python-tests
/basics/008-functions.py
1,945
4.21875
4
def basicFunction(param1, param2): print "param1 is " + str(param1) + " and param2 is " + str(param2) return str(param1) + str(param2) print "basicFuncntion with param1 = a and param2 = b returns : " + basicFunction("a", "b") print "params are polymorphic : param1 = 1 and param2 = b returns : " + basicFunction(1, "b") print "params are polymorphic : param1 = True and param2 = 10.2 returns : " + basicFunction(True, 10.2) def functionWithDefaults(param1 = False, param2 = False, param3 = False): if param1: print " param1 is passed True" if param2: print " param2 is passed True" if param3: print " param3 is passed True" print "function can have default values for params. So you can call a fucntion" print "this way: " functionWithDefaults(True, True, True) print "or this way:" functionWithDefaults(True, True) print "or this other way:" functionWithDefaults(True) print "or even without params:" functionWithDefaults() print "functions always returns something, if there isn't return statements it will return : " , functionWithDefaults() print "Another cool feature is passing functions to another functions by parameters." def move(animal="Humans", kindOfMove="watch TV"): if callable(kindOfMove): # check if param is a function (can be 'called') return animal + " " + kindOfMove() + "." else: return animal + " " + kindOfMove + "." def run(): return "run" def fly(): return "fly" def swim(): return "swim" print move("Lions", run) print move("Birds", fly) print move("Fishes", swim) print move() print "In python, functions can return multiple objects as a tuple" def returnMultipleValues(): return 1, "a", True # assing every value to a variable position, character, isVowel = returnMultipleValues() print "character '" + str(character) + "' is in position " + str(position) + ". Is it vowel? " + str(isVowel)
true
e0f5027edcb4d31e7f4a22e9d5a4fa42fe9cb5d1
novas0x2a/config-files
/.vim/scripts/SwapArguments.py
1,850
4.15625
4
#!/usr/bin/env python import re def swap(text): '''Swap the args of a 2-argument macro >>> swap('a(b,c);') 'a( c, b );' >>> swap('a(b(c,d),e);') 'a( e, b(c,d) );' >>> swap('a((b,c));') 'a((b,c));' >>> swap('a(b(c,d),e(f,g));') 'a( e(f,g), b(c,d) );' >>> swap('a(b,c,d);') 'a(b,c,d);' >>> swap('a(b,c);\\nd(e,f);') 'a( c, b );\\nd( f, e );' >>> swap('a(b,c)') 'a(b,c)' >>> swap(' a(b,c);') ' a( c, b );' >>> swap(' a(b,c,d);') ' a(b,c,d);' >>> swap('blah blah a(b,c);') 'blah blah a(b,c);' >>> swap('a(b,c); blah blah') 'a(b,c); blah blah' ''' result = [] for line in text.split('\n'): result.append(swapline(line)) return '\n'.join(result) def swapline(line): m = re.search('^(\s*)([A-Za-z_]\w*)\(\s*(.*)\s*\);\s*$', line) if not m: return line indent, func = m.group(1), m.group(2) args = parse_args(m.group(3)) if len(args) != 2: return line return '%s%s( %s, %s );' % (indent, func, args[1], args[0]) def parse_args(s): args = [] pending = '' depth = 0 for c in s: if c == '(': depth += 1 pending += c elif c == ')': depth -= 1 pending += c elif depth == 0 and c == ',': args.append(pending) pending = '' elif depth == 0 and c == ' ': pass else: pending += c assert(depth == 0) args.append(pending) return args if __name__ == '__main__': try: import vim except ImportError: # Not running inside vim. Just do doctests. import doctest doctest.testmod() else: r = vim.current.range vim.current.buffer[r.start:r.end+1] = map(swapline, r)
false
98228bf388a87f742d64b939af2a65f6e720b6de
Swapnil-ingle/Python-projects
/collatz.py
317
4.28125
4
def collatz(number): if((number % 2)==0): print(number//2) return number//2 elif((number%2)==1): print(3*number+1) return 3*number+1 try: number=int(input('Enter your number:')) except ValueError: print('The user should only enter integer') exit() while number!=1: number=collatz(number)
true
14d8f97ef28b71a6772584e6427373940dc31256
HBalija/data-structures-and-algorithms
/02-recursion/03-recursion-helper/02-recursion-helper.py
486
4.25
4
#!/usr/bin/env python3 def collect_odd_values(lst): """ Return odd values from given array. Function uses recursive helper method. """ result = [] def helper(sub_lst): # recursive function if not len(sub_lst): return if sub_lst[0] % 2 != 0: result.append(sub_lst[0]) helper(sub_lst[1:]) helper(lst) return result print(collect_odd_values([1, 2, 4, 3, 5, 66, 77, 89])) # [1, 3, 5, 77, 89]
true
297d9cb80a891057436cbf4c6354304ce0bf5145
HBalija/data-structures-and-algorithms
/11-priority-queues/03-list-implementation.py
742
4.3125
4
#!/usr/bin/env python3 """ Priority queue - List Sort O(n log n)time Dequeue O(n)time """ class PriorityQueue: def __init__(self): self.values = [] def enqueue(self, val, priority): self.values.append(dict(val=val, priority=priority)) self.sort() def dequeue(self): return self.values.pop(0) def sort(self): self.values.sort(key=lambda x: x['priority']) q = PriorityQueue() q.enqueue('B', 3) q.enqueue('C', 5) q.enqueue('D', 2) q.enqueue('Q', 20) q.enqueue('P', 1.5) print(q.values) """ values sorted based on priority [ { val: 'P', priority: 1.5 }, { val: 'D', priority: 2 }, { val: 'B', priority: 3 }, { val: 'C', priority: 5 }, { val: 'Q', priority: 20 } ] """
false
52bb4e8324f1547542ef5b4e52c6c21d11199e21
harshuop/Python-Crash-Course
/Addition_Calculator.py
311
4.15625
4
def addition(num1, num2): try: x = int(num1) + int(num2) except ValueError: print(' Please use numbers\n') else: print(' Ans: ' + str(x) + '\n') while True: n1 = input(' What is your first number: ') n2 = input('What is your second number: ') addition(n1, n2)
true
ef8fb9faa9cc73fa423122593a0c36644056d0ce
bmdvt90/python_work
/parrot.py
223
4.25
4
number = input("Give me a number, and I will tell you is it is divisible by 10: ") number = int(number) if number % 10 == 0: print(str(number) + " is divisible by 10") else: print(str(number) + " is not divisble by 10")
true
4b397f16003f16ebb439eec17ae90aeeaf10b9c0
brandonfry/LPTHW_EX45
/ex45_text.py
1,176
4.125
4
""" This file contains functions to aid text adventures in handling both text output and input. """ import os import textwrap def clear(): """This function clears the screen regardless of OS.""" os.system('cls' if os.name == 'nt' else 'clear') return def newline(): """Just wanted a way not to type backslash.""" print "\n" return def wrapit(input_text): """Uses textwrap.py to format paragraphs neatly. Textwrap outputs an array of lines to be printed. Print array entries individually and finish with a new line. """ # Replaced whitespace so that \n would be left behind. wrapped = textwrap.wrap(input_text, width=60, replace_whitespace=True) for line in wrapped: print line newline() return def carriage_return(): """Waits for user to "scroll" the screen by way of clearing it.""" raw_input(">> PRESS RETURN") clear() return def get_input(): """Grabs user input and returns it as a lowercase string. Null responses are disallowed. """ response = raw_input(">> ENTER CHOICE: ") if response == '': response = get_input() return response.lower()
true
16ce211b4d644bb88334b927f50e404223a23401
shanavas786/coding-fu
/hackerrank/algo/is_bst.py
1,334
4.28125
4
#!/usr/bin/env python3 # Given the root node of a binary tree, can you determine if it's also a binary search tree? def check_binary_search_tree_(root): nodes = [] current = root current_val = None while True: if current: nodes.append(current) current = current.left elif nodes: current = nodes.pop() if current_val is None: current_val = current.data elif current_val >= current.data: return False current_val = current.data current = current.right else: break return True class node: def __init__(self, data): self.data = data self.left = None self.right = None def test(): n1 = node(1) n2 = node(2) n3 = node(3) n4 = node(4) n5 = node(5) n6 = node(6) n7 = node(7) n3.left = n2 n3.right = n6 n2.left = n1 n2.right = n4 n6.left = n5 n6.left = n7 print(check_binary_search_tree_(n3)) def test1(): n1 = node(1) n2 = node(2) n3 = node(3) n4 = node(4) n5 = node(5) n6 = node(6) n7 = node(7) n4.left = n2 n4.right = n6 n2.left = n1 n2.right = n3 n6.left = n5 n6.left = n7 print(check_binary_search_tree_(n3))
true
67e426860887488b35a7451f843398332bc5ad32
jonnydubowsky/cess
/cess/agent/prereq.py
2,035
4.125
4
import math class Prereq(): """a prerequisite, e.g. for a goal or an action""" def __init__(self, comparator, target): """a comparator is a 2-arity predicate; the target is the value to compare to. generally you would use something like `operator.le` as a comparator.""" self.target = target self.comparator = comparator def __call__(self, val): return self.comparator(val, self.target) def __and__(self, other_prereq): return AndPrereq(self, other_prereq) def __or__(self, other_prereq): return OrPrereq(self, other_prereq) def distance(self, val): """squared normalized distance to value; squared so it can be used to calculate euclidean distance""" # if satisfied, distance = 0 if self(val): return 0 if self.target == 0: return (self.target - val)**2 return ((self.target - val)/self.target)**2 class OrPrereq(Prereq): """a multi-prerequisite with an OR relationship""" def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def __call__(self, val): return self.p1(val) or self.p2(val) def distance(self, val): """for OR relationship, minimum of distances is the distance""" return min(self.p1.distance(val), self.p2.distance(val)) class AndPrereq(Prereq): """a multi-prerequisite with an AND relationship""" def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 def __call__(self, val): return self.p1(val) and self.p2(val) def distance(self, val): """for AND relationship, the sum of the distances is the distance""" return self.p1.distance(val) + self.p2.distance(val) def distance_to_prereqs(state, prereqs): """(euclidean) distance of a state to a set of prerequisites""" dist_sum = 0 for k in prereqs.keys(): pre, val = prereqs[k], state[k] dist_sum += pre.distance(val) return math.sqrt(dist_sum)
true
67df460641c345810d65e7cefcbaed28acf62f80
pramod-karkhani/codechef_beginner
/valid_triangles.py
580
4.21875
4
*** Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees. Input The first line contains an integer T, total number of testcases. Then follow T lines, each line contains three angles A, B and C of triangle separated by space. Output Display 'YES' or 'NO' if the triangle is Valid or not respectively. *** t = int(input()) for i in range(t): ans = sum(list(map(int , input().split()))) if ans==180: print("YES") else: print("NO")
true
bef1894630f3d627a023d169651e9bd4538dc539
amulyasuresh24/Pythonassignment1
/Pythonassignnments/11.py
646
4.125
4
''' Python program to find the area of the triangle,square and circle''' def Area (radius): PI = 3.14159 area =float (PI*radius *radius) return area def Areaoftriangle(h,b): areat=float(h*b)*0.5 return areat def Areaofsquare(a): areas=float(a*a) return areas; radius = int(input("enter the radius of the circle:")) h=float(input("enter the height of the triangle:")) b=float(input("enter the base of the triangle:")) a=float(input("enter the side of the squre:")) print("area of the circle:",Area(radius)) print("area of the triangle:",Areaoftriangle(h,b)) print("area of the square:",Areaofsquare(a))
false
254a01685c904b1d20583a572895a6e9a42bfe40
brockorr/git_python_project
/projects20170307.py
2,887
4.625
5
#!/usr/bin/python ''' below are lessons from week 6 of the python class. 1. Create a function that returns the multiplacaion of a product of three params: x,y,z z should have a default value of 1. ''' asdf print("Project 1") # A Call the function will all positional arguments def funct_a(x,y,z=1): return x*y*z # B Call the function will all named arguments def funct_b(x,y,z): return x*y*z # C call the function with a mix of positional and named arguments. def funct_c(x,y,z): return x*y*z # D call the function with only two arguemts and use the default value of z. def funct_d(x,y,z=1): return x*y*z print funct_a(1, 2, 3) print funct_b(x=1,y=2,z=3) print funct_c(1, 2, z=3) print funct_d(1,2) print("Project 2") ''' Write a function that converts a list to a dictionary where the index of the list is used as the key to the new dictionary. The function should return the new dictionary. Notes: ways to findor iterateate over the length of a list. 1. len(list_var) -- this returns an int of the list. 2. for index, value in enumerate(list_var): print(index, value) Enumerate is an object that stores the index and the value of the index. ''' # Declaring a list gateway_router_attributes = ["model", "sn", "market_name", "city", "ip"] # Convert the list into a dictionary def transform_to_dictionary(a_list): # Create the dictionary dictionary = {} # Figure out how long the list is # len() # Then use a loop to iterate over the list and add the dictionary for index, value in enumerate(a_list): dictionary.update({value: ""}) return dictionary # Then call the function converted_list = transform_to_dictionary(gateway_router_attributes) print(converted_list) print("###################") ''' And now I'm going to convert the ip address validation code into a function, take one variable (ip address) and return whether it's a valid IP - true or false ''' # I did this a little differently, but we can still do the lesson. # first import socket so we can deal with the IP address. # Remember, socket a to n technically converts the ip address to a number, but it only # Converts valid addresses, which is why it's valid to do this way. import socket def test_ipv4_address(ip): check = False try: socket.inet_aton(ip) check = True except: check = False return check ip_address = "10.5.0.999" print(test_ipv4_address(ip_address)) ''' Now i'm supposed to call it from the python command prompt. First import the file with an import {filename} statement Second call the function by typing {filename}.test_ipv4_address({ip_var}) Now im supposed to call it another way First import the file with a from {filename} import {test_ipv4_address} NOTE: This executes all the things in the main init section of the file before it loads the funtion into itself. Second, you can then call the function directly without using the module. '''
true
7af59e9daed6839337f86c1095de23d821efe30b
fairclon0508/cti110
/P5T1_KilometerConverter_FairclothN.py
539
4.15625
4
# Kilometer converter # 7/14/2019 # CTI-110 P5T1_KilometerConverter # Faircloth, N # def main(): km = input('Enter a distance in kilometers: ') try: km = float(km) except: print('Input must be a number.') return 1 miles = convert(km) print(format(km, ',.2f'), 'kilometers is ', format(miles, ',.2f'), 'miles.') # convert kilometers to miles def convert(num1): miles = num1 * 0.6214 return miles main()
true
873840460d2c90adb134584a89b41694cbba5435
fairclon0508/cti110
/p4t1a_FairclothN.py
597
4.125
4
# CH 4 Tutorial # 6/29/2019 # CTI-110 P4T1 - Turtle shapes # Faircloth N # import turtle def main(): win = turtle.Screen() t = turtle.Turtle() #make pen blue, draw square using for loop t.color('blue') for i in range(4): t.forward(100) t.left(90) #move pen t.penup() t.backward(200) t.pendown() #make pen red, draw triangle using for loop t.color('red') for i in range(3): t.forward(100) t.left(120) #wait for user to close window win.mainloop() main()
false
1526f42b46977a475750cb635a9da070a1934ae7
nazrul-avash/Python-Practise
/General_Practises/BirthDay.py
463
4.15625
4
birthDays = {"Alice": "2 april", "Bob": "5 june", "Carol": "12 july"} while True: print("Enter a name:") name = input() if name == "": break if name in birthDays: print(birthDays[name] + " is the birth day of" + name) else: print(name +" is not added") bDay = input() birthDays[name] = bDay print("Updated") dates = list(birthDays.keys()) print(dates) del dates[1] print(birthDays) print(dates)
true
d237ed0ef8165b2dc5548bf801585f3952ffc204
gitmengzh/python_base
/py_list_tuple_str_set_dict.py
1,276
4.5
4
''' str、tuple、set、dict、list 几种数据结构之间的转换 ''' # list、str convert_list = [1, 2, 4, 'a', 'max'] str_list = str(convert_list) print(str_list, type(str_list)) convert_str1 = 'string' convert_str2 = 'This is string' str_list1 = list(convert_str1) # 讲一个字符串转化成一个列表 str_list2 = list(convert_str2) # 将一个字符串转化成一个列表 str_list3 = convert_str2.split(' ') # 讲一个字符串转化成一个列表,以空格为拆分 print(str_list1, str_list2, str_list3) # ['s', 't', 'r', 'i', 'n', 'g'] ['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 's', 't', 'r', 'i', 'n', 'g'] ['This', 'is', 'string'] # list 转 str convert_list2 = ['1', '2', 'a', 'hello'] convert_str3 = ''.join(convert_list2) print(convert_str3) # 输出 12ahello, 必须保证list中全部都是字符格式的元素 # list&tuple list和tuple互相转换直接强制转化 list_tuple1 = (1,2,'a') tuple_list1 = [22,'a'] print(list(list_tuple1), tuple(tuple_list1)) ''' 复习一下list和tuple的区别,list 有序 可变,tuple 有序、不可变 如何让tuple可变呢,在tuple中嵌套list(或者其他可变数据结构),改变list ''' L = {'p':'P','y':'Y','t':'T','h':'H','o':'O','n':'N'} print('_'.join(L.values()))
false
3458f56ce1ccff4104509988dcb9bd516bfb33f4
nitebaron/practise
/nonlinear.py
1,354
4.15625
4
import numpy as np import math import matplotlib.pyplot as plt from scipy.misc import derivative # solving non linear equations using the # bisection method: repeated halving of the interval. pick two points x1 # and x2 such that f(x1) and f(x2) have opposite signs. Then find the # midpoint x3 = (x1+x2)/2, and test its sign, then replace either x1 or x2 with this # midpoint depending on the sign of the midpoint (so that we'd get closer to the root) # newton raphson method: pick a point x1 near the root of interest, then x2 # is given by x2 = x1 - f(x1)/f'(x1) # WARNING: if you take a wrong initial point x1, this method might take you further # away from the root. def f(x): return 3*math.exp(-x)-x+3 def bisection(x1,x2): x3 = (x1+x2)/2 #print(x3) while abs(f(x3)) > 0.01: #sanity check #print(abs(f(x3))) #print(x3) #print(f(x3)) if f(x1)*f(x2) >= 0: print("you need one number below, and another above 0, as your root is at 0, dumb dog") break if f(x3)*f(x2) < 0: x1 = x3 #print(x1) else: x2 = x3 x3 = (x1+x2)/2 return "meh" x1 = 1.0 x2 = 15.0 x = 4.0 #print(f(3)) result = bisection(x1,x2) #print(result) def newton_raphson(x): x = x-f(x)/derivative(f, x, dx=1e-6) while abs(f(x)) > 0.01: x = x-f(x)/derivative(f, x, dx=1e-6) print(x) return "meh" print(newton_raphson(x))
true
79c39fc9fbf14b5e92f71b6ec623cf87ee87c5cc
rommelrmarquez/practice
/odd_occurrence_arr.py
801
4.15625
4
""" A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. For example, in array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired. """ def odd_occur(arr): num = 0 for i in arr: num ^= i return num def main(): assert odd_occur([9, 9, 9, 3, 9, 1, 2, 1, 2]) == 3 print('Hurray!') if __name__ == '__main__': main()
true
b5180a2dbe1f12e1bbc92874c67ea99c9a84a9ed
ahenze/python-fuer-einsteiger
/groessere_programme/beispiele/try_except_example.py
326
4.15625
4
# print all cards with even numbers. cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] for card in cards: try: number = int(card) if number % 2 == 0: # modulo operator print(card, "is an even card.") except ValueError: print (card, "can not be divided")
true
e67d6abfdfbf5a14a951094546388356bcede800
yimenglei2001/GroupStudy-Python-MachineLearning
/PythonCrashCourse/T3-7.py
663
4.28125
4
#3-4 arr=["Martin O'Donnell","Ludwig Goransson","Hans Zimmer"] for a in arr:#此处用到后面的知识。也可以一句一句的输出 print("Welcome, "+a+"!") print() #3-5 print(arr.pop(0)+"is not available.") arr.append("Henry Jackman") for a in arr: print("Welcome, "+a+"!") print() #3-6 print("I've found a bigger table.") arr.insert(0,"Alan Silvestri") arr.insert(2,"Ramin Djawadi") arr.append("Tom Salta") for a in arr: print("Welcome, "+a+"!") print() #3-7 while(len(arr)>2):#此处用到后面的知识。也可以一句一句的输出 print("I'm sorry, "+arr.pop()+", but there's no seat for you.") for a in arr: print("Welcome, "+a+"!") del arr[0] del arr[0] print(arr)
false
ecb6c92dae294c257c494338fbc8d200b8958986
bramratz/Recurance_relation
/recurance.py
1,744
4.1875
4
#! usr/bin/env python """ Given two positive integers, n and m, returns the total number of rabbit pairs that will be present after n months. Assumes starting with 1 pair. Every rabit takes a month to mature. Each pair can produce offstring, one male and one female baby rabbit (ie. a pair), each month once maturaity is reached. Rabbits live for m months before they die. """ n = 6 # Total number of months m = 3 # Months before death def mortalRabbits (nMonths: int, mLive: int) -> int: """ Given the number the total number of months the simulation should be run and the number of months each rabbit has left to live, returns an integer with the number of living rabbits after nMonths. """ # Create list of length mLive to keep track of how many living rabbits # are still in the simulation alive = [0] * mLive # Always start with one rabbit alive[-1] = 1 # Iterate over n months starting from month 2 for i in range(1, nMonths): # New babies born are equal to the number of adults present in # the population. Sum excluding the furthest column in the array # as these will be babies in the first month and are unable # to reproduce newBabies = sum(alive[:-1]) # Shift adults left 1 position (getting older) alive[:-1] = alive[1:] # Add new babies to the list alive[-1] = newBabies # After n months the total number of rabbits will be the total number # of individuals (both babies and adults) present in the array return sum(alive) # Calculate total num pairs in final round living = mortalRabbits(n, m) print(f"The total number of pairs is: {living}")
true
9deda83bdb9a2a11c5bb98dc9f8274bb375998a5
LucasBSG/exerc.py
/exercicios_sec3/exercicio25.py
373
4.125
4
numero = int(input('Digite um número: ')) print(numero) if numero > 10: print('A operação será continuada.') if numero > 20: print('O número é maior que 20') print(numero * 2) else: print('O número é menor que 20') print(numero * 5) else: print('O número não é alto o suficiente e a operação será encerrada.')
false
3baec944cb67ace46ee2d180a429eb8ee6286833
raahelpie/blind-75
/Array/contains_duplicate.py
1,202
4.25
4
""" Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. Example 1: Input: [1,2,3,1] Output: true Example 2: Input: [1,2,3,4] Output: false Example 3: Input: [1,1,1,3,3,4,3,2,4,2] Output: true """ ''' EXPLANATION: This is also a search problem, we can solve this just as we have solved the two_sum problem. Store the elements we have already seen and for every element we check if the element is in the set, if yes return true and if we reached the end without returning anything, we haven't found any duplicates hence return false. Every thing is just like the two_sum solution, except that we use a set here. If the element is already in set, we return True, if its not in set, we add it. ''' ''' What datastructure did we use and why? We used a set() datastructure because: 1. The lookup time is O(1) ''' def contains_duplicates(nums): seen = set() for each in nums: if each in seen: return True else: seen.add(each) return False print(contains_duplicates([1, 2, 3, 4]))
true
7ca06f8ae3f6eb6e99ed83fe00b5bc23ec8e3744
jiobu1/Intro-Python-I
/src/05_lists.py
964
4.375
4
""" For the exercise, look up the methods and functions that are available for use with Python lists. https://note.nkmk.me/en/python-list-clear-pop-remove-del/ https://note.nkmk.me/en/python-list-append-extend-insert/ """ x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE x.append(4) print(x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # YOUR CODE HERE x.extend(y) print(x) # Change x so that it is [1, 2, 3, 4, 9, 10] # YOUR CODE HERE x.remove(8) print(x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] # YOUR CODE HERE x.insert(-1, 99) print(x) # Print the length of list x # YOUR CODE HERE print(len(x)) # Print all the values in x multiplied by 1000 # YOUR CODE HERE x = [num * 1000 for num in x] print(x) """ Answers [1, 2, 3, 4] [1, 2, 3, 4, 8, 9, 10] [1, 2, 3, 4, 9, 10] [1, 2, 3, 4, 9, 99, 10] 7 [1000, 2000, 3000, 4000, 9000, 99000, 10000] """
true
72be734c771a6c8c6a2c8c2ae1521528471f512a
xinglongjian/AnacondaStudy
/OOP/NestedClass.py
515
4.15625
4
# -*- coding: utf-8 -*- class OuterClass: _name='outName' def __init__(self,name): self._name=name def get_name(self): return self._name """ 定义一个内部嵌套类 """ class InnerClass: def get_name(self,outer): #必须在外部类中声明该属性 return outer._name if __name__=='__main__': c=OuterClass("nestedclass") i=OuterClass.InnerClass() print(i.get_name(c))
false
a15cc9571813c68356827b7ef8a77420db8dd170
tanv1r/swe-languages
/python/2015_exercises_for_programmers_in_python/09_paint_calculator/paint_calc1.py
433
4.125
4
from math import ceil conversion_factor = 1/350 try: width = float(input("Please enter the room's width in feet: ")) length = float(input("Please enter the room's length in feet: ")) area = round(width * length, 2) gallons_needed = ceil( area * conversion_factor ) print(f"You will need to purchase {gallons_needed} gallons of paint to cover {area} square feet.") except ValueError: print("Invalid input.")
true
ace8de1ef82130b78cfb518701d6812bf7b9c0d8
tanv1r/swe-languages
/python/2015_exercises_for_programmers_in_python/02_count_char/count_char2.py
283
4.125
4
print("Type 'q' to quit.") while True: sentence = input("What is the input string? ") if sentence == 'q': break if sentence: print(sentence + " has " + str(len(sentence)) + " characters.") else: print("Please enter a non-empty sentence.")
true
552b7e53ccdb110795d579ab326f4410bbd5f45e
clee6288/PythonProjects
/Simpleimage_PixelDetection_PixelManipulation_RemoveGreenScreen/shrink.py
1,202
4.1875
4
""" File: shrink.py Name: Chris Lee ------------------------------- Create a new "out" image half the width and height of the original. Set pixels at x=0 1 2 3 in out , from x=0 2 4 6 in original, and likewise in the y direction. """ from simpleimage import SimpleImage def shrink(filename): """ :param filename: str, :return img: SimpleImage, """ old = SimpleImage(filename) blank_image = SimpleImage.blank(old.width // 2, old.height // 2) blank_image.show() for x in range(old.width): for y in range(old.height): new = blank_image.get_pixel(x // 2, y // 2) old2 = old.get_pixel(x, y) if x % 2 == 0 and y % 2 == 0: new.green = old2.green new.blue = old2.blue new.red = old2.red return blank_image def main(): """ The computer will decrease the picture size to 1/4 without changing the structure of the image while viewing. """ original = SimpleImage("images/poppy.png") original.show() after_shrink = shrink("images/poppy.png") after_shrink.show() if __name__ == '__main__': main()
true
5a72369598f26db4a2422cd312c8477ee625a059
samanthaquach/PythonStack
/PythonFiles/comparingls.py
683
4.1875
4
list_one = [1,2,5,6,2] list_two = [1,2,5,6,2] if (list_one == list_two): print ("the lists are the same") else: print ("the list are not the same") list_one = [1,2,5,6,5] list_two = [1,2,5,6,5,3] if (list_one == list_two): print ("the lists are the same") else: print ("the list are not the same") list_one = [1,2,5,6,5,16] list_two = [1,2,5,6,5] if (list_one == list_two): print ("the lists are the same") else: print ("the list are not the same") list_one = ['celery','carrots','bread','milk'] list_two = ['celery','carrots','bread','cream'] if (list_one == list_two): print ("the lists are the same") else: print ("the list are not the same")
false
334221b57b2c97802967ad52095b1d53cb33841b
bigbrainacademy/python4kids
/lec01/Project_Starwars.py
2,197
4.34375
4
## ************************************************** ## * Python4kids * ## ************************************************** ## * lecture01: starwars project * ## ************************************************** ## We are going to learn: ## - how to use comments, change line, etc ## - how to use input() and print() functions ## - how to define string and integer numbers ## - how to join two strings and manipulate numbers ## - how to use if...else... ## ************************************************** import time print("R2D2: Welcome to Star Wars!") # name=input("R2D2: What's your name? \n") # # - don't forget qotation mark "" for a string # # - \n is used for change line # print("R2D2: Hi, "+name+"!") # print("R2D2: I hope you are doing well today.") ## - The operator + is for joining two strings. # ********************************************************** # Now let's try to repeat the above operation with variables # ********************************************************** R2D2_S1 = "R2D2: What's your name? \n >>>" name = input(R2D2_S1) # Luke Skywalker. # Leia Organa. # Ben Solo. R2D2_S2 = "R2D2: Hi, "+ name+"!" R2D2_S3 = "R2D2: I hope you are doing well today." print(R2D2_S2) print(R2D2_S3) ## Now let's add some more information age = input("R2D2: How old are you? (pls enter a number)\n >>>") next_year_age = int(age) + 1 R2D2_S4="R2D2: Wow! Next year you will be "+str(next_year_age)+" years old." print(R2D2_S4) weapon=input("R2D2: What kid of weapons do you want to choose?\n >>>") # lightsaber R2D2_S4="R2D2: Good choice! Your weapon "+str(weapon)+" is really cool!" print(R2D2_S4) R2D2_S5="R2D2: Let's fight Darth Vader together!" print(R2D2_S5) print("Why don't we play a guess game to decide who will win? \n") # question question="Can you guess what I am? \n I am living in China.\ \n I am a kind of bear. \ \n I am black and white. \ \n I eat bamboo.\n >>> " time.sleep(2) # Delays for 5 seconds. print("\n") animal=input(question) R2D2_S6=" Congratulation! You win!" R2D2_S7=" Sorry! I am Panda!" if animal !="Panda" and animal !="panda": print(R2D2_S7) else: print(R2D2_S6)
true
e66e90512a1f49c829cfc5c6fbbb7bdaa78a909d
ChamoProgrammer/proyectos-python
/projects-beginners-python/whats-the-word.py
2,745
4.375
4
import random # library that we use in order to choose ------biblioteca que usamos para elegir # on random words from a list of words--------de palabras aleatorias de una lista de palabras name = input("cual es tu nombre? ") # Here the user is asked to enter the name first---------Aquí se le pide a la usuario que ingrese el nombre primero. print("Buena suerte! ", name) # word yo choice-----palabra a elegir words = ['computadora', 'programar', 'nombre', 'empezar', 'agua', 'celular', 'popo', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '10'] # Function will choose one random-La función elegirá una al azar # word from this list of words---# palabra de esta lista de palabras word = random.choice(words) print("adivina l@s personajes") guesses = '' # any number of turns can be used here---------- Aquí se puede utilizar cualquier número de vueltas turns = 12 while turns > 0: # counts the number of times a user fails---------cuenta la cantidad de veces que falla un usuario failed = 0 # all characters from the input----------todos los caracteres de la entrada # word taking one at a time.---------palabra tomando una a la vez. for char in word: # comparing that character with-----comparando ese personaje con # the character in guesses---------el personaje en conjeturas if char in guesses: print(char) else: print("NO ES CORRECTO") # for every failure 1 will be # incremented in failure failed += 1 if failed == 0: # user will win the game if failure is 0---------usuario ganará el juego si falla 0 # and 'You Win' will be given as output-------y 'You Win' se darán como salida print("ganastes...!!!🎉🎉") # this print the correct word-----------ESTA PARALABRA ES CORRECTA print("La palabra es: ", word) break # if user has input the wrong alphabet then------si el usuario ha introducido el alfabeto incorrecto, # it will ask user to enter another alphabet-------------# le pedirá al usuario que ingrese otro alfabeto guess = input("adivina un personaje:") # every input character will be stored in guesses guesses += guess # check input with the character in word if guess not in word: turns -= 1 # if the character doesn’t match the word-----si el carácter no coincide con la palabra # then “Wrong” will be given as output --------entonces se dará "Incorrecto" como salida print("incorrecto") # this will print the number of----# esto imprimirá el número de # turns left for the user---------# vueltas a la izquierda para el usuario print("tu tienes", + turns, 'mas oportunidades') # SI EL CONTADOR LLEGO A 0 EL RESULTADO SERA if turns == 0: print("PERDISTES...!!!😣😞")
false
c0768f4ba5c420f0084c4d12a609c5013e53449d
jiangyanan2000/pythoncode
/单继承.py
622
4.25
4
""" 故事主线:一个煎饼果子老师傅,在煎饼果子界摸爬滚打多年,研发了一套精湛的摊煎饼果子技术。师父要把这套技术传授给他的唯一的最得意的徒弟。 分析:徒弟是不是要继承师父的所有技术? """ #1师父类,属性和方法 class Master(object): def __init__(self): self.kongfu = "[古法煎饼果子配方]" def make_cake(self): print(f"运用{self.kongfu}制作煎饼果子") class Prentice(Master): pass #3.用徒弟类创建对象,调用实例属性和方法 daqiu = Prentice() print(daqiu.kongfu) daqiu.make_cake()
false
5f5ae4c7557155ac378600841b18aad84915a204
jiangyanan2000/pythoncode
/子类调用父类同名方法和属性.py
1,448
4.40625
4
""" 故事:很多顾客都希望也能吃到古法和黑马的技术的煎饼果子 """ class Master(object): def __init__(self): self.kongfu = "[古法煎饼果子配方]" def make_cake(self): print(f"运用{self.kongfu}制作煎饼果子") #创建学校类 class School(object): def __init__(self): self.kongfu = "[黑马煎饼果子配方]" def make_cake(self): print(f"运用{self.kongfu}制作煎饼果子") #创建学生类,添加和父类同名的属性和方法 class Prentice(School,Master): def __init__(self): self.kongfu = "[独创煎饼果子配方]" def make_cake(self): #如果不加这个自己的初始化,kongfu的值就是上一次调用的init内的kongfu的值 self.__init__() # Prentice.__init__(self) 两种方法 print(f"运用{self.kongfu}制作煎饼果子") #子类调用父类的同名属性和方法:把父类的同名属性和方法再次封装 def make_master_cake(self): #父类名.函数() #再次调用初始化的原因:这里想要调用父类的同名方法和属性,熟悉在init初始化位置,所以需要再次调用init Master.__init__(self) Master.make_cake(self) def make_school_cake(self): School.__init__(self) School.make_cake(self) daqiu = Prentice() daqiu.make_cake() daqiu.make_master_cake() daqiu.make_school_cake() daqiu.make_cake()
false
1cb649073f435cd622c0e1ad95be884a1a224906
bekbusinova/-1
/arr.py
338
4.125
4
def arr_min(arr): min = arr[0] for elem in arr: if elem < min: min = elem return min def arr_avg(arr): count = len(arr) summ = sum(elem for elem in arr) return summ / count arr = [1, 2, 4, 6, 0] print("minimum") print(arr_min(arr)) print("average") print(arr_avg(arr))
false
1a146889a8d9b35b0940400db4a793ae5d5fff17
joebehymer/python-stuff
/dicts_.py
902
4.5
4
# represent student using dictionary student = { 'name': 'Joe', 'age': 25, 'courses': ['Math', 'CompSci'], 1: 'intkey' } print(student) # get value of one key print (student['courses']) print(student[1]) # keys can be ints too # throws an error if we try to direct access a key that doesn't exist, so we can use get instead print(student.get('name')) print(student.get('phone', 'empty!')) # add phone to dictionary student['phone'] = '555-5555' print(student['phone']) # add or update things via update method student.update({'name': 'John', 'phone': '333-3333'}) print(student) # delete a key and its value # del student['age'] print(student) # pop removes and returns print(student.pop('age')) print(student) print(len(student)) print(student.keys()) print(student.values()) # looping thru dict for key, value in student.items(): print(f'Key={key}. Value={value}')
true
045547e57d667afadee0f15c337ea13dfb1d7a95
joebehymer/python-stuff
/strings.py
830
4.15625
4
message = 'Hello World' print(message) # how many chars in the string? print ("Length= " + str(len(message))) # access chars print(message[10]) # string slicing, just get hello print(message[:5]) # subset, just get world print(message[6:]) # lower case message print(message.lower()) # count chars print(message.count('l')) # find index print(message.find('World')) # replace chars message2 = message.replace('World', 'Universe') print(message2) # concat strings together greeting = 'Hello' name = 'Joe' message = greeting + ', ' + name + '. Welcome!' print(message) # format strings message = '{}, {}. Welcome!'.format(greeting, name) # new f strings in 3.6 or above message = f'{greeting}, {name.upper()}. Welcome!' print(message) # print autocomplete #print(dir(message)) #print(help(str)) # print(help(str.lower))
true
ba8c0ecdf2387180d636419c4f8e61dfe7837969
mushtaqmahboob/CodingPractice
/LeetCode/Easy/Subtree_of_another_tree(Amazon).py
1,578
4.25
4
# Defining a binary tree node # Making a node with x as its value and initializing it's left and right child as null (None in python) class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None # Define a function that takes 2 inputs basically 2 nodes # Making own function to test the similarity. Make sure to declare before you can use the function. Otherwise # you get an error 'not declared' .We are using recursive calls here as the problem resembles recursive technique. def isSametree(s, t): if s==None or t==None: return s==None and t==None elif s.val == t.val: return isSametree(s.left,t.left) and isSametree(s.right,t.right) else: return False def isSubtree(s: TreeNode, t: TreeNode): # If the tree 's' is null, there is no point of considering tree 't' as it subtree, so return false if s==None: return False if isSametree(s,t): return True else: return isSubtree(s.left,t) or isSubtree(s.right,t) # Lets write a testing code S = TreeNode(3) S.left = TreeNode(4) S.right = TreeNode(5) S.left.left = TreeNode(1) S.left.right = TreeNode(2) T = TreeNode(3) T.left = TreeNode(4) T.right = TreeNode(5) print(isSubtree(S,T)) S1 = TreeNode(3) S1.left = TreeNode(4) S1.right = TreeNode(5) S1.left.left = TreeNode(1) S1.left.right = TreeNode(2) T1 = TreeNode(4) T1.left = TreeNode(1) T1.right = TreeNode(2) print(isSubtree(S1,T1)) '''Method Used = Recursion, Time complexity = O(MN)..... M = nodes in S and N = nodes in T '''
true
edac4dd175d10a558f031100636cbab0700621cc
asyrul21/algorithm-practice
/sort/count-inversion-merge-alt.py
1,723
4.15625
4
# to understand what Count Inversion is see # https://www.geeksforgeeks.org/counting-inversions/ # inversions are counted by the sum of inversions of left # sub array, + sum of inversions of right sub array # and + the inversions in merge step # this approach does not modify original array # but very confusing lol # avoid this approach from util import isSorted, testArray2 import time ########### def _mergeSort(arr): invCount = 0 if(len(arr) > 1): mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] invCount += _mergeSort(left) invCount += _mergeSort(right) i = j = k = 0 while i < len(left) and j < len(right): if(left[i] < right[j]): arr[k] = left[i] i += 1 else: invCount += (mid - i) arr[k] = right[j] j += 1 k += 1 while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 return invCount def mergeSort(arr): # declare copy or array arrCopy = [item for item in arr] inv = _mergeSort(arrCopy) return arrCopy, inv ########### startTime = time.time() sortedArr, invCounts = mergeSort(testArray2) endTime = time.time() print("Initial Array:") print(testArray2) print("Sorted Array:") print(sortedArr) print("Inversion counts:") print(invCounts) print("Sorted: " + str(isSorted(sortedArr))) print("Execution time:") print(str(endTime - startTime)+ " ms")
true
86a07d172daebe9d1811e58e047f5e168565efda
rjloube/automateTheBoringStuff
/madLibs.py
2,128
4.4375
4
#! python 3 # madLib.py - this program lets users add their own text anywhere the word ADJECTIVE, NOUN, or VERB appears in a string. # Results are printed to the screen and written to a text file. import re # Make new text file with a mad lib sentence. madLibFile = open('madLibTemplate.txt', 'w') madLibFile.write('The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.') madLibFile.close() madLibFile = open('madLibTemplate.txt') content = madLibFile.read() madLibFile.close() print(content) # ADJECTIVE adjectiveRegex = re.compile(r'ADJECTIVE') moSearch = adjectiveRegex.search(content) if moSearch != None: print('Replace ADJECTIVE with:') moSub = adjectiveRegex.sub(input(), content, 1) inputFile1 = open('madLib1.txt', 'w') inputFile1.write(moSub) inputFile1.close() madLibFile1 = open('madLib1.txt') content = madLibFile1.read() madLibFile1.close() # NOUN nounRegex = re.compile(r'NOUN') moSearch = nounRegex.search(content) if moSearch != None: print('Replace NOUN with:') moSub = nounRegex.sub(input(), content, 1) inputFile1 = open('madLib1.txt', 'w') inputFile1.write(moSub) inputFile1.close() madLibFile1 = open('madLib1.txt') content = madLibFile1.read() madLibFile1.close() # VERB verbRegex = re.compile(r'VERB') moSearch = verbRegex.search(content) if moSearch != None: print('Replace VERB with:') moSub = verbRegex.sub(input(), content, 1) inputFile1 = open('madLib1.txt', 'w') inputFile1.write(moSub) inputFile1.close() madLibFile1 = open('madLib1.txt') content = madLibFile1.read() madLibFile1.close() # NOUN(2) nounRegex = re.compile(r'NOUN') moSearch = nounRegex.search(content) if moSearch != None: print('Replace NOUN with:') moSub = nounRegex.sub(input(), content, 1) inputFile1 = open('madLib1.txt', 'w') inputFile1.write(moSub) inputFile1.close() madLibFile1 = open('madLib1.txt') content = madLibFile1.read() madLibFile1.close() # Print results to the screen inputFile1 = open('madLib1.txt') content = inputFile1.read() inputFile1.close() print(content)
true
eb2d8ff1f664e5cd8878f40f909069503b522897
kh4r00n/SoulCodeLP
/sclp025.py
322
4.15625
4
'''Crie um programa que peça uma letra como entrada se a letra digitada for diferente de A imprima "Tente novamente" e se a letra digitada correta imprima "Agora você acertou ''' letra = str(input('Digite: ')) while letra != 'A': letra = str(input('Tente novamente: ')) print('Agora você digitou certo')
false
f76047c401bbdee8adeb82f63da070f6eac8877f
loongqiao/learn
/python1707A/0710-0716/tiger.py
694
4.15625
4
""" 这是一个老虎棒子鸡的游戏 老虎吃鸡 鸡吃虫 虫啄棒子 棒子打老虎 老虎=0 鸡=1 虫=2 棒子=3 """ #导入random模块 import random #用户输入 plyer=input("请您出招(0为老虎,1为鸡,2为虫,3为棒子): ") #电脑随机出招 computer=random.randint(0,3); #判断胜负 if (plyer=='0' and computer== '1')or (plyer=='1' and computer== '2')or (plyer=='2' and computer== '3')or (plyer=='3' and computer== '0'): print("恭喜你获得胜利") elif(computer=='0' and plyer=='1')or(computer=='1' and plyer=='2')or(computer=='2' and plyer=='3')or(computer=='3' and plyer=='0'): print("Bingo,你输了,干了这一杯吧!") else: print("平局")
false
acd5b320e2a68d19ad274de107109eecdb4dbf8c
loongqiao/learn
/python1707A/0710-0716/shijijiayuan.py
1,804
4.28125
4
""" 用于管理所有的姑娘 功能: 查看所有姑娘 新增一个姑娘 修改一个姑娘 删除一个姑娘 查询不某个姑娘 退出系统 """ #打印软件界面 print("#########################################################################") print("#\t\t世纪佳缘相亲对象管理系统 ") print("#1.查看所有注册的姑娘") print("#2.新增一个姑娘") print("#3.修改指定的姑娘") print("#4.删除一个指定的姑娘") print("#5.查看某个指定 的姑娘") print("#6.退出系统") print("###########################################################################") #定义一个保存所有姑娘的列表 girls=[] while True: #用户进行选项选择 choice=input("请输入你的选项: ") if choice=='1': #利用for循环遍历姑娘 for name in girls: print("姑娘:%s"% name) elif choice=='2': name=input("请输入你要添加的姓名:") girls.append(name) elif choice=='3': name=input("请输入你需要修改姑娘的姓名:") if name in girls: index=girls.index(name) if index>=0: name=input("请输入新的名字: ") girls[index]=name else: print("你输错名字了吧!") #判断修改的序号 """index=girls.index(name) if index >=0: name=input("请输入你要修改姑娘的姓名: ") girls[index]=name else: print("抱歉,查无此人")""" elif choice=='4': name=input("请输入你要删除姑娘的姓名:") if name in girls: girls.remove(name) else: print("查无此人") elif choice=='5': name=input("请输入你需要查看的姑娘:") if name in girls: print("该姑娘已存在") else: print("查询不到此人信息") elif choice=='6': print("客官,慢走") break else: print("没有这个选项")
false
1daf14ea74f20e331d8b65b988ef35d07731b5e9
loongqiao/learn
/python1707A/0725/demo04.py
1,618
4.15625
4
""" 烤牛排 """ class Beef(object): #如果创建对象的时候,对象的某些属性就具备固定的值,此时不需要传递参数直接使用默认值即可 def __init__(self): self.cookedDesc="生的" self.cookedInt=0 self.seasoning=[]#调料 #定义一个天加佐料的方法 def addSeasoning(self,s): self.seasoning.append(s) #字符串转换 解决输出只显示内存问题 def __str__(self): return "熟度:%s;烧烤时间:%s;佐料:%s;"%(self.cookedDesc,self.cookedInt,self.seasoning) #定义一个烧烤的行为 def bbq(self,time): self.cookedInt += time if(self.cookedInt>0)and(self.cookedInt<=2): self.cookedDesc="一分熟" elif(self.cookedInt>2)and(self.cookedInt<=5): self.cookedDesc="三分熟" elif(self.cookedInt>5)and(self.cookedInt<=7): self.cookedInt="五分熟" elif(self.cookedInt>7)and(self.cookedInt<=9): self.cookedInt="八分熟" elif(self.cookedInt>9)and(self.cookedInt<=12): self.cookedInt="熟透了" elif self.cookedInt>12: self.cookedInt="烤糊了" #python中的main方法:表示下面的代码只能执由当前文件执行 if __name__=="__main__": beef=Beef() beef.bbq(1) beef.addSeasoning("黄油") print(beef) beef.bbq(1) print(beef) beef.bbq(1) print(beef) beef.bbq(1) beef.addSeasoning("意面") print(beef) beef.bbq(1) print(beef) beef.bbq(1) beef.addSeasoning("黑椒") print(beef)
false
3d8d5ab7c1bf6d395afcfe8ff6bd9ad637e36d63
rohit196/Python_Learnings
/Basic Python Scripts/Functions.py
1,764
4.84375
5
""" Single parameter and zero parameter functions: 1.define a function that takes no parameters and prints a string 2.create a variable and assign it the value 5 3.create a function that takes a single parameter and prints it 4.call the function you created in step 1 5.call the function you created in step 3 with the variable you made in step 2 as its input """ def ex(): print("Hello World") ex() var1 = 5 def ex1(a): print(a) ex1(var1) """ multiple parameter functions: 1.create 3 variables and assign integer values to them 2.define a function that prints the difference of 2 parameters 3.define a function that prints the product of the 3 variables 4.call the function you made in step 2 using 2 of the variables you made for step 1 5.call the function you made in step 3 using the 3 variables you created for step 1 """ va1 = 1 va2 = 2 va3 = 3 def sub(a,b): print(a-b) def prod(a,b): print(a*b) sub(va2,va1) prod(va3,va2) """ Calling previously defined functions within functions: 1.create 3 variables and assign float values to them 2.create a function that returns the quotient of 2 parameters 3.create a function that returns the quotient of what is returned by the function from the second step and a third parameter 4.call the function you made in step 2 using 2 of the variables you created in step 1. Assign this to a variable. 5.print the variable you made in step 4 6.print a call of the function you made in step 3 using the 3 variables you created in step 1 """ v1 = 1.2 v2 = 2.6 v3 = 3.9 def quot(a,b): return a / b def quot1(a,b,c): return quot(a,b) / c vare1 = quot(v2,v1) print(vare1) print(quot1(v2,v1,v3))
true
55e4e41973ebd416f7d9b22e132bc5cb530ebfc5
Mbote-Joseph/Factorial-of-Number-in-Python
/Factorial.py
281
4.28125
4
num=int(input("Enter the number : ")) fact=1 if num<0: print("There are no factorials for negative numbers") elif num==0: print(f"The factoria of 0 is : {fact}") else: for i in range(1,num+1): fact=fact*i print("The factorial of {} is {}".format(num,fact))
true
3313dd3ffdfdebe5cf1b48bcdf71475dfd61de63
laurennk/oop_tutorial
/oop_playground/oop_examplex.py
2,227
4.71875
5
""" Examples using OOP in Python3 """ import abc #------------------------------------------------------------------------------# # Parent Class # #------------------------------------------------------------------------------# #class Item(): class Item(abc.ABC): #abc makes class abstract (Abstract Base Class) _count = 0 def __init__(self, name): self.name = name self._private_name = "don't access" self.__really_private = "can't access" Item._count += 1 @abc.abstractmethod def calc_price(self): #print("Calculate the price in Item") pass @classmethod def print_count(cls): print("This is a class method, I don't know my instance") print(cls._count) @staticmethod def print_date(): print("This is a static method, I don't know my class or instance") print("Today is ...") #------------------------------------------------------------------------------# # Subclasses # #------------------------------------------------------------------------------# class BookItem(Item): def __init__(self, author, **kwargs): self.author = author super().__init__(**kwargs) def get_author(self): return self.author def calc_price(self): print("Calculate the price in BookItem") #------------------------------------------------------------------------------# class FoodItem(Item): def get_exp_date(self): return '12-20-18' #------------------------------------------------------------------------------# #book_item = Item("Cats") # print(Item) # print(book_item) # print(book_item.name) # print(book_item._private_name) # #print(book_item.__really_private) #book_item.print_count() #another_item = Item("Pens") #Item.print_count() my_book = BookItem(name='Moon', author='Sam') my_book.print_count() your_book = BookItem(name='Moon', author='Sam') your_book.print_count() print(my_book.name) my_book.calc_price() print("") for i in (your_book, my_book): i.print_date() i.print_count() i.calc_price()
true
e9e8aa4d144ae96bc82ac89568134f5ffa724664
ayush-programer/pythoncode
/simplestatistics.py
1,779
4.25
4
import statistics import math grades = [80, 85, 77, 97, 100, 75, 88, 90, 93] # Mean # Here is how we calculate the mean(average) of all the grades in our list. meangrades = statistics.mean(grades) print(f'The mean of all the grades is {meangrades}') # Median # To calculate the Median, or midpoint of the grades, we’ll use this code here. mediangrades = statistics.median(grades) print(f'The median of all the grades is {mediangrades}') # Sort to view the "middle" print(sorted(grades)) # Now we can do the calculation of the mode like so. grades = [75, 80, 85, 77, 97, 100, 75, 88, 75, 90, 93, 77] modegrades = statistics.mode(grades) print(f'The mode of all the grades is {modegrades}') # Variance grades = [75, 80, 85, 77, 97, 100, 75, 88, 75, 90, 93, 77] variancegrades = statistics.variance(grades) print(f'The grades have a variance of {variancegrades}') grades = [90, 90, 90, 90, 90, 90] variancegrades = statistics.variance(grades) print(f'The grades have a variance of {variancegrades}') grades = [90, 90, 90, 90, 90, 90, 100] variancegrades = statistics.variance(grades) print(f'The grades have a variance of {variancegrades}') grades = [80, 82, 100, 77, 89, 94, 98, 50] variancegrades = statistics.variance(grades) print(f'The grades have a variance of {variancegrades}') # Standard Deviation grades = [89, 91, 95, 92, 93, 94, 98, 90] stdevgrades = statistics.stdev(grades) print(f'The grades have a standard deviation of {stdevgrades}') grades = [30, 80, 100, 45, 15, 94, 64, 90] stdevgrades = statistics.stdev(grades) print(f'The grades have a standard deviation of {stdevgrades}') grades = [30, 80, 100, 45, 15, 94, 64, 90] stdevgrades = math.sqrt(statistics.variance(grades)) print(f'The grades have a standard deviation of {stdevgrades}')
true
403bc17f5abcbb258eec1048c06baf2274369640
ayush-programer/pythoncode
/abstractclass.py
1,396
4.4375
4
# Simple Class With Inheritance class Vehicle: def __init__(self): super().__init__() def go_forward(self): print('Driving forward.') class Car(Vehicle): def __init__(self): super().__init__() class Truck(Vehicle): def __init__(self): super().__init__() vehicle1 = Vehicle() car1 = Car() car1.go_forward() truck1 = Truck() truck1.go_forward() # Adding Abstract Base Class from abc import ABC, abstractmethod class Vehicle(ABC): def __init__(self): super().__init__() @abstractmethod def go_forward(self): pass # Adding A Subclass class Car(Vehicle): def __init__(self, press_accelerator): super().__init__() self.press_accelerator = press_accelerator def go_forward(self): if self.press_accelerator: print('Driving forward') else: print('Press the accelerator to drive forward') car1 = Car(True) car1.go_forward() # A Second Subclass class Truck(Vehicle): def __init__(self, press_accelerator): super().__init__() self.press_accelerator = press_accelerator def go_forward(self): if self.press_accelerator: print('Driving forward') else: print('Press the accelerator to drive forward') truck1 = Truck(False) truck1.go_forward() truck2 = Truck(True) truck2.go_forward()
false
5908b85ffbf90093c72592f4918761e59c9a3143
andersonprovox/IntroProgPython
/Exercicio/Cap3/exc3.13.py
286
4.125
4
#Saida: converter a temperatura em C° para F° # Entrada: a temperatura em C° #Processamento: usar a formula de conversão: # f = (9 x c) / 5 + 32 celsius = float(input("Insira a temperatura em Celsius: ")) f = (9 * celsius) /5 + 32 print("A conversão em Fahrenheit: %5.2f" % f)
false