blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
55ef09f37beb7dffabe79a811837a8c0a042a4de
ComeOnTaBlazes/Programming-Scripting
/wk5weekday.py
353
4.28125
4
# James Hannon # Create program to confirm if today is a weekday # Import datetime import datetime x= datetime.datetime.now().weekday() #test of if formula #x = 5 #print (x) # Weekday values in tuple list Wkday = range (0, 5) #x = datetime.datetime.now().weekday() if x in Wkday: print ("Today is a weekday") else: print ("Today is a weekend")
true
4b79c179840e0dcebdb70592acfc383a3cae03ba
JarrodPW/cp1404practicals
/prac_01/loops.py
825
4.53125
5
# 3. Display all of the odd numbers between 1 and 20 with a space between each one for i in range(1, 21, 2): print(i, end=' ') print() # a) Display a count from 0 to 100 in 10s with a space between each one for i in range(0, 101, 10): print(i, end=' ') print() # b) Display a count down from 20 to 1 with a space between each one for i in range(20, 0, -1): print(i, end=' ') print() # c) Get a number from the user then print that amount of stars number_of_stars = int(input("Number of stars: ")) for i in range(number_of_stars): print("*", end="") print() # d) Get a number from the user then print that amount of lines with increasing stars number_of_stars = int(input("Number of stars: ")) # Note: the for loop has an in-built counter for i in range(1, number_of_stars + 1): print("*" * i) print()
true
5e994a2d80337153a660e00aaded081737907002
ilante/programming_immanuela_englander
/simple_exercises/lanesexercises/py_lists_and_loops/4.addlist_from_2.py
352
4.21875
4
# 4. use the function addlist from point 3 to sum the numbers from point 2 x='23|64|354|-123' y=x.split("|") print(y) number_list =[] # need to append int transformed stringnum for i in y: number_list.append(int(i)) print(number_list) def addlist(Liste): sum=0 for el in Liste: sum += el return sum print(addlist(number_list))
true
3eb59906b65d759a145c8503e3be187ae8f80b5a
ilante/programming_immanuela_englander
/simple_exercises/lanesexercises/py_if_and_files/4-11_more_liststuff.py
1,040
4.21875
4
# 4. put the values 5,2,7,8,1,-3 in a list, in this order li=[5,2,7,8,1,-3] # 5. print the first and the third value in the list print('question 5') print(li[0], li[2]) # 6. print the double of all the values in the list print('question 6:') doubleli=[] for el in li: dob = el*2 doubleli.append(dob) print(doubleli) # 7. print each value in the list after doubling it, subtracting 2 and dividing by 3 print('question 7:') dobsubs2div3=[] for num in li: newnum = (num*2/3)-2 dobsubs2div3.append(newnum) print(dobsubs2div3) # 8. print the sum of all the numbers in the list print('sum of all the numbers in the list') sumli=0 for num in li: sumli += num print(sumli) # 9. print the minimum value in the list print('The minimum value is:') li=[5,2,7,8,1,-3] min=li[0] for el in li: if el < min: min = el print(min) # 10. print the maximum value in the list max=li[0] for el in li: if el > max: max=el print(max) # 11. print the average value sum=0 for el in li: sum += el print(sum/len(li))
true
253ee4b4fe35698ff0e94e0f4820db33167c3a08
linkeshkanna/ProblemSolving
/EDUREKA/Course.3/Case.Study.2.Programs/target.Right.Customers.For.A.Banking.Marketing.Campaign.py
2,297
4.125
4
""" A Bank runs marketing campaign to offer loans to clients Loan is offered to only clients with particular professions List of successful campaigns (with client data) is given in attached dataset You have to come up with program which reads the file and builds a set of unique profession list Get input from User for the "Profession of Client" System tells whether client is eligible to be approached for marketing campaign Key issues: Tele Caller can only make x number of cold calls in a day. Hence to increase her effectiveness only eligible customers should be called Considerations Current system does not differentiate clients based on age and profession Data volume: bank-data.csv Business benefits: Company can achieve between 15% to 20% higher conversion by targeting right clients Approach to Solve Build a Class using OOPs concepts with Modules, Errors and Exceptions Program should be designed in a way that in future if any changes required to add age or any other factor to consider, the system should be easy to inherit/extend without changes in the main campaign 1. Read file bank-data.csv 2. Build a set of unique jobs 3. Read the input from command line 4. Check if profession is in list 5. Print whether client is eligible """ import csv import pandas as pd import re print("Enter InputFileName&path ex :F:/Python/bank-data.csv") FilePath = input() Data = pd.read_csv(FilePath, usecols=["job"]) UniqueData = Data.drop_duplicates(keep="first").sort_values(by=["job"]) Uniq_Result = UniqueData.to_string(index=False, header=False) To_Job_Match = Uniq_Result.split() print("List of Jobs Professional in File :") print(Uniq_Result) print("Enter the Job Eligibel for Loan :") Job = input() for jobcheck in To_Job_Match: if re.sub(r"[- ]", "", jobcheck.lower()) == re.sub(r"[- ]", "", Job.lower()): print("Given Job Avialble.Check Output CSV for Details") # print ('Enter OutFile Name along with path ex: F:/Python/bankdata_toTelecall.csv') # Output_File = input() df = pd.read_csv(FilePath) df["Find_Eligibel"] = ["yes" if x.strip() == Job.strip() else "No" for x in Data["job"]] # df.to_csv(Output_File,index=False) # print (df) break else: print("Given Job Not Avialble.Enter the Valid Profession")
true
93daf1a021a125b2d2568d299e94779795c3b7a8
jonahnorton/reference
/recipes/function.py
635
4.125
4
# create my own function and call it # https://www.tutorialspoint.com/python/python_functions.htm # ================================================== # simple function call def myfunction(x, y): z = x + y return z myvalue = myfunction(3, 4) print(myvalue) myvalue = myfunction(5, 3) print(myvalue) print("-------------------") # ================================================== # using keywork arguments def calc_cost(price, quantity=1): cost = price * quantity return cost bill = calc_cost(price=10, quantity=56) print(bill) # demonstrate default value for quantity bill = calc_cost(price=25) print(bill)
true
96aa3e910490ce0fb063ef1ad3faa3eb94ff8787
matyh/MITx_6.00.1x
/Week2/Problem2.py
1,820
4.53125
5
# Now write a program that calculates the minimum fixed monthly payment needed # in order pay off a credit card balance within 12 months. By a fixed monthly # payment, we mean a single number which does not change each month, but # instead is a constant amount that will be paid each month. # # In this problem, we will not be dealing with a minimum monthly payment rate. # # The following variables contain values as described below: # # balance - the outstanding balance on the credit card # # annualInterestRate - annual interest rate as a decimal # # The program should print out one line: the lowest monthly payment that will # pay off all debt in under 1 year, for example: # # Lowest Payment: 180 # Assume that the interest is compounded monthly according to the balance at # the end of the month (after the payment for that month is made). The monthly # payment must be a multiple of $10 and is the same for all months. Notice that # it is possible for the balance to become negative using this payment scheme, # which is okay. A summary of the required math is found below: # # Monthly interest rate = (Annual interest rate) / 12.0 # Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment) # Updated balance each month = (Monthly unpaid balance) + (Monthly interest # rate x Monthly unpaid balance) balance = 15 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 tempBalance = balance payment = 0 while True: payment += 10 for month in range(12): monthEndBalance = tempBalance - payment tempBalance = monthEndBalance + monthEndBalance * monthlyInterestRate # print("Month", month + 1, "balance", tempBalance) if tempBalance > 0: tempBalance = balance else: print("Lowest Payment:", payment) break
true
da3a76cfa02b4e807711be21ab4052bb88d8dabc
Shankhanil/CodePractice
/Project Euler/prob14.py
1,184
4.15625
4
""" The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. """ def collatz_chain(N): count = 1 while(N > 1): count = count+1 if N % 2 ==0: N = N/2 else: N = 3*N + 1 return count if __name__ == "__main__": Nmax = 1000000 - 1 Nmin = 13 Lcoll = 0 res = 0 for i in range(Nmax, Nmin, -2): #Lcoll = max(Lcoll, collatz_chain(i)) temp = collatz_chain(i) if temp > Lcoll: res = i Lcoll = temp print("i = {}, coll# = {}".format(i,Lcoll)) print(i) #print(collatz_chain(15))
true
237757575f46ccadcff1469e1b4398260299d081
Shankhanil/CodePractice
/Project Euler/prob9.py
512
4.21875
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc """ import math as m if __name__ == "__main__": N = 1000 for i in range(1000): for j in range(1000): py = m.sqrt(i**2 + j**2) if py + i + j == N and int(py) == py: print(i*j*int(py)) break
true
763b465c86db6fd897bd46f07364a9d9b8d75bb0
MaxSpanier/Small-Projects
/Reverse_String/reverse_string.py
947
4.25
4
import sys class ReverseString(): def __init__(self, string): self.string = string def GUI(self): self.string = input("Please enter a string:\n") def reverse(self, given_string): return given_string[::-1] def play_again(self): choice = str(input("-------------------------------\nDo you want to reverse another string? (y/n) - ")) if choice == "y": self.string = "" self.main() elif choice == "n": sys.exit() else: print("Plese enter a valid answer.") self.play_again() def main(self): if self.string == "": self.GUI() reversed_string = self.reverse(self.string) print(f"Your given string reversed looks like this: \n{reversed_string}") self.play_again() # reverser = ReverseString("Hallo") # reverser.main() reverser02 = ReverseString("") reverser02.main()
true
7fbee4fa737684b2b92fff3f0aa74aa0130aed25
samuelcavalcantii/Mundo3
/ex076-ListaPreço.py
705
4.125
4
#Exercício Python 076: Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular. listagem = 'Lápis', 1.75,'Caderno', 15.90,'Folha A4', 40.00,'Lapiseira', 10.90, 'Estojo', 25 print(listagem) print(len(listagem)) #QUANTIDADE DE ITENS NA TUPLA print('-'*40) print(f'{"LISTA DE PREÇOS":^40}') print('-'*40) for item in range (0, len(listagem)): #para saber a posição na lista if item % 2 ==0: #Volta a posição par na lista print(f'{listagem[item]:.<30}', end= ' ') #volta o item na lista de acordo com a posição else: print(f'R${listagem[item]:.2f}')
false
894927d48c2c671786b6ad1ee8ac1e854059feaa
MohammedBhatti/code1
/dogpractice.py
611
4.15625
4
dogs = ("beagle", "collie", "healer", "pug") dogs_characteristics = {} list_of_characteristics = [1, 25, 'ball'] # Loop through the list and print each value out for dog in dogs: if dog == "healer": print(dog) # Create the dict object dogs_characteristics["breed"] = dog dogs_characteristics["age"] = list_of_characteristics[0] dogs_characteristics["weight"] = list_of_characteristics[1] dogs_characteristics["favorite_toy"] = list_of_characteristics[2] # When we find a match for the dog type, create a dict obj # with the key being the dog print(dogs_characteristics)
true
d3dc0d902f8120e90c4b85b87ef67c31b0709736
devendra631997/python_code_practice
/graph/graph.py
1,540
4.25
4
# 1 2 8 # 2 3 15 # 5 6 6 # 4 2 7 # 7 5 30 # 1 5 10 # 3 5 # 2 7 # 1 6 # Add a vertex to the dictionary def add_vertex(v): global graph global vertices_no if v in graph: print("Vertex ", v, " already exists.") else: vertices_no = vertices_no + 1 graph[v] = [] # Add an edge between vertex v1 and v2 with edge weight e def add_edge(v1, v2, e): global graph # Check if vertex v1 is a valid vertex if v1 not in graph: print("Vertex ", v1, " does not exist.") # Check if vertex v2 is a valid vertex elif v2 not in graph: print("Vertex ", v2, " does not exist.") else: # Since this code is not restricted to a directed or # an undirected graph, an edge between v1 v2 does not # imply that an edge exists between v2 and v1 temp = [v2, e] graph[v1].append(temp) # Print the graph def print_graph(): global graph for vertex in graph: for edges in graph[vertex]: print(vertex, " -> ", edges[0], " edge weight: ", edges[1]) # driver code graph = {} # stores the number of vertices in the graph vertices_no = 0 add_vertex(1) add_vertex(2) add_vertex(3) add_vertex(4) add_vertex(5) add_vertex(6) add_vertex(7) # Add the edges between the vertices by specifying # the from and to vertex along with the edge weights. add_edge(1, 2, 8) add_edge(2, 3, 15) add_edge(5, 6, 6) add_edge(4, 2, 7) add_edge(7, 5, 30) add_edge(1, 5, 10) print_graph() # Reminder: the second element of each list inside the dictionary # denotes the edge weight. print ("Internal representation: ", graph)
true
b701b7cbcf31f704ec7d3cea7ab5a7f9092e542f
harshitksrivastava/Python3Practice
/DynamicPrograms/factorial.py
904
4.34375
4
# factorial using recursion without Dynamic Programming # def fact(number): # if number == 0: # return 1 # else: # return number * fact(number - 1) # ===================================================================================================================== # factorial using recursion with Dynamic Programming (Memoization) def fact(number): memory = {} if number not in memory: if number == 0: memory[number] = 1 else: memory[number] = number * fact(number - 1) return memory[number] # ===================================================================================================================== # Main function call if __name__ == "__main__": num = int(input("enter the number")) print("factorial is", fact(num)) print("factorial is", fact(num + 1)) print("factorial is", fact(num + 8))
true
9da4d5948208d4e7453bf288bfcf173c4d88beed
AM-ssfs/py_unit_five
/multiplication.py
556
4.21875
4
def multiplication_table(number): """ Ex. multiplication_table(6) returns "6 12 18 24 30 36 42 48 54 60 66 72 " :param number: An integer :return: A string of 12 values representing the mulitiplication table of the parameter number. """ table = "" for x in range(1, 13): table = table + " " + str(number * x) return table def main(): print(multiplication_table(1)) print(multiplication_table(2)) print(multiplication_table(5)) print(multiplication_table(6)) if __name__ == '__main__': main()
true
887631e111b25443c7d554ebabf65b5e4cbb7e77
eloghin/Python-courses
/PythonZTM/100 Python exercises/42.Day11-filter-map-lambda-list.py
517
4.125
4
# Write a program which can map() and filter() to make a list whose elements # are square of even number in [1,2,3,4,5,6,7,8,9,10]. def map_func(l): l = filter(lambda x: x%2==1, l) m = map(lambda x:x*x, l) return list(m) print(map_func([1,2,3,4,5,6,7,8,9,10])) ******* SOL 2 ******* def even(x): return x%2==0 def squer(x): return x*x li = [1,2,3,4,5,6,7,8,9,10] li = map(squer,filter(even,li)) # first filters number by even number and the apply map() on the resultant elements print(list(li))
true
66d361ff9b192cd686c4457bc1136c993f48e9b4
eloghin/Python-courses
/HackerRank/interview-prep-kit-alternating-characters.py
1,195
4.125
4
""" You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string. Your task is to find the minimum number of required deletions. https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings """ #!/bin/python3 import math import os import random import re import sys # Complete the alternatingCharacters function below. def alternatingCharacters(s): l = len(set(s)) if l == 1: return (len(s)-1) s_list = list(s) i, count = 0, 0 while i != len(s_list)-1: if s_list[i] == s_list[i+1]: s_list.remove(s_list[i]) count += 1 else: i += 1 return(count) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input()) for q_itr in range(q): s = input() result = alternatingCharacters(s) fptr.write(str(result) + '\n') fptr.close()
true
bbb2aa394383ae52f42b842cdd19ab2d1cf46b30
eloghin/Python-courses
/PythonZTM/100 Python exercises/22. Day08-word-frequency-calculator.py
436
4.1875
4
""" Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. """ string = 'New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.' words = string.split() word_count = {} for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 for k,v in word_count.items(): print(f'{k}:{v}')
true
cfea624a44abf9270a0c69817d417779a2d91973
eloghin/Python-courses
/ThinkPython/12.5.CompareTuples.py
816
4.25
4
""" Play hangman in max 10 steps """ """ Exercise 2 In this example, ties are broken by comparing words, so words with the same length appear in reverse alphabetical order. For other applications you might want to break ties at random. Modify this example so that words with the same length appear in random order. Hint: see the random function in the random module. Solution: http://thinkpython.com/code/unstable_sort.py. """ from random import random def sort_by_length(words): t = [] for word in words: t.append((len(word), random(), word)) t.sort(reverse=True) res = [] for length, rand, word in t: res.append(word) return res words = ['elena', 'aron', 'amurg', 'ana', 'andrei', 'ioana', 'iarina', 'vicky', 'nora', 'ina', 'iris'] print(sort_by_length(words))
true
a974ff163d113eebcc41271208d3610d7f00fd76
eloghin/Python-courses
/PythonZTM/100 Python exercises/39.Day11-filter-print-tuple.py
509
4.1875
4
""" Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10). """ def create_tuple(t): t2 = tuple((i for i in t if i%2==1)) print(t2) create_tuple((1,2,3,4,5,6,7,8,9)) ******* SOL 2 ******* tpl = (1,2,3,4,5,6,7,8,9,10) tpl1 = tuple(filter(lambda x : x%2==0,tpl)) # Lambda function returns True if found even element. # Filter removes data for which function returns False print(tpl1)
true
10166a92e26316e1182a17528bfa73e88f4364e4
eloghin/Python-courses
/LeetCode/contains_duplicate.py
703
4.1875
4
# Given an array of integers that is already sorted in ascending order, find two numbers such that # they add up to a specific target number. # 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. """"" SOL 1 """"" dict_duplicates = {} for item in nums: if item in dict_duplicates: return True else: dict_duplicates[item] = 1 return False """"" SOL 2 """"" # num = list(set(nums)) #To remove duplicates # if len(num) == len(nums): # return False # return True
true
3ac0db2e66847721aad13697fad5ec3bc54353fb
eloghin/Python-courses
/HackerRank/string_Ceasar_cipher.py
1,605
4.59375
5
"""Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c. Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated +3: defghijklmnopqrstuvwxyzabc Function Description Complete the caesarCipher function in the editor below. caesarCipher has the following parameter(s): string s: cleartext int k: the alphabet rotation factor Returns string: the encrypted string Input Format The first line contains the integer, n, the length of the unencrypted string. The second line contains the unencrypted string, s. The third line contains k, the number of letters to rotate the alphabet by. Sample Input 11 middle-Outz 2 Sample Output okffng-Qwvb """ import math import os import random import re import sys # Complete the caesarCipher function below. def caesarCipher(s, k): result = '' for char in s: if 65 <= ord(char) <= 90: result += chr((ord(char) -65 + k)%26 + 65) elif 97 <= ord(char) <= 122: result += chr((ord(char) -97 + k)%26 + 97) else: result += char return result if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() k = int(input()) result = caesarCipher(s, k) fptr.write(result + '\n') fptr.close()
true
c8a7f351613de02685ee86346e6ee5ad75f01835
eloghin/Python-courses
/ThinkPython/12.4.SumAll.py
443
4.46875
4
""" Play hangman in max 10 steps """ """ Exercise 1 Many of the built-in functions use variable-length argument tuples. For example, max and min can take any number of arguments: >>> max(1,2,3) 3 But sum does not. >>> sum(1,2,3) TypeError: sum expected at most 2 arguments, got 3 Write a function called sumall that takes any number of arguments and returns their sum. """ def sumall(*args): return sum(args) print(sumall(1,2,4,5))
true
e6421c4d66bdc42d0ea5dd1c1906c0d7e7f97f43
LucLeysen/python
/pluralsight_getting_started/loops.py
255
4.15625
4
student_names = ['Jeff', 'Jessica', 'Louis'] for name in student_names: print(name) x = 0 for index in range(10): x += 10 print(f'The value of x is {x}') x = 0 for index in range(5, 10, 2): x += 10 print(f'The value of x is {x}')
true
ac20bc5e55fe2193c57ffc1f724ad2d9a10aadc9
yxpku/anand-python
/chapter2/pro31-map.py
292
4.1875
4
# Python provides a built-in function map that applies a function to each element of a list. Provide an implementation for map using list comprehensions. def square(num): return num*num print square(2) def map(function,list): print [function(x) for x in list] print map(square,[1,2,3,4,5])
true
167d3db677427717e3002141037727da46947493
MischaBurgess/cp1404practicals
/Prac_05/state_names.py
1,016
4.125
4
""" CP1404/CP5632 Practical State names in a dictionary File needs reformatting Mischa Burgess """ # TODO: Reformat this file so the dictionary code follows PEP 8 convention CODE_TO_NAME = {"QLD": "Queensland", "NSW": "New South Wales", "NT": "Northern Territory", "WA": "Western Australia", "ACT": "Australian Capital Territory", "VIC": "Victoria", "TAS": "Tasmania"} print(CODE_TO_NAME) state_code = input("Enter short state: ") while state_code != "": # while state code is not empty state_code = state_code.upper() # changes user input into uppercase if state_code in CODE_TO_NAME: # if code matches, then.. print(state_code, "is", CODE_TO_NAME[state_code]) # print description else: print("Invalid short state") state_code = input("Enter short state: ") """Part two""" print("*Part Two: print list of states*") for key, val in CODE_TO_NAME.items(): # for both key and values in dictionary print("{:3} is {:8}".format(key, val)) # print with correct spacing
true
6b33c6e9dc6d599f687331aa9934b329f91814e0
MischaBurgess/cp1404practicals
/Prac_09/sort_files_2.py
1,617
4.15625
4
"""sort files in FilesToSort, version 2""" import os import shutil FOLDER_TO_SORT = 'FilesToSort' def main(): os.chdir(FOLDER_TO_SORT) files_to_sort = get_files_to_sort() extensions = get_extensions(files_to_sort) get_categories(extensions, files_to_sort) def get_files_to_sort(): """Gets a list of the files in the current directory.""" try: files_to_sort = [f for f in os.listdir('.') if os.path.isfile(f)] # ignores folders except IsADirectoryError: print("Directory error - Could not find {} in directory".format(FOLDER_TO_SORT)) return files_to_sort def get_extensions(files_to_sort): """Gets extensions from list of unsorted files.""" extensions = [] for file in files_to_sort: extension = file.split('.')[-1] if extension not in extensions: extensions.append(extension) else: pass return extensions def get_categories(extensions, files_to_sort): """Asks the user how to organise files.""" for extension in extensions: category = input('What category would you like to sort {} files into? '.format(extension)) try: os.mkdir(category) except FileExistsError: pass rearrange_files(files_to_sort, category, extension) def rearrange_files(files_to_sort, category, extension): """Uses shutil module to rearrange files into their corresponding folder.""" for file in files_to_sort: current_extension = file.split('.')[-1] if current_extension == extension: shutil.move(file, category) main()
true
82a835c4a7ef3ff39ab91815f5da8d7eb0652ba9
harofax/kth-lab
/bonus/övn-2/övn-2-krysstal.py
1,838
4.46875
4
# exercise 1 def rectangle_area(height, width): """ :param height: height of rectangle :param width: width of rectangle :return: area of a rectangle with the specified width and height """ assert isinstance(width, int) or isinstance(width, float), "Width has to be a number!" assert isinstance(height, int) or isinstance(height, float), "Height has to be a number!" assert (not isinstance(width, bool)) and (not isinstance(height, bool)), "Width/height can't be a boolean" return height*width # exercise 2 def rectangle_circumference(height, width): """ :param height: height of rectangle :param width: width of rectangle :return: circumference of a rectangle with the specified width and height """ assert isinstance(width, int) or isinstance(width, float), "Width has to be a number!" assert isinstance(height, int) or isinstance(height, float), "Height has to be a number!" assert (not isinstance(width, bool)) and (not isinstance(height, bool)), "Width/height can't be a boolean" # Since the sides are parallel, we multiply the height and width by two and add them together. return height * 2 + width * 2 # exercise 3 def third_character_of_string(string): """ :param string: string to get the third character of :return: the third character of the given string """ if len(string) < 3: return False else: # Since indexing starts at 0, the third character will have the index 2 return string[2] def main(): # Making sure that the functions return the proper results assert third_character_of_string("abcdef") == "c" assert third_character_of_string("hi") is False assert rectangle_area(2, 5) == 10 assert rectangle_circumference(2, 6) == 16 if __name__ == "__main__": main()
true
c02807420cb24aa6153d051f927e70d79e42aa61
pasqualc/Python-Examples
/rotatearray.py
450
4.4375
4
# This program will take an array and a size of rotation as input. The Output # will be that array "rotated" by the specified amount. For example, if the Input # is [1, 2, 3, 4, 5] and size of rotation is 2, output is [3, 4, 5, 1, 2] while 1: array = input("Array: ") list = array.split() size = int(input("Size of rotation: ")) print(list) for i in range(0, size): list.append(list.pop(0)) print(list) print("")
true
d53a41cff07f6ebbf0d2c890c6b984b5c3075dce
gladiatorlearns/DatacampExercises
/Adhoc/Packages.py
431
4.125
4
# Definition of radius r = 0.43 # Import the math package import math # Calculate C C = 2*math.pi*r # Calculate A A = math.pi*r**2 # Build printout print("Circumference: " + str(C)) print("Area: " + str(A)) # Definition of radius r = 192500 # Import radians function of math package from math import radians # Travel distance of Moon over 12 degrees. Store in dist. phi=radians(12) dist=r*phi # Print out dist print(dist)
true
3f66c64d2cae9031fc7b0c9e326f8c8b1f2150e8
Dipson7/LabExercise
/Lab3/question_no_7.py
367
4.34375
4
''' WAP that accepts string and calculate the number of upper case and lower case letters. ''' def UPPERLOWER(sentence): u = 0 l = 0 for i in sentence: if i >= 'A' and i <= 'Z': u += 1 elif i >= 'a' and i <= 'z': l += 1 print(f"Uppercase: " + str(u)) print(f"Lowercase: " + str(l)) UPPERLOWER(sentence)
true
b8e5d8bc58770e0550a59f79acd8aa5ac5881416
Dipson7/LabExercise
/Lab3/question_no_2.py
485
4.28125
4
''' WAP called fizz_buzz that takes that takes a number. If it is divisible by 3, it should return fizz. If it is divisible by 5 return buzz. It it is divisible by both return fizzbuzz. Otherwise it should return the same number. ''' def div(): a = int(input("Enter any number: ")) if a/5 == a//5 and a/3 == a//3: print(f'fizzbuzz') elif a/3 == a//3: print(f'fizz') elif a/5 == a//5: print(f'buzz') else: print(a) div()
true
5942e08cc117c38fbd2a4d7390f250f5d051b0bb
Barabasha/pythone_barabah_hw
/test11.py
949
4.125
4
#В двумерном массиве отсортировать четные столбцы по возрастанию, а нечетные - по убыванию def random_table(table): import random for idx1 in range(line): for idx2 in range(column): table[idx1][idx2] = random.randint(1,100) return table def print_table(table): for line in table: for elem in line: print(elem, end="\t") print() return def my_sort (table): for i in range(column): s = [] for j in range(line): s.append(table[j][i]) if i%2 == 0: s.sort(reverse=True) else: s.sort() for j in range(line): table[j][i] = s[j] return table line = 3 column = 8 lst = [[0]*column for i in range(line)] random_table(lst) print_table(lst) print() my_sort(lst) print_table(lst)
false
a86cebe421426649f4850db1f33bde0d85a11bdf
skye92/interest_cal
/InterestCal_v.2.py
1,455
4.34375
4
def account_balance():# def function/ what is function name, how many params. starting_balance = float(input("what is the starting balance? ")) # ask user for input for starting_balance stock_cost = float(input("how much does the stock cost? "))# ask user how much the stock cost stock_owned = starting_balance / stock_cost # how many of the stock is owned dividend_amount = float(input("how much is the dividend")) #How much is the dividend dividend_payment = stock_owned * dividend_amount # how much is the dividend payment new_balance = starting_balance + dividend_payment # what is the new balance of the starting balance and the dividend payment #print(new_balance) # print new balance #create list that adds new_balance to it. # define nested function def interest_cal(new_balance): count = 0 how_many = int(input("How many units of time? ")) balance_list = [new_balance] while(count <= how_many): comp_interst = new_balance + dividend_payment # new balance + dividend payment is = to ? count = count + 1 for i in range(len(balance_list)): i = balance_list.append(i + comp_interst) print(balance_list[-1]) # how many times to add the new balance to dividend payment # print results of new balance + dividend payment * how many times interest_cal(new_balance) account_balance()
true
c9d4210f3e39ee89cc3cb7816caf920e22f32513
kalyansikdar/ctci-trees
/check_subtree.py
1,195
4.1875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Algorithm: # 1. If the structure matches with the root, return true. # 2. Else check if it's a subtree of left subtree or right # Note: While checking structure the subtrees of two inputs should match exactly. class Solution(object): def checkStructure(self, root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val == root2.val: # so that the trees match exactly, even the childrens should be exactly same. return self.checkStructure(root1.left, root2.left) and self.checkStructure(root1.right, root2.right) else: return False def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ if s: if self.checkStructure(s, t): return True else: return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) else: return False
true
1e6e5bde622e94e827a67ea13badc76d9059ee61
LenaTsepilova/Course_python_2021
/lesson_hm_1.py
2,720
4.21875
4
"""Урок 1. Задание 2""" # Пользователь вводит время в секундах. # Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. # n = int(input("введите время в секундах: \n")) # # print(1, 2, 3, sep=":") # # print(str(n // 3600) + ":" + str(n % 3600 // 60) + ":" + str(n % 60)) # h = n // 3600 # m = n % 3600 // 60 # s = n % 60 # print('{:02d}:{:02d}:{:02d}'.format(h, m, s)) """Урок 1. Задание 3""" # Узнайте у пользователя число n. # Найдите сумму чисел n + nn + nnn. Например, пользователь ввёл число 3. # Считаем 3 + 33 + 333 = 369. # n = input("введите целое число:") # print(int(n) + int(n * 2) + int(n * 3)) """Урок 1. Задание 4""" # Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. # n = int(input("введите число: ")) # max_number = 0 # while n > 0: # if n % 10 > max_number: # max_number = n % 10 # n = n // 10 # print(max_number) """Урок 1. Задание 5""" # Запросите у пользователя значения выручки и издержек фирмы. # Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или # убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью, # вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите численность сотрудников # фирмы и определите прибыль фирмы в расчете на одного сотрудника. # v = int(input("введите выручку:")) # i = int(input("введите издержки:")) # if v > i: # print("прибыль") # r = (v - i) / v # print("Рентабельность равна:", r) # p = int(input("введите количество сотрудников: ")) # print((v - i) / p, "прибыль фирмы в расчете на одного сотрудника") # else: # print("убыток")
false
c47a4043bdf87c41ac6081184473778996b750c4
vigjo/mdst_tutorials
/tutorial1/python_exercises.py
1,247
4.21875
4
""" Intro to python exercises shell code """ from collections import Counter def is_odd(x): if x % 2 != 0: return false return true """ returns True if x is odd and False otherwise """ def reverse(s): str = "" for i in s: str = i + str return str def is_palindrome(word): if word == word.reverse: return true return false """ returns whether `word` is spelled the same forwards and backwards """ def only_odds(numlist): """ returns a list of numbers that are odd from numlist ex: only_odds([1, 2, 3, 4, 5, 6]) -> [1, 3, 5] """ odds = [] for x in numlist: if is_odd x: odds.append(x) return odds def count_words(text): """ return a dictionary of {word: count} in the text words should be split by spaces (and nothing else) words should be converted to all lowercase ex: count_words("How much wood would a woodchuck chuck" " if a woodchuck could chuck wood?") -> {'how': 1, 'much': 1, 'wood': 1, 'would': 1, 'a': 2, 'woodchuck': 2, 'chuck': 2, 'if': 1, 'could': 1, 'wood?': 1} """ text = text.lower() words = text.split(' ') cnt = Counter() for word in text: cnt[word] += 1 return cnt
true
671b9b5777df9c755c8ee396c3cd7c21e187e7e5
olliepotter/Python_Scripts
/Python_Scripts/Coursework_1/fibonacci.py
1,297
4.78125
5
""" This file contains various functions to compute a given number of fibonacci terms """ def fibonacci(number, next_value=1, prev_value=0): """ Calculates the 'nth' number in the fibonacci sequence :param number: The 'nth' term in the fibonacci sequence to be returned :param next_value: The next value in the sequence :param prev_value: The previous value in the sequence :return: Decrement of the number, the new value calculated, the now previous value """ if number == 0: return prev_value if number == 1: return next_value return fibonacci(number - 1, next_value + prev_value, next_value) # Function is recursive def fibonacci_sequence(n): """ Returns a list containing each number in the fibonacci sequence up to 'n' terms :param n: The amount of items to be returned :return: A list of fibonacci numbers , size n """ sequence = [] for i in range(n): # Loop through n times to make a list of size n populated with terms from fibonacci sequence sequence.append(fibonacci(i)) return sequence if __name__ == '__main__': # Main part of the program output_list = fibonacci_sequence(20) for i in range(len(output_list)): # Format output nicely print(output_list[i])
true
66104e9f2bdb1175ad28f4ef81f1835eb449138d
FerruccioSisti/LearnPython3
/Conditionals Examples/ex36.py
1,668
4.25
4
#This exercise is basically the previous one, except it is meant to be short and entirely on our own from sys import exit #red room option from starting room def redRoom(): print("Everything in this room is red. You can't see any objects other than the outline of the door.") print("Do you try and go out the door ?") choice = input ("> ") if choice == "yes": print("you trip over some red spikes and die\nNice") exit() elif choice == "no": print("you don't move out of fear and starve to death\nNice") exit() else: print("idk what that means bro") redRoom() #blue room option from starting room def blueRoom(): print("Everything in this room is blue. You can't see any objects other than the outline of the door.") print("Do you try and go out the door ?") choice = input("> ") if choice == "yes": print("the door leads outside\nNice") exit() elif choice == "no": print("you didn't notice the room filling up with water and drowned\nNice") exit() else: print("idk what that means bro") blueRoom() #starting room def startRoom(): print("You awake sleeping on a couch in a bizarre room\nThere are two coloured doors on the opposite side of the room") print("Do you take the blue door or the red door ?") choice = input("> ") if choice == "blue": print("You choose the blue door") blueRoom() elif choice == "red": print("You choose the red door") redRoom() else: print("idk what that means bro\nYou gotta say red or blue") startRoom() startRoom()
true
b331aff61366b16861907d9466bd1c26e9945f66
FerruccioSisti/LearnPython3
/Tests/ex24.py
1,308
4.4375
4
#This is a longer exercise where we practice everything from the previous 23 examples print("Lets practice everything.") print('You\'d need to know \'bout escapes with \\ that do: ') print('\n newlines and \t tabs') poem = """\t the lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\twhere there is none.""" print(f"---------------\n{poem}\n---------------") five = 10 - 2 + 3 - 6 print(f"This should be five: {five}") #Functions can return multiple variables in python def secretFormula(started): jellyBeans = started * 500 jars = jellyBeans / 1000 crates = jars / 100 return jellyBeans, jars, crates startPoint = 10000 #You can assign multiple variables if your function returns multiple variables beans, jars, crates = secretFormula(startPoint) print("With a starting point of: {}".format(startPoint)) print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.") startPoint = startPoint / 10 print("We can also do it this way: ") #This makes a list of strings formula = secretFormula(startPoint) #This iterates through the list and assigns each {} to an index of the list, with the first {} being index 0 print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
true
ead6245978ad7c23674e14b472457eeafa099330
franckess/Python-for-Everybody-Coursera-
/Python Data Structures/Scripts/Assignment_84.py
859
4.5
4
## Assignment 8.4 # Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. # The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. # When the program completes, sort and print the resulting words in alphabetical order. fname = raw_input("Enter file name: ") path = 'E:/Coursera/Python-for-Everybody-Coursera/Python Data Structures/' filename = path + fname try: fh = open(fname) except: print 'The following file doesn''t exist:',fname exit() lst = list() for line in fh: newline = line.split() m = len(newline) len_range = range(m) for i in len_range: value = newline[i] if value not in lst: lst.append(value) lst.sort() print lst
true
df64b21d85348ac280397effe3d8cd576a73f52d
Rutujapatil369/python
/Assignment1_2.py
621
4.21875
4
# Write a program which contains one function named as ChkNum() which accept one parameter as number. #If number is even then it should display “Even number” otherwise display “Odd number” on console. #Input : 11 Output : Odd Number #Input : 8 Output : Even Number def ChkNum(No): if(No%2==0): return True; else: return False; def main(): print("Enter number") value=int(input()) num=ChkNum(value) if(num==True): print("Even Number") else: print("Odd Number") if __name__=="__main__": main()
true
52753b372d177b9eb2f423cbe7270cb561f18bfe
prathimacode-hub/Python-Tutorial
/Beginner_Level/Closure + Nested Function/anotherclosureexample.py
552
4.25
4
def nth_power(exponent ): def pow_of(base): return pow(base, exponent) return pow_of # note that we are returning function without function square = nth_power(2) print(square(31)) print(square(32)) print(square(33)) print(square(34)) print(square(35)) print(square(36)) print(square(37)) print(square(38)) print(square(39)) print('------') cube = nth_power(3) print(cube(2)) print(cube(3)) print(cube(4)) print(cube(5)) print(cube(6)) print(cube(7)) print(cube(8)) print(cube(9))
false
9aa7e369bcbe68fef446bc4e64242c37df29eb0e
d2015196/PythonTutorial-
/Boolean.py
600
4.15625
4
favoritefood = "Hotdogs" favoritelanguage = "Python (Yuzzz!)" favoritecountry = "Deutschland" stuff = [] stuff.append(favoritecountry) stuff.append(favoritelanguage) if favoritecountry == "Deutschland" or favoritecountry == "Mexico": print ("You are correct ") if favoritelanguage in stuff: print("Cool bro") if favoritecountry == "Deutschland": print("Cool story, die Deutsche sind immer toll ") elif favoritefood == "Hotdogs": print("Sie sind nicht so gut fur sie, aber ja hotdogs sind lecker") else: print("Du bist nicht interessant, tut mir leid") print(not False == False)
false
38360af0cefbce3fea4b9e03931bdee92fd822aa
ZTMowrer947/python-number-guess
/guessing_game.py
2,284
4.40625
4
""" Python Web Development Techdegree Project 1 - Number Guessing Game ----------------------------------------------------------------------- This project implements a simple version of the number guessing game. The user is prompted to guess a random number between 1 and 10, and does so until they guess correctly. At the end, they see how many guesses they took to guess the random number. """ import random def play_game(): """This function runs the entire game: the user is asked to guess a random number between 1 and 10 repeatedly until they guess correctly, with feedback being shown after each incorrect guess to narrow their future guesses. Once they guess correctly, the number of total guesses is displayed and the game ends. Returns the number of guesses it took the user to guess the random number. """ random_number = random.randint(1, 10) guess_counter = 1 while True: guess = input("\nPick a number between 1 and 10: ") try: guess = int(guess) except ValueError: print( "Sorry, that isn't a valid guess. Your guess must be a number between 1 and 10.") continue if guess not in range(1, 11): print("Sorry, {} is outside the valid range. Your guess must be a number between 1 and 10.".format(guess)) continue elif guess == random_number: print("You got it! The number was {}!".format(random_number)) print("It took you {} guess(es) to get it.".format(guess_counter)) break elif guess > random_number: print("{} is too high. Guess lower!".format(guess)) else: print("{} is too low. Guess higher!".format(guess)) guess_counter += 1 return guess_counter high_score = 0 print("Welcome to the Number guessing game!") while True: game_score = play_game() should_replay = input("\nWould you like to play again? (yes/no) ") if should_replay.lower() == "yes": if game_score < high_score or high_score == 0: high_score = game_score print("\nThe current high score is {}".format(high_score)) continue else: print("\nThank you for playing!") break
true
e249538c94d2b2c6d8a3dfece71adb4be5d187f4
SamuelLeeuw/mypackage
/mypackage/sorting.py
1,052
4.28125
4
def bubble_sort(items): '''Return array of items, sorted in ascending order''' for passnum in range(len(items)-1,0,-1): for i in range(passnum): if items[i]>items[i+1]: temp = items[i] items[i] = items[i+1] items[i+1] = temp return items def merge(l, r): """Merge sort merging function.""" left_index, right_index = 0, 0 result = [] while left_index < len(l) and right_index < len(r): if l[left_index] < r[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(r[right_index]) right_index += 1 result += l[left_index:] result += r[right_index:] return result def merge_sort(items): '''Return array of items, sorted in ascending order''' if len(items) <= 1: return items half = len(items) // 2 l = merge_sort(items[:half]) r = merge_sort(items[half:]) return merge(l, r)
true
fd06d649f3cb966c9f5b6d0b34195f778de695bc
CAMOPKAH/BA
/LearnPython/Lesson5/task2.py
776
4.25
4
""" 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке. """ f_read = open ("test_words.txt", "r") word_count = 0 line_count = 0; for line in f_read: line_count = line_count + 1 str = " " + line.replace("\n", "") + " " #Обрамляем в пробелами и удаляем перевод каретки while str.count(" ") > 0: #Удаляем двойные пробелы str = str.replace(" ", " ") word_count = word_count + str.count(" ") -1 print(F"Кол-во строк: {line_count}\n Кол-во слов: {word_count}")
false
57174e710e1cd8d871ce605f4dd7bf5d8f8a21d8
deepakdas777/think-python-solutions
/Classes-and-functions/16.1.py
476
4.375
4
#Exercise 16.1. Write a function called print_time that takes a Time object and prints it in the form hour:minute:second . Hint: the format sequence '%.2d' prints an integer using at least two digits, including a leading zero if necessary. class time: hour=0 minut=0 second=0 def print_time(t): print('The time is %2d:%2d:%2d' %(t.hour,t.minut,t.second)) def main(): t=time() t.hour=5 t.minut=25 t.second=23 print_time(t) if __name__=='__main__': main()
true
48723d15b68caa2942c2add79890be28816fa6ea
amudwari/hangman
/game.py
1,191
4.1875
4
import random def get_random_word(): small_file = open("small.txt", "r") words = small_file.readlines() random_word = random.choice(words) print(random_word) return random_word def start_game(): print(''' You'll get 3 tries to guess the word. Lets START...''') random_word = get_random_word() length = len(random_word) - 1 #print(length) for i in range(length): dash = "_ " print(dash, end = '') for j in range(3): user_input = input("\n" + "Enter a letter: ") for c in range(0, length): if random_word[c] == user_input: print(user_input, end="") else: print(" _ ", end="") if user_input in random_word: index_word = random_word.index(user_input) print(index_word) # user_input = input("\n" + "Enter a letter: ") def menu(): print('''Welcome to Hangman! Please choose one of the following: 1.Start Game 2.Exit ''') choice = int(input("Please enter 1 or 2: ")) if choice == 1: start_game() else: exit() get_random_word() menu()
true
b0dfd9e4aed10b3cfc9f6931290c485e1f566482
slubana/GuessTheNumber
/guessmynumber.py
1,057
4.125
4
import math import random import time print("Welcome to the Guess the Number Game! \nThe goal of the game is to guess the number I am thinking!") choice = input("Do you want to play? Enter 'No' to quit and 'Yes' to play!") if choice=="No": print("Ok! Have a good day!") exit() else: print("You have chosen to play!\nThink of a number between 0 and 100!") totalguesses = 0 number = random.randrange(0, 101, 2) guess = -1 while (guess != number): while True: try: guess = int(input("Enter your guess!")) break except: print("That's not a valid number!") if(guess > number): print("Hey! The number I am thinking is lower than that!!!") totalguesses = totalguesses + 1 elif(guess < number): print("Hey! The number I am thinking of is high than that!!") totalguesses = totalguesses + 1 if (totalguesses == 1): print("How in the world did you do that huh?") else: print("Only took you {} guesses to guess the number!".format(totalguesses))
true
21ef5a2af4468d11bf7b1cf85f5cc861f486a912
Krushnarajsinh/MyPrograms
/InnerClass.py
1,237
4.6875
5
#class inside a antother class is called as inner class class Student: class_name="A" #Inner class can access class variable but not instance variable of outer class def __init__(self,no,name): self.no=no self.name=name self.lap=self.Laptop("HP","i8") def show(self): print(self.name,"Has Roll Number {}".format(self.no)) self.lap.show() class Laptop: def __init__(self,lap_name,cpu_name): self.lap_name=lap_name self.cpu_name=cpu_name def show(self): print("{} Laptop which cpu version is {}".format(self.lap_name,self.cpu_name)) s1=Student(1,"karan") s2=Student(2,"hitesh") s1.show() s2.show() #We can create object of inner class in two way #(1) create inner class object inside the outer class into init() method and (2)create inner class object outside the outer class #(2) lap1=Student.Laptop("HP","i5") lap2=Student.Laptop("Dell","i7") #this will create two different object for inner class lap3=s1.lap lap4=s2.lap print(id(lap3)) print(id(lap4)) #lap3=s1.lap.show() this can be used when we create inner calss object inside the outer class lap is object created inside init() of outer class #OR lap1.show() lap2.show()
true
78a7a815b07f7d0e38d74d6958e94bb35d0cbec7
Krushnarajsinh/MyPrograms
/OneTryBlockWithManyExceptBlock.py
1,031
4.28125
4
#suppose i perform some operation with database and i need to open a connection to connect the detabase #when our task is over then we must close that connection #fa=int(input("Enter the number A:")) a=int(input("Enter the number A:")) b=int(input("Enter the number B:")) try: print("open connection") a=int(input("Enter a number:")) print(a) print("Division ofthis both number is:", a / b) #print("close connection") except ValueError as e: print("Exception:",e) except ZeroDivisionError as e: print("Exception:", e) except Exception as e: print("Exception:", e) #print("close connection") finally: print("close connection") #finally is a block which provide guarintee to exexute the statement that written inside in it #Even exception occures or not #hence we need to perform a task that is important to execute even exception occures or not then we can put that statement inside a finally block #in try block if some error occures then the statements after that error are not executes
true
81a9ace06a898dce5d7ad77592e79ba2ae394cc5
Krushnarajsinh/MyPrograms
/ConstructorINInheritance.py
953
4.25
4
class A: def __init__(self,a): print("This is A class Constructor","value is:",a) def display1(self): print("This is display1 method") class B(A): def __init__(self,a): super().__init__(5) print("This is B class Constructor","value is:",a) def display2(self): print("This is display2 method") def show(self): print("Fetching method of A using Super") super().display1() b1=B(10) b1.show() b1.display2() #the moment you create the object of B then compiler first check if there is init() inside B class if it is not then it will check for init() of A and execute it #But when both A and B class Have Init() method then only init() of B class Is Executed #therefor to execute init() of A also we need to use one keyword or function which is called as super() #when you use super() it represent super class A #by using super() we can access init() as well as all the methods of A
true
ee198677e75c5bdac38a13c76c34c9de2ab7ad7e
Krushnarajsinh/MyPrograms
/ListAsArgumentInFunction.py
462
4.21875
4
def odd_even(list): even=0 odd=0 for i in list: if i%2==0: even+=1 else: odd+=1 return even,odd list=[] num=int(input("Howmay values you want to enter in the list:")) i=1 while i<=num: x=int(input("Enter the {}th value in list:".format(i))) list.append(x) i+=1 print(list) even,odd=odd_even(list) print("There are {} even values in list and There are {} odd values in list".format(even,odd))
true
6e07b9cbfa479441ad03df261c47822ec6159ef4
Krushnarajsinh/MyPrograms
/GeneratorDemo.py
1,183
4.53125
5
#In iterator we need to face some issues like we need to define to functions iter() and next() #hence instead of using iterator we can use Generator #lat's do that def toptan(): yield 5 #yield is the keyword that make your method as generator now this is not normal method it is Generator #yield also similar to the return keyword but yield returns the value in the form of iterator #So, python Give us a Generator that gives iterator yield 6 yield 8 yield 9 yield 10 list=[1,2,3,4,5,6,7] yield list val=toptan() print(val) #here address of generator is print #TO print the value we can use next() method #print(val.__next__()) #print(val.__next__()) #print(val.__next__()) #we can also use for loop and remember that for loop is (inderictly An iterator) for i in val: print(i) #why we need Generator ? #Ans:-Suppose you want to fetch some data from your database and data may contain 10000 of values #If you fetch or perform operations on these all value at same time then it will load in your memory #but we don't want that #so we can simply fetch one value at a time and perform some operation on it or print that value using Generator
true
9b1e3c9bf8b357f38518a1c44032fc5a4780a0ca
suchismitapadhy/AlgoPractice
/zero_matrix.py
528
4.125
4
def zero_matrix(arr): zero_i = set() zero_j = set() # find index(i,j) for zero valued elements for i in range(len(arr)): for j in range(len(arr[i])): if arr[i][j]==0: zero_i.add(i) zero_j.add(j) # traverse the matrix to set rows and cols to zero for i in range(len(arr)): for j in range(len(arr[i])): if i in zero_i or j in zero_j: arr[i][j]=0 return arr print(zero_matrix([[1,2,3],[4,0,6],[7,8,9],[10,11,12]]))
false
0f4b63cdb1224d2c5c86a2e75dcd9b8db925c5c9
Edrasen/A_Algoritmos
/Divide&Conquer2_QuickSort/quickLast.py
1,406
4.375
4
#Practica 4 #Ramos Mesas Edgar Alain #quicksort by pivot at last element #By printing every iteraction with partition function we will be able to see #how many iterations there are on the algorithm, in this case it takes only 6 iterations. contador = 0 comparaciones = 0 def partition(arr,low,high): global contador global comparaciones comparaciones +=1 print(arr) i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot for j in range(low , high): # If current element is smaller than the pivot if arr[j] < pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] contador +=1 arr[i+1],arr[high] = arr[high],arr[i+1] contador +=1 return ( i+1 ) # Function to do Quick sort def quickSort(arr,low,high): if low < high: # part is partitioning index, arr[p] is now # at right place part = partition(arr,low,high) # Separately sort elements before # partition and after partition quickSort(arr, low, part-1) quickSort(arr, part+1, high) #Test code arr = [10,7,8,9,1,5,5] n = len(arr) quickSort(arr,0,n-1) print("Sorted array is:") print(arr) print(" Swaps: ", contador) print(" Comparaciones: ", comparaciones)
true
22bf6c6cd2472d712e0749844c8041f11213deec
headHUB/morTimmy
/raspberrypi/morTimmy/bluetooth_remote_control.py
2,281
4.125
4
#!/usr/bin/env python3 import remote_control # Controller driver and command classes import pybluez # Bluetooth python libary class RemoteController(ControllerDriver): """ Remote control morTimmy the Robot using bluetooth This class will be used to control the Raspberry Pi using external remote controls like a game controller or bluetooth phone application """ command = ControllerCmd() def __init__(self): """ Setup the bluetooth connection """ def recvCommand(self): """ This receives a command from the controller """ return class ControllerCmd: """ Command definition for controller drivers This class defines the various commands our robot morTimmy can respond to. It's used by both the arduino/raspberry pi interface and remote control devices interfacing with the Raspberry Pi. """ leftMotorSpeed = 0 # Controls the speed of the left side motors rightMotorSpeed = 0 # Controls the speed of the right side motors def goForward(speed): leftMotorSpeed = speed rightMotorSpeed = speed def goBack(speed): leftMotorSpeed = -speed rightMotorSpeed = -speed def goLeft(speed): leftMotorSpeed = -speed rightMotorSpeed = speed def goRight(speed): leftMotorSpeed = speed rightMotorSpeed = -speed def stop(): leftMotorSpeed = 0 rightMotorSpeed = 0 def joystick(x, y): """ Controlling the robot using a joystick Args: x (int): x-axis of the joystick, controls the amount of steering y (int): y-axis if the joystick, controls the forward/back speed """ leftMotorSpeed = x - y rightMotorSpeed = x + y # Make sure the remote control x and y values # do not exceed the maximum speed if leftMotorSpeed < -255: leftMotorSpeed = -255 elif leftMotorSpeed > 255: leftMotorSpeed = 255 if (rightMotorSpeed < -255): rightMotorSpeed = -255 elif rightMotorSpeed > 255: rightMotorSpeed = 255 def main(): pass if __name__ == '__main__': main()
true
bad07650cf04085300eb252fccbbec7c345587f3
impiyush83/expert-python
/decorators.py
1,751
4.21875
4
# DECORATORS WITH ARGUMENTS : def trace(func): def wrapper(*args, **kwargs): print(f'TRACE: calling {func.__name__}() ' f'with {args}, {kwargs}') original_result = func(*args, **kwargs) print(f'TRACE: {func.__name__}() ' f'returned {original_result!r}') return original_result return wrapper @trace def say(name, line): return f'{name}: {line}' print(say("piyush", "nalawade")) """This makes debugging and working with the Python interpreter awkward and challenging. Thankfully there’s a quick fix for this: the functools.wraps decorator included in Python’s standard library. You can use functools.wraps in your own decorators to copy over the lost metadata from the undecorated function to the decorator closure. """ import functools def uppercase(func): @functools.wraps(func) def wrapper(): return func().upper() return wrapper def italics(func): @functools.wraps(func) def wrapper(): print(func()) return "<i>" + func().lower() + "</i>" return wrapper @italics @uppercase def greet(): """Return a friendly greeting.""" return 'Hello!' print(greet()) """ Python Decorators – Key Takeaways * Decorators define reusable building blocks you can apply to a callable to modify its behavior without permanently modifying the callable itself. * The @ syntax is just a shorthand for calling the decorator on an input function. Multiple decorators on a single function are applied bottom to top (decorator stacking). * As a debugging best practice, use the functools.wraps helper in your own decorators to carry over metadata from the undecorated callable to the decorated one. """
true
dedb545a4c77ff1d065cb5815b585737f6b3293a
gadepall/IIT-Hyderabad-Semester-Courses
/EE2350/Coding Assignment-1/2.1.1g.py
1,080
4.15625
4
# Code for Moving Average System import numpy as np import matplotlib.pyplot as plt n = int(input("No.of Elements in signal: ")) x = np.ones(n) time = np.arange(n) for i in range(n): # Generating the input x[i] = 0.95 ** i def Signal_Ideal_Delay(signal,d = 2): # Function to generate ideal delay in signal """ Now we get ideal delay in signal """ s = signal.shape[0] time = np.arange(+d,s+d) return signal,time def Moving_Average_System(signal,M = 10): # Function of Moving Average System using Ideal Delay System """ Moving Average System using Ideal Delay System. """ p,q,s = M,signal.shape[0]- M,signal.shape[0] signal_new = np.zeros(s+M) for i in range(M+1): signal_new[M-i:M-i+s] += Signal_Ideal_Delay(signal,d=i)[0] signal_new = signal_new/(M + 1) time = np.arange(0,s+M) return signal_new,time x_filtered,time_filtered = Moving_Average_System(x) plt.figure(figsize=(13, 8)) ax = plt.subplot(1, 2, 1) plt.stem(time,x,'r') ax = plt.subplot(1,2,2) plt.stem(time_filtered,x_filtered,'y') plt.show()
true
a2e5abd26ff8ebe066c20741ec54f14400942a59
uh-bee/Balakrishnan_Story
/addSix.py
203
4.40625
4
""" This program will take the input of the user and return that number plus 6 in a print statement """ x= float(int(input('please enter a number'))) print("the number" + x + "plus 6 is:" + str((x+6)))
true
d5546cf9190ec318bbb90a4af97b4f46d76e5a02
unites/code_library
/python/comparison.py
1,757
4.53125
5
# Python 3 code # check if list are equal # using set() & difference() # initializing list and convert into set object x = set(['x1','rr','x3','y4']) y = set(['x1','rr','rr','y4']) print ("List first: " + str(x)) print ("List second: " + str(y)) # take difference of two lists z = x.difference(y) print("Difference of first and second String: " + str(z)) # if lists are equal if not z: print("First and Second list are Equal") # if lists are not equal else: print("First and Second list are Not Equal") # For SET # Method Description # add() Adds an element to the set # clear() Removes all the elements from the set # copy() Returns a copy of the set # difference() Returns a set containing the difference between two or more sets # difference_update() Removes the items in this set that are also included in another, specified set # discard() Remove the specified item # intersection() Returns a set, that is the intersection of two other sets # intersection_update() Removes the items in this set that are not present in other, specified set(s) # isdisjoint() Returns whether two sets have a intersection or not # issubset() Returns whether another set contains this set or not # issuperset() Returns whether this set contains another set or not # pop() Removes an element from the set # remove() Removes the specified element # symmetric_difference() Returns a set with the symmetric differences of two sets # symmetric_difference_update() inserts the symmetric differences from this set and another # union() Return a set containing the union of sets # update() Update the set with the union of this set and others
true
c9a1ec2ce98f8d6940ec066f3354f97cb4407c7f
Yujunw/leetcode_python
/116_填充每个节点的下一个右侧节点.py
1,217
4.15625
4
''' 给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。 ''' # Definition for a Node. class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next class Solution: def connect(self, root): if not root.left and not root.right: return None root.left.next = root.right if root.left.right: root.left.right.next = root.right.left self.connect(root.left) self.connect(root.right) def connect_2(self, root): if not root: return None if root.left: root.left.next = root.right if root.next: root.right.next = root.next.left self.connect_2(root.left) self.connect_2(root.right) return root
false
8d27d8e9695d6316a6316194b04b792edfff183b
treelover28/Tkinter-Learning
/grid.py
644
4.59375
5
from tkinter import * # create root window root = Tk() # define Label widget on top of the Root widget label = Label(root, text="Hello World") label2 = Label(root, text="My name is Khai Lai") label3 = Label(root, text="---------------") # instead of automating the placement using .pack() # we can specify the position using tkinter's GRID system # one will be on top while the other is in the bottom. label.grid(row=0, column=0) # the grid system is relative # since there is nothing in column 2,3,4 # it just ignore our placement in column 5, # place it in 2 instead label2.grid(row=1, column=5) label3.grid(row=0, column=1) root.mainloop()
true
8506fa5f0f87247548f3398f4f4d0c288e1c9780
KseniaTrox/lesson_2
/5.1.py
574
4.28125
4
# Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.Об # окончании ввода данных свидетельствует пустая строка. f = open('grumbler.txt', 'w', encoding='utf-8') while True: s = input('введите строку:') if s == '': break # пустая строка f.write(s + '\n') f.close() f = open('grumbler.txt', 'r') content = f.read() print(content) f.close()
false
5b834fef771547925b2e9fdf7b37a8a2c54dd4ef
AmirQadir/MITx-6.00.1x
/Week2/Prob1.py
501
4.34375
4
balance = int(input("Enter the current balance:")) annualInterestRate = float(input("Enter the annualInterestRate")) monthlyPaymentRate = float(input("monthlyPaymentRate")) for i in range(12): mir = annualInterestRate / 12.0 # Monthly Interest Rate mmp = monthlyPaymentRate * balance # Minimum Monthly Payment mub = balance - mmp # Monthly unpaid balance ubem = mub + (mir * mub) # Updated balnace each month balance = ubem print("Remaining balance:", ("%.2f" % balance))
true
90043fe44b0ade6594e0b2fad7d79bd3a14033a9
pedrobrasileiro/Exercicios-Python-e-Django-3
/programa1.p3.py
626
4.125
4
#!/usr/bin/env python3 # encoding: utf-8 """ programa1.py Created by Pedro Brasileiro Cardoso Junior on 2010-12-28. Copyright (c) 2010 Particular. All rights reserved. Importa o módulo random e sorteia um número inteiro entre 1 e 100 """ import random numero = random.randint(1,100) escolha = 0 tentativas = 0 while escolha != numero: escolha = int(input("Escolha um número entro 1 a 100: ")) tentativas += 1 if escolha < numero: print("O número", escolha, "é menor que o sorteado") elif escolha > numero: print("O número", escolha, "é maior que o sorteado") print("Parabéns, você acertou em", tentativas, "tentativas")
false
76f61ae21e0d1747e82e42188ed61421d2dad483
jivid/practice
/cracking/Chapter 4 - Trees and Graphs/q4_5.py
596
4.21875
4
""" Implement a function to check if a binary tree is a binary search tree """ import sys # Assume here that values in the tree are positive (i.e. > 0) so as to # not worry about -1 being the base case for min and max def is_binary_search_tree(root, max=-1, min=-1): if root is None: return True if min == -1: min = -sys.maxint - 1 if max = -1: max = sys.maxint if root.value < min or root.value > max: return False return is_binary_search_tree(root.left, root.value, min) and\ is_binary_search_tree(root.right, max, root.value)
true
ad3082500a9dd68294a70036a4799d03ebf86045
siddharth20190428/DEVSNEST-DSA
/DI015_Diameter_of_a_binary_tree.py
741
4.125
4
""" Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. ----------------- Constraints The number of nodes in the tree is in the range [1, 10^4]. -100 <= Node.val <= 100 """ from DI015_Trees import TreeNode def dia(node): if not node: return 0, 0 lp, lw = dia(node.left) rp, rw = dia(node.right) return 1 + max(lp, rp), max(lw, rw, 1 + lp + rp) def diameterOfBinaryTree(root): return dia(root)[1] - 1 root = [1, 2, 3, 4, 5] root = [1, 2]
true
7b425622ed0ea1745ebabc7407082b09b1cb4e2d
siddharth20190428/DEVSNEST-DSA
/DI016_Maximum_width_of_a_binary_tree.py
1,209
4.125
4
""" Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. It is guaranteed that the answer will in the range of 32-bit signed integer. ----------------- Constraints The given binary tree will have between 1 and 3000 nodes. """ from DI015_Trees import TreeNode def getw(root, rootlevel, rootindex, widthmap): if root: if rootlevel not in widthmap: widthmap[rootlevel] = [rootindex, rootindex] elif rootindex < widthmap[rootlevel][0]: widthmap[rootlevel][0] = rootindex elif rootindex > widthmap[rootlevel][1]: widthmap[rootlevel][1] = rootindex getw(root.left, rootlevel + 1, (2 * rootindex) + 1, widthmap) getw(root.right, rootlevel + 1, (2 * rootindex) + 2, widthmap) def widthOfBinaryTree(root): widthmap = {} getw(root, 0, 0, widthmap) return max([1 + x[1] - x[0] for x in widthmap.values()])
true
ef367ea0d700846d6103154c1e6d92e97489c933
thumbimigwe/nipy
/snippets/5th feb/Number based brainteasers/Digit Grouping.py
748
4.34375
4
#!/usr/bin/python3 # When displaying numbers it is good practice to group digits together and use the comma to separate groups of three digits. For instance 100000000 is easier to read when it is displayed as 100,000,000. # Ask the user to enter any large number (e.g. at least 3 digits long). The program should display the result of formatting this number using the comma. For instance if the user enters 65738924 the program should return 65,738,924. number = int(input("type in a six figure digit")) grouping = "" counter = 0 for digit in number [::-1]: if counter==3: grouping = digit + "," + grouping counter=0 else: grouping = digit + grouping counter = +1 print("The inmber is "+grouping)
true
c38069122b4b78fcb3092018d9e93bdbe55223e9
thumbimigwe/nipy
/snippets/Math Quiz/mathQuiz.py
2,311
4.28125
4
#!/usr/bin/python3 # ********************* PROBLEM STATEMENT ********************* # A primary school teacher wants to test her students mental arithmetic by making them complete a test with 10 questions in which they complete operations like; adding, subracting and multiplying. # Complete the following tasks; # 1. Design and create the algorithm for this new primary school arithmetic quiz # 2. Think of and implement a new feature to improve this task. # # the teacher also wants to store the student's marks on a text file # # 3. Design and implement this feature into your algorithm. # # however, this teacher has two clases for mathematics and she wants to keep the class' score separate. # # 4. improve task (3) so that there is more than oneset of class score. # # # ********************* PSEUDOCODE ********************* # import a new function (Random) import random # Variables we are going to use score=0 answer=0 operators=('+','-','x') valid_name=False numbers="1234567890" # ------------------------------------------------------------- # loading up the testfile myFile=open("scores.txt","a") myFile.close() # inputing a name // data validation while valid_name == False: number_found=False name = input('what is your name? ') for i in name: for u in numbers: if i==u: number_found=True if number_found == True: valid_name=False else: valid_name=True for i in range(10): num = random.randint(5,10) num1 = random.randint(1,5) # pick out the operator of choice operator = random.choice(operators) # mark out the answer if operator == "+": answer = num + num1 elif operator == "-": answer = num - num1 elif operator == "x": answer = num * num1 # create the users input print('What is '+str(num) + operator + str(num1)) user_answer= int(input('Enter The answer = ')) # responce section if user_answer == answer: print('Correct!') score = score +1 else: print("Sorry, That's Not Right. The answer was "+str(answer)) score=score print("your score was "+str(score)) myFile=open("score.txt","a") myFile.write(name+","+str(score)+"\n") myFile.close()
true
7c620e8a40994c5dcf6f1a140ded402cff04b910
GIT-Ramteja/project1
/string2.py
1,801
4.40625
4
str = "Kevin" # displaying whole string print(str) # displaying first character of string print(str[0]) # displaying third character of string print(str[2]) # displaying the last character of the string print(str[-1]) # displaying the second last char of string print(str[-2]) str = "Beginnersbook" # displaying whole string print("The original string is: ", str) # slicing 10th to the last character print("str[9:]: ", str[9::3]) # slicing 3rd to 6th character print("str[2:6]: ", str[2:6]) # slicing from start to the 9th character print("str[:9]: ", str[:9]) # slicing from 10th to second last character print("str[9:-1]: ", str[9:-1]) print(str[-1:-1]) print(str[-3:-1]) print(str[::-1]) print(str[:-1]) str = "Welcome to beginnersbook.com" str2 = "Welcome XYZ" str3 = "come XYZ" str4 = "XYZ" # str2 is in str? True print(str2 in str) # str3 is in str? False print(str3 in str2) # str4 not in str? True print(str4 not in str) print(str4 not in str3) str = "AbC" str2 = "aBC" str3 = "aYZ" str4 = "byz" print(str>str2) print(str4<str3) b = "Hello, World!" print(b[-5:-2]) a = " Hello World! " print(a.strip()) print(a.lstrip()) print(a.rstrip()) print(a.lower()) print(a.upper()) print(a.replace("H", "J")) print(a.split(" ")) txt = "The rain in Spain stays mainly in the plain {}" x = "ain" in txt print(x) x = "ain" not in txt print(x) age=36 print(txt.format(age)) quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) txt = "We are the so-called \"Vikings\" from the north." print(txt) r="resdddeff" print(type(r)) print(r[0:4:1])
true
c612c428f14af37f07d412303b80302040f8516f
Paavni/Learn-Python
/Python project/pythonex8.py
330
4.125
4
#print "How are you today?" #answer = raw_input() #print "Enter age" #age = raw_input() #print "Your age is %s" %age print "This will print in", print "one line.", print "One line it is!" name = raw_input("What is your name? ") print "Your name is: %s" %name age = raw_input("What is your age? ") print "Your age is: %r" %age
true
75bab9cc50495b3f50749278e02fe7e54e126c50
timorss/python
/24addRemoveItem.py
616
4.28125
4
letters = ['a', 'b', 'c', 'd'] # add item in the beginning letters.append('e') print(letters) # ['a', 'b', 'c', 'd', 'e'] # add item in specific location letters.insert(3, '--') print(letters) # ['a', 'b', 'c', '--', 'd', 'e'] # remove item in the end letters.pop() print(letters) # ['a', 'b', 'c', '--', 'd'] # remove item in specific location letters.pop(1) print(letters) # ['a', 'c', '--', 'd'] # remove item not by index letters.remove('--') print(letters) # ['a', 'c', 'd'] # remove many items del letters[1:2] print(letters) # ['a', 'd'] # empty all the list letters.clear() print(letters) # []
true
8010ee6122f45866fd1a3dbffac29a039ceff938
ajpiter/CodeCombat
/Desert/SarvenSavior.py
753
4.125
4
"""My pet gets left behind everytime :( """ # An ARRAY is a list of items. # This array is a list of your friends' names. friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus'] # Array indices start at 0, not 1! friendIndex = 0 # Loop over each name in the array. # The len() function gets the length of the list. while friendIndex < len(friendNames): # Use square brackets to get a name from the array. friendName = friendNames[friendIndex] # Tell your friend to go home. # Use + to connect two strings. hero.say(friendName + ', go home!') # Increment friendIndex to get the next name. friendIndex += 1 # Retreat to the oasis and build a "fence" on the X. hero.moveXY(22, 29) hero.buildXY("fence", 30, 30)
true
9ba06c2ab12388b1ffe5596089dbd34c681d3c95
AnthonyWalton1/ARBI
/Raspberry Pi/Raspberry Pi Code/Arbi GUIs/GUI Tutorials/Tutorial1.py
350
4.125
4
#!/usr/bin/env python from Tkinter import * # Start a GUI (object) from Tkinter class root = Tk() # Create a label (text box widget) called theLabel and set what text it shows theLabel = Label(root, text = "Python GUI") # Place the text box in the first available space and display it theLabel.pack() # Keep the GUI on screen root.mainloop()
true
7c92766f99e3dff17ed5426962aca10f1bac7890
Environmental-Informatics/building-more-complex-programs-with-python-avnika16
/amanakta_Exercise_6.5.py
460
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Solution for Exercise 6.5 Avnika Manaktala """ def gcd(a,b): #Defining GCD function if b!=0: #Setting up recursion return gcd(b, a%b) else: return a #When b=0 recursion stops def user_gcd(): #Defining user input for GCD function a= int(input("Enter a: ")) a= float(a) b= int(input("Enter b: ")) b= float(b) print("GCD= ", gcd(a,b)) user_gcd() #Running Function
true
e013ee6c78fef1df17b4f1879b49d628c0386c30
jonathangjertsen/classmemo
/classmemo/__init__.py
2,039
4.125
4
""" A `Memoizer` can be used as a factory for creating objects of a certain class. It exposes a constructor and 2 methods * `memoizer = Memoizer(SomeClass)` * `memoizer.get(*args, **kwargs)` * If `memoizer` has never seen the given arguments, it creates `SomeClass(*args, **kwargs)` and returns it. * If `memoizer` has seen the given arguments before, it returns the same instance that it returned the last time. * `memoizer.forget(*args, **kwargs)` * Makes `memoizer` forget that is has seen the given arguments. ### Usage The original application was for a `MeasurementQueue` class that processes incoming sensor data from many sensors, where the sensor ID's were not known ahead of time: ```python queue_manager = Memoizer(MeasurementQueue) for sensor_id, data in event_stream(): queue = queue_manager.get(sensor_id) queue.push(data) ``` When the first measurement comes in for a given sensor_id, a new `MeasurementQueue` will be created and returned for that sensor. On subsequent events with the same sensor ID, the same `MeasurementQueue` instance will be used to process the data. """ from typing import Tuple from frozendict import frozendict class Memoizer(object): __slots__ = ["instances", "cls"] def __init__(self, cls: type): """Set the class and make an empty instance dict""" self.instances = {} self.cls = cls def key(self, *args, **kwargs) -> Tuple[Tuple, frozendict]: """Returns the arguments as a key that can be used for dictionary lookup.""" return (args, frozendict(kwargs)) def get(self, *args, **kwargs): """Returns an instance if found, otherwise a new instance.""" key = self.key(*args, **kwargs) if key not in self.instances: self.instances[key] = self.cls(*args, **kwargs) return self.instances[key] def forget(self, *args, **kwargs): """Removes the instance from the internal lookup.""" key = self.key(*args, **kwargs) self.instances.pop(key, None)
true
612ca7eb6e6f9e77ed0d8315e560c88ecc50840c
ferminitu/F_de_Informatica
/F. de Informática/Python avanzado/Práctico1-Parte2/Ejercicio 14.py
661
4.1875
4
# Creá una función que calcule la temperatura media de un día a partir de la temperatura máxima y mínima. Escribí un programa principal, # que utilizando la función anterior, vaya pidiendo la temperatura máxima y mínima de cada día y vaya mostrando la media. El programa # tiene que pedir el número de días que se van a introducir. def temp_media(temp, temp1): return (temp + temp1) / 2 dias = int(input("Ingrese la cantidad de dias: ")) num = 0 while num < dias: max = float(input("Ingrese la temperatura maxima del dia: ")) min = float(input("Ingrese la temperatura minima del dia: ")) num += 1 print(temp_media(max, min))
false
b8980a7259eb8cb5f01f156e0d053f0b74e8f758
dwhdai/advent_of_code
/2020/day3.py
2,826
4.4375
4
def import_map(filepath): """Given a filepath, import the map object as as a nested list. Returns: list: a 2D nested list, representing the rows of the map as individual list objects """ with open(filepath) as f: map = f.read().splitlines() return map def traverse_step(start_position, map_width, step_x=3, step_y=1): """Given a starting coordinate, return the ending coordinate after traversing one step of "right 3 down 1" Args: start_position[tuple]: (x coordinate, y coordinate) map_width[int]: the width of the map step_x, step_y[int]: number of steps to take in the x,y direction Returns: [int]: x coordinate, y coordinate """ x_end = (start_position[0] + step_x) % map_width y_end = start_position[1] + step_y return x_end, y_end def tree_present(map, position): """Given a map and position, check to see if the inputted position contains a tree on the map Args: map[list]: 2D list representing the map as row vectors position[tuple]: (x coordinate, y coordinate) Returns: tree[boolean]: True if tree present, False otherwise """ x_coord = position[0] - 1 y_coord = position[1] - 1 tree = map[y_coord][x_coord] == "#" return tree def traverse_map(map, start_position=(1, 1), step_x=3, step_y=1): """Given a map, traverse through the map by taking steps of 3 right 1 down, and count the number of trees encountered. End when finished traversing all rows of the map. Args: map[list]: 2D list object start_position[tuple]: tuple with 2 ints, representing the x and y coordinates of the starting position. Note: to get list indices, subtract 1 from the position step_x, step_y[int]: the number of units to traverse in x and y directions per step Returns: num_trees[int]: number of trees encountered """ # Define x and y positions, initialized to start_position x = start_position[0] y = start_position[1] # Calculate width of map map_width = len(map[0]) # Initialize tree counter num_trees = 0 while y - 1 < len(map): # Check if current position contains a tree # If there is, add to num_trees counter num_trees += tree_present(map, (x, y)) # Iterate to next step x, y = traverse_step((x, y), map_width, step_x, step_y) return num_trees map = import_map("./day3_input.txt") slope1 = traverse_map(map, step_x=1, step_y=1) slope2 = traverse_map(map, step_x=3, step_y=1) slope3 = traverse_map(map, step_x=5, step_y=1) slope4 = traverse_map(map, step_x=7, step_y=1) slope5 = traverse_map(map, step_x=1, step_y=2) print(slope1 * slope2 * slope3 * slope4 * slope5)
true
47fb7a15721f699fdf2703ec25bea5afe020b90a
sam943/Python2.7
/Python_301/sqlite_database_connections.py
937
4.25
4
import sqlite3 # default db module available with python conn = sqlite3.connect('dem3d.db') # here is the db doesn't exist the database is created c = conn.cursor() # cursor is a handle to execute our queries c.execute('''CREATE TABLE users(username text,email text)''') c.execute("INSERT INTO users VALUES ('Sam', 'me@mydomain.com')") conn.commit() # Inserting values through variable username, email = 'I', 'I@idomain.com' # Assigning multiple variables c.execute("INSERT INTO users VAlUES(?, ?)",(username, email)) conn.commit() # Inserting values as List userlist = [('paul', 'p@domain.com'),('donny', 'd@domain.com')] c.executemany("INSERT INTO users VAlUES(?, ?)",userlist) conn.commit() # Select using username as variable c.execute('SELECT email from users where username = ?',(username,)) print c.fetchone() # Lookup with single value in tuple lookup = ('Sam',) c.execute('SELECT email from users where username = ?', lookup) print c.fetchone()
true
8195a360629e12c4efec9d2086466e6f15e0cfe2
josefren/numpy-scipy-exercises
/exercise-7-numpy-practice.py
1,748
4.65625
5
""" Start up Python (best to use Spyder) and use it to answer the following questions. Use the following imports: import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt 1 Choose a value and set the variable x to that value. 2 What is command to compute the square of x? Its cube? 3 Choose an angle θ and set the variable theta to its value (a number). 4 What is sinθ? cosθ? Angles can be measured in degrees or radians. Which of these are being used used? 5 Use the np.linspace function to create a row vector called meshPoints containing exactly 500 values with values evenly spaced between -1 and 1. 6 What expression will yield the value of the 53th element of meshPoints? What is this value? 7 Produce a plot of a sinusoid on the interval [−1, 1] using the command plt.plot(meshPoints,np.sin(2*pi*meshPoints)) 8 Please save this plot as a jpeg (.jpg) file and send it along with your work. """ import math import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt LINE = "-" * 30 # 1 x = 42 # 2 print("Square of {x} is {square}, Cube is {cube}".format(x=x, square=x ** 2, cube=x ** 3)) print(LINE) # 3 theta = 30 * (math.pi / 180) # 4 print("θ = {} radian, Sin of θ = {}, Cos of θ = {}".format(theta, math.sin(theta), math.cos(theta))) # print("θ = {} radian, Sin of θ = {}, Cos of θ = {}".format(theta, np.sin(theta), np.cos(theta))) print(LINE) # 5 meshPoints = np.linspace(-1, 1, 500) print("500 values with values evenly spaced between -1 and 1\n", meshPoints) print(LINE) # 6 print("53th value of meshPoints is {}".format(meshPoints[52])) print(LINE) # 7 plt.plot(meshPoints, np.sin(2 * math.pi * meshPoints)) plt.show() # 8 plt.savefig("sin.png")
true
d6d79f72a837978a1244c929b26270b76845030f
DreamXp/cse210-student-hilo
/hilo/game/Guesser.py
1,999
4.25
4
import random class Guesser: """The responsibility of this class of objects is to play the game - choose the card, add or subtract points from the total, guess whether the next card will be lower or higher, and determine whether the player can guess again. Attributes: points (number): The number of points added or taken away per round """ points = 300 cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] def __init__(self): """Class constructor. Decares and initializes instance attributes. Args: self (Guesser): An instance of Guesser. """ self.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] def deal_first_card(self): """Deals (prints) a random card to the user. Args: self (Dealer): An instance of Dealer. Returns: int: Value representing the integer representation of the card for comparison. """ randomCardIndex = random.randint(0,12) print(f'The card is: {self.cards[randomCardIndex]}') return randomCardIndex def deal_second_card(self): """Deals (prints) a random card to the user. Args: self (Dealer): An instance of Dealer. Returns: int: Value representing the integer representation of the card for comparision. """ randomCardIndex = random.randint(0,12) print(f'The next card was: {self.cards[randomCardIndex]}') return randomCardIndex def choose_card(self): card1 = self.deal_first_card() guess = input(f'High or Low? (h/l)').lower guess = input(f'High or Low? (h/l)').lower() card2 = self.deal_second_card() if guess == 'l': if card2 <= card1: return True else: return False elif guess == 'h': if card2 >= card1: return True else: return False
true
be56e882bbb827a1e40a1d6c06333292627ab9a8
artsalmon/Think-Python-2e---my-solutions
/07 - Exercises/7.2 - Module 2.py
1,083
4.5
4
""" Exercise 7.2. The built-in function eval takes a string and evaluates it using the Python interpreter. For example: >>> eval('1 + 2 * 3') 7 >>> import math >>> eval('math.sqrt(5)') 2.2360679774997898 >>> eval('type(math.pi)') <class 'float'> Write a function called eval_loop that iteratively prompts the user, takes the resulting input and evaluates it using eval, and prints the result. It should continue until the user enters 'done', and then return the value of the last expression it evaluated. This example is detailed and added content for end user understanding. """ def eval_loop(): while True: user_input = input("Enter a command (or 'done' to quit):\n") if user_input == "done": print("The last user input was: ", eval(user_var)) # if "done" is entered, this line will print the last variable (see comment below) print("You have entered done, program now exiting.") break print(eval(user_input)) user_var = user_input # this adds the last evaluated to a new variable "user_var" eval_loop()
true
a3748d80579b19cf572f07a9dac445457895f749
theecurlycoder/CP_PWP
/1. Python/control_flow.py
551
4.25
4
# if/then statements # boolean values likes_pizza = True likes_cats = False print(True) print(False) is_john_killer = True is_bob_killer = False if is_bob_killer == True: print("Bob is the killer") if is_john_killer == True: print("John is the killer") print() #Equality Operators print(5 == 5) print(5 > 5) print(5 <= 5) print('___________________________________') x = -1 if x < 5: print('smaller than 5') elif x == 10: print('equal to 10') elif x > 15: print('greater than 15') else: print('is it even a number?')
true
7130c34b6e9b7cabc479c49e8bb118b9130b7220
yudhapn/OCBC-H8-Python
/Session3/function.py
2,413
4.1875
4
# case 1 def my_function(p, l): '''Function to calculate area of a square''' print(p * l) def printme(str_input): print(str_input) printme("I'm first call to user defined function") printme("Again second call to do the same function") print("\n===processing input and return it===") def changeme(myList): myList = myList+[1,2,3,4] print("\nValues inside the function: ",myList) return myList myList = [10,20,30] print("\nValues outside the function - before : ", myList) myList = changeme( myList ) print("\nValues outside the function - after : ", myList) # Required arguments print("\n===Required arguments===") def printme( str_input ): '''This prints a passed string into this function''' print(str_input) # Now you can call printme function printme("Hello") # # This syntax will give you an error # printme() # argument order is important! def personalInfoData(name, age): print("name:", name) print("age:", age) personalInfoData("yudha", 24) # wrong personalInfoData(24, "yudha") # Keyword Arguments print("\n===Keyword Arguments===") personalInfoData(age = 24, name = "yudha") # Default Arguments print("\n===Default Arguments===") def printinfo( name, age = 24 ): print("Name : ", name) print("Age : ", age) print("") # Now you can call printinfo function printinfo( age=18, name="yudha" ) print("\n===Variable-length Arguments (Tuples)===") def printinfo( arg1, *vartuple ): print('arg1 : ', arg1) print('vartuple : ', vartuple) print('') for var in vartuple: print('isi vartuple : ', var) printinfo( 10 ) printinfo( 70, 60, 50, "a" ) print("\n===Variable-length Arguments (Dictionary)===") def person_car(total_data, **kwargs): '''Create a function to print who owns what car''' print('Total Data : ', total_data) print("kwargs:", kwargs) for key, value in kwargs.items(): print('Person : ', key) print('Car : ', value) print('') person_car(3, jimmy='chevrolet', frank='ford', tina='honda') person_car(3) # person_car(3, {"jimmy":'chevrolet', "frank":'ford', "tina":'honda'}) sum = lambda arg1, arg2: arg1 + arg2 # That lambda function will be equal to : # def sum(arg1, arg2): # return arg1+arg2 def calculate(sum): print(sum) # Now you can call sum as a function print("Value of total : ", sum( 10, 20 )) print("Value of total : ", sum( 20, 20 )) calculate(sum( 10, 20 ))
true
8c54fe17d934cfeefac3baaa6852201a163cc696
iisdd/Courses
/python_fishc/45.2.py
1,060
4.125
4
'''2.编写一个 Counter 类,用于实时检测对象有多少个属性 程序实现如下: >>> c = Counter() >>> c.x = 1 >>> c.counter 1 >>> c.y = 1 >>> c.z = 1 >>> c.counter 3 >>> del c.x >>> c.counter 2 我的答案: class Counter: def __init__(self): self.counter = 0 def __setattr__(self , name , value): if name != 'counter': super().__setattr__(name , value) self.counter += 1 else: super().__setattr__('counter', value) def __delattr__(self , name): super().__delattr__(name) self.counter -= 1 ''' # 网站答案:(super就完事了) class Counter: def __init__(self): super().__setattr__('counter' , 0) def __setattr__(self , name , value): super().__setattr__('counter' , self.counter + 1) super().__setattr__(name , value) def __delattr__(self , name): super().__setattr__('counter' , self.counter - 1) super().__delattr__(name) c = Counter()
false
87cf045792fbaf399c8c2285bebc1cf4fdd1696a
iisdd/Courses
/python_fishc/46.2.py
1,201
4.1875
4
'''2. 再来一个有趣的案例:编写描述符 MyDes,使用文件来存储属性, 属性的值会直接存储到对应的pickle(腌菜,还记得吗?)的文件中。 如果属性被删除了,文件也会同时被删除,属性的名字也会被注销 举个栗子: >>> class Test: x = MyDes('x') y = MyDes('y') >>> test = Test() >>> test.x = 123 >>> test.y = "I love FishC.com!" >>> test.x 123 >>> test.y 'I love FishC.com!' 产生对应的文件存储变量的值: 如果我们删除 x 属性: >>> del test.x >>> 对应的文件也不见了: ''' import pickle import os def save_file(file_name , num): with open(file_name + '.pkl' , 'wb') as f: pickle.dump(num , f) class MyDes: def __init__(self , name): self.name = name def __get__(self , instance , owner): return self.value def __set__(self , instance , value): self.value = value save_file(self.name , self.value) def __delete__(self , instance): os.remove(self.name + '.pkl') del self.name class Test: x = MyDes('x') y = MyDes('y') test = Test()
false
2bed38ecafd8dc1077079b023fd78cbaface8c28
iisdd/Courses
/python_fishc/11.0.py
386
4.15625
4
'''0. 课堂上小甲鱼说可以利用分片完成列表的拷贝 list2 = list1[:], 那事实上可不可以直接写成 list2 = list1 更加简洁呢? ''' # 举个例子: list1 = [1 , 9 , 5 , 7 , 6 , 2] list2 = list1[:] list3 = list1 list1.sort() print('母体列表1:' + str(list1)) print('copy列表2:' + str(list2)) print('墙头草列表3:' + str(list3))
false
b431fd6ddcbcb157382bcfa82b33b4b3faac088d
iisdd/Courses
/python_fishc/6.1.py
305
4.125
4
''' 1. 我们说过现在的 Python 可以计算很大很大的数据,但是...... 真正的大数据计算可是要靠刚刚的硬件滴,不妨写一个小代码,让你的计算机为之崩溃? ''' # 不推荐运行嗷 count = 100 for i in range(1 , 100): count **= i print(count)
false
c33e1014f0b877dbec5dc4c129c9c8d8b1934c0d
raj-andy1/mypythoncode
/samplefunction14.py
282
4.15625
4
""" sampleprogram14 - class 4 while loop example - type a """ looping = True while looping == True: answer = input("Type letter a") if answer == 'a': looping = False else: print ("TYPE THE LETTER A") print ("Thanks for typing the letter A")
true
5bc78f4f6b0a5f48ebae15a7cc5db65e6dbdc386
irakowski/PY4E
/03_Access Web Data/ex_12_3.py
945
4.5
4
"""Exercise 3: Use urllib to replicate the previous exercise of (1) retrieving the document from a URL, (2) displaying up to 3000 characters, and (3) counting the overall number of characters in the document. Don’t worry about the headers for this exercise, simply show the first 3000 characters of the document contents.""" import urllib.request import re url = input('Enter valid url: ') url_verification = re.search(r'^(?P<http>https?://|www\d{0,3}[.]|)(?P<host>[a-z0-9.\-]+[.][a-z]{2,4})/.*', url) if url_verification is not None: url = url_verification.group() else: print('Could not parse url address. Please verify provided link') quit() with urllib.request.urlopen(url) as response: print() count = 0 text = '' for line in response: for character in line: count +=1 text = text + line.decode().strip() print(text[:30]) print(f'Total # of characters: {count}')
true
4ca87c9e82ed461cf2a0192c354493279d0ec224
irakowski/PY4E
/01_Getting Started with Python/ex_3_1.py
403
4.1875
4
""" Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours """ hours = float(input("Enter Hours: ")) rate = float(input("Enter Rate: ")) standart_time = 40 if hours > standart_time: overtime_rate = rate * 1.5 * (hours - standart_time) pay = (standart_time * rate) + overtime_rate else: pay = hours * rate print("Pay: ", pay)
true
f93df966be9f9c9c4121154d0e014840b95cc70b
irakowski/PY4E
/02_Data Structures/ex_7_1.py
759
4.3125
4
"""Exercise 1: Write a program to read through a file and print the contents of the file (line by line) all in upper case. Executing the program will look as follows: python shout.py Enter a file name: mbox-short.txt FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008 RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJECT.ORG> RECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90]) BY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA; SAT, 05 JAN 2008 09:14:16 -0500 You can download the file from www.py4e.com/code3/mbox-short.txt""" filename = input('Enter the file name: ') try: file = open(filename, 'r') except: print('File cannot be opened:', filename) exit() output = open('shout.txt', 'w') for line in file: line = line.upper() output.write(line) output.close()
true
2ad39ba81a7e59fd6f49d809279ed67bfcb3f419
Jdothager/web-caesar
/caesar.py
1,271
4.25
4
def encrypt(text, rot): """ receives a string, rotates the characters by the the integer rot and returns the new string """ if type(rot) != int: rot = int(rot) # if text is not a string, return text if type(text) is not str: return text # encrypt and return the new string new_string = "" for i in range(len(text)): new_string += rotate_character(text[i], rot) return new_string def alphabet_position(letter): """ receives a single character string and returns the 0-based index alphabet position """ # calculate position based on lowercase characters letter = letter.lower() position = ord(letter) - 97 return position def rotate_character(char, rot): """ receives a single character string and an integer to rotate by returns the new char based on rotating to the right by rot """ # return char if it is not a letter if not char.isalpha(): return char # rotate position old_pos = alphabet_position(char) new_pos = (old_pos + rot) % 26 # preserve original case if char.islower(): new_pos += 97 else: new_pos += 65 # calculate and return new character char = chr(new_pos) return char
true
5a25d8f5cf6f8bee0c6d43b8f591480946ed07a3
SahRieCat/python
/02_basic_datatypes/2_strings/02_10_most_characters.py
754
4.5625
5
''' Write a script that takes three strings from the user and prints them together with their length. Example Output: 5, hello 5, world 9, greetings CHALLENGE: Can you edit to script to print only the string with the most characters? You can look into the topic "Conditionals" to solve this challenge. ''' #input1 usr1 = input("type something") #input2 usr2 = input("type something") #input3 usr3 = input("type something") #count1 cou1 = (len(usr1)) #count2 cou2 = (len(usr2)) #count3 cou3 = (len(usr3)) #printall print(cou1,",",usr1) print(cou2,",",usr2) print(cou3,",",usr3) #print only the string with the most characters biggest = usr1 if cou1 < cou2: biggest = usr2 if cou2 < cou3: biggest = usr3 print(biggest)
true
5d9540a605a97694b2b934181a11afb8c3361da6
nkbyrne/scrap
/reusing_code/dice.py
626
4.125
4
#!/usr/bin/env python3 """ This will roll two dice and print out the values """ import sys from random import randint def rolldice(): print() answer = input("Roll Dice? (y/n):") if (answer == "y") or (answer == ""): die01 = (randint(1, 6)) die02 = (randint(1, 6)) #print(("You rolled a:"), (die01)) return die01, die02 elif answer == "n": sys.exit(0) else: print("Invalid key pressed") sys.exit(1) def main(): die01, die02 = rolldice() print("die01 ", die01) print("die02 ", die02) main() if __name__ == "__main__": main()
false
b3f95c536d87d27d1a37ec0df9e47050b2c0e0d3
y0ssi10/leetcode
/python/symmetric_tree/solution.py
1,338
4.28125
4
# Problem # # Given a binary tree, # check whether it is a mirror of itself (ie, symmetric around its center). # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: # 1 # / \ # 2 2 # / \ / \ # 3 4 4 3 # import queue class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: q = queue.Queue() q.put(root) q.put(root) while not q.empty(): t1 = q.get() t2 = q.get() if t1 is None and t2 is None: continue if t1 is None or t2 is None: return False if t1.val != t2.val: return False q.put(t1.left) q.put(t2.right) q.put(t1.right) q.put(t2.left) return True # Recursive def is_symmetric_2(self, root: TreeNode) -> bool: def is_mirror(left: TreeNode, right: TreeNode): if left is None and right is None: return True if left is None or right is None: return False return left.val == right.val and is_mirror(left.left, right.right) and is_mirror(left.right, right.left) return is_mirror(root, root)
true
b7755ffbc6242a2098ff4a99d4623e24b7fc3d25
y0ssi10/leetcode
/python/diameter_of_binary_tree/solution.py
1,031
4.21875
4
# Problem: # Given a binary tree, you need to compute the length of the diameter of the tree. # The diameter of a binary tree is the length of the longest path between any two nodes in a tree. # This path may or may not pass through the root. # # Note: # The length of path between two nodes is represented by the number of edges between them. # # Example: # 1 # / \ # 2 3 # / \ # 4 5 # Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. # class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: def calc(node: TreeNode) -> 'Tuple[int, int]': if node is None: return 0, 0 l = calc(node.left) r = calc(node.right) height = max(l[0], r[0]) + 1 return height, max((l[0] + r[0]), max(l[1], r[1])) output = calc(root) return output[1]
true