blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9a666f4a21fcdc424bd8cbf1daab06193ea917a9
jjagdishh/python-practice-codes
/shorting list.py
418
4.34375
4
list= ["1", "4", "2", "9", "7","10"] # we have a like string # to short we can use short function like below list.sort() print(list) # Output: ['1', '10', '2', '4', '7', '9'] # So it will short the strings but like that not as integer numbers # to short the number list in correct order we can do like this list1= ["1", "4", "2", "9", "7","10"] list1= [int(i) for i in list1] list1.sort() print (list1)
true
9e0ca5a08bb037796fc7055906b38fc84a28bc6d
jjagdishh/python-practice-codes
/working with files.py
1,355
4.46875
4
# In this demo we will see different method to create a new file in different methods and how you can access them # to Create a file file= "Demo.text" # Note if you do not give the exact path for your file it will be created in the default folder of that project permission= "r" # Always use the permission what you required at that time # w= write # r= read # a= append myfile= open(file,permission) # Now File has been created we will write something in our file myfile.write("hey this is a demo text file \n") #Now we will append some text in the file myfile.write("we are appending some text her \n ") # Note make sure the file permission is set to "w" while appending something in a file else it will overwrite the existing information # Now lets write an CSV file. A Comma is used to separate the lines in the csv file myCsv= open("DemoCsv.csv",'w') myCsv.write("Jagdish,20 \n") myCsv.write("Abnish,20 \n") # to read a file print(myfile.read()) myfile.close() myCsv.close() # If you need to delete an file from your system import os os.remove('Demo.text') os.remove('DemoCsv.csv') # For Loop to read a text file and its Word myfile = open("Demo.text",'r') myfile.readline() for currentline in myfile: print(currentline) for currentword in currentline: print (currentword)
true
d3dc19df8138d68c887044d37fd32665352ea7c0
linika/Python-Program
/code70.py
232
4.46875
4
# program to sort the list o tuples in increasing order by last elemnet in each tuple def last(n): return n[-1] def sort(tuples): return sorted (tuples,key=last) a=input("enter the list of tuples") print("sorted") print(sort(a))
true
40a18cf482e9e9d0e87f1b0bc1da60179ab387d0
linika/Python-Program
/code47.py
260
4.40625
4
# to check substring is present in given string(this is running online) strg=input("enter the string") sub_str=input("enter the sub string") if (strg.find(sub_str)==-1): print("substring not found in the string") else: print("substring found in the string")
true
b8d7db14b87c43c2b363c140ba0a6db0a79d7606
ynonp/basic-python-for-developers
/session1/solutions1/03.py
312
4.1875
4
# Read an input number from the user, # print BOOM if: # the number is divisible by 7 # OR the number contains 7 number : int = int(input("Please select a number")) is_divisible_by_7 : bool = number % 7 == 0 contains_7 : bool = "7" in str(number) if is_divisible_by_7 or contains_7: print("BOOM")
true
e8bfe95efdd712efc920f04a502cc01d327dc9b5
Enkuushka/class1
/2019-10-05/func.py
1,030
4.25
4
def add(a, b): print(a+b) def main(): print("I am main function") add(5, 8) def selfCallingFunc(too): if(too > 0): print(too) selfCallingFunc(too-1) #selfCallingFunc(4) ## no for, while ## n - from keyboard ## n! = 1*2*3*4...*n ## RECURSIVE FUNCTION example def factorial(n): if(n == 1): return 1 else: return n * factorial(n-1) #print(factorial(5)) # default value def printer(text = "Default text"): print(text) #printer("Хэвлүүлэх текст") #printer() # олон элемэнттэй аргумент def listHandler(theList): for x in theList: print(x) listHandler([1, "neg", "abc", ("a1",), {"a":1}]) def named(arg1, arg2="default 2"): print("arg1 = "+arg1) print("arg2 = "+arg2) #named(arg1 = "neg") def manyArgs(*args): urt = len(args) print("Ta "+str(urt)+" ширхэг өгөгдөл дамжуулсан.") if(1 in args): print("1 baina.") #print(args) manyArgs(1, 2,3, "asdasd", "223")
false
12869c01cfa8554d8e30334bf7c9b036121e26cb
gutorocher/dojo-pydjango
/dojo-day6/calculadora.py
1,259
4.28125
4
# -*- coding: utf-8 -*- #Autor: Gustavo, Elber #Caso: # Implementar Classe objeto #Implementar classe calculos #todos os objetos informam seus valores #PASSO 1 - implementar teste #PASSO 2 - implementar funcionalidade #PASSO 3 - Voltar o passo 1 import math class Calculos(object): def __init__ (self,n1,n2): self.n1 = n1 self.n2 = n2 def soma (self): soma = self.n1 + self.n2 return soma def subtracao(self): subtracao = self.n1 - self.n2 return subtracao def multiplicacao(self): multiplicacao = self.n1 * self.n2 return multiplicacao def divisao(self): divisao = self.n1 / self.n2 return divisao def raizQuadrada(self): raiz = math.sqrt(self.n1) return raiz if __name__ == '__main__': print " ============================" print " CALCULOS BASICOS CALCULADORA " print " ============================" c = Calculos(5.0,6.0) print " Soma dos valores : %s" %c.soma() print " Subtracao dos valores : %s" %c.subtracao() print " Divisao dos valores : %s" %c.divisao() print " Raiz Quadrada do valor : %s" %c.raizQuadrada() print " ============================"
false
994a88248abdbb3e458661f49b3ee046172190f9
singhdharm17/Python_Edureka
/Question_8.py
556
4.21875
4
"""8. Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma- separated sequence.""" import math C = 50 H = 30 def Formula(D): Q = int(math.sqrt((2 * C * D) / H)) return Q print("Enter the number") num = input(">>> ") num = num.split(",") result = [] for i in range(len(num)): f = Formula(int(num[i])) result.append(f) print(result)
true
a2bd0cf1a239e19811ba45ac118cd46c0d09c365
gabrielmichi/Python
/cursoPython/Map-Filter.py
653
4.5
4
####### Map Function ####### # Muito utilizado com listas # Aplicar uma função a um Iterable, por item. (list, turple, dic etc) ####https://docs.python.org/3/library/functions.html lista1 = [1, 2, 3, 4] #Função Map em uma lista def multi(x): return x * 2 lista2 = map(multi, lista1) print(list(lista2)) ### MAP com Lambda ### Com 1 linha, conseguimos substituir as 4 do exemplo anterior print(list(map(lambda x: x*2, lista1))) ###### FILTER ###### valores = [10, 12, 40, 45, 57] def remover20(x): return x > 20 print(list(filter(remover20, valores))) ## mesmo exemplo, utilizando lambda print(list(filter(lambda x: x > 20, valores)))
false
e34040cd6512f0964d1d32609b00b6359f7ba34b
stevehngo/cti110
/ngo_ca618.py
1,238
4.34375
4
# Steve Ngo # ngo_cw618 # 6-18-2019 # This program will calculate the area of a triangle #Psudocode # 1.)Declare Variables # Base = 0 float # Height = 0 float # area = 0 float # HALF = .5 float # 2.)Prompt user for the base and height of the triangle # 3.)Calculate the area of the triangle using the following formula: # area = .5base * height # 4.)Display the area of the triangle # declare variables base = 0.0 height = 0.0 area = 0.0 HALF = .5 # prompt user for the height and base base = float(input("Enter the base of the triangle: ")) height = float(input("Enter the height of the triangle: ")) # calculations area=HALF*base*height #or area=.5*base*height # display area of the triangle ##print("The area of the triangle is " + str(area)) ## ##print("the area of the triangle is ", format(area,'.2f' ),".",sep='', end='') ## ##print("The area of the triangle is " + str(area)) #extra title = "Triangle" baseHdg = "Base" heightHdg = "Height" areaHdg = "Area" print(title.center(30)) print() print(baseHdg.ljust(10) + heightHdg.ljust(10) + areaHdg.ljust(10)) print() print(str(format(base,'.2f')).ljust(10) + str(height).ljust(10) + str(area).ljust(10))
true
75ff6bd832ce5bd30ea1a0d128d225e18e1c9564
stevehngo/cti110
/P3HW1_ColorMixer_Ngo.py
1,141
4.21875
4
# CTI-110 # P3HW1 - Color Mixer # Steve Ngo # 6-20-2019 # #psudocode # 1.)Prompt user for primary color inputs # 2.)Display results of mixing two colors using the following: # red + blue = purple # red + yellow = orange # blue + yellow = green # 3.)Include error message if user inputs foregn variables # extra print("Primary Color Mixer".center(30)) print("Please input two primary colors.") print("Primary colors are: red, blue, and yellow") print() # prompt user for primary colors prime1 = str(input("Enter a primary color: ")) prime2 = str(input("Enter a primary color: ")) print() # display results if (prime1 == "red" and prime2 == "blue") or (prime1 == "blue" and prime2 == "red"): print(prime1 + " mixed with " + prime2 + " is purple. ") elif (prime1 == "red" and prime2 == "yellow") or (prime1 == "yellow" and prime2 == "red"): print(prime1 + " mixed with " + prime2 + " is orange. ") elif (prime1 == "blue" and prime2 == "yellow") or (prime1 == "yellow" and prime2 == "blue"): print(prime1 + " mixed with " + prime2 + " is green. ") # error message else: print("Error please use primary colors.")
true
9c822ef11d3d72e6fec0d73c098bf8f3ac56d62b
AkshayKamble2312/personal
/akshay/python_lectures/statementsnew.py
2,492
4.3125
4
# #if statements # if 1==1: # print('im in if statement') # else: # print('im in else statement') # if 2>3: # print('it is true') # else: # print('it is false') # if ('true'): # print('1==1') # else: # print('1<1') # if False: # print('a==a') # else: # print('a<b') #------------------------------------------------------------------------------------------------------------------------------------- # a=int(input('enter value of a')) # b=int(input('enter value of b')) # if a>b: # print('a is smaller than b') # if (a-b >= 2): # print('a is greater than b{}'.format(a-b)) # elif a<b: # print('a is greater than b') # else: # print('a is equal to b') #------------------------------------------------------------------------------------------------------------------------------------------ # list2=[1,2,3,4,5,6] # print(list2) # for item in list2 : # if not(item % 2): # print(item) #------------------------------------------------------------------------------------------------------------------------------------------- # list1=[1,2,3,4,5] # print(list1) # for item in list1 : # if not (item % 2): # print(item) #------------------------------------------------------------------------------------------------------------------------------------------ #for loop with sorting # d={'a':'akshay','b':'banana','c':'car'} # for w,e in d.items(): # print(w) # print('value is',e) #------------------------------------------------------------------------------------------------------------------------------- #functions # def my_name(a,b): # print(a+b) # return a+b # my_name(4,2) #--------------------------------------------------------------------- # def is_prime (num): # for n in range (2,num): # if not num%n== 0 : # print ('number is not prime') # break # else: # print('number is prime') #------------------------------------------------------------------------- #map # def list1(num): # return num**2 # new_list2=[1,2,3,4,5] # new_list=list(map(list1,new_list2)) # print(new_list) #------------------------------------------------------------------------ # names = ['raju','akshay','sam','ram'] # def even_odd(name) # print (name) # if(len(name%2==0)): # return even_odd #-----------------------------------------------------------------------
false
ec14819a74a8342b5b76a0c620349daf056a218b
larion/algorithm-yoga
/linked_lists.py
2,693
4.125
4
#! /usr/bin/python # singly linked lists class Node(object): def __init__(self, value, succ=None): self.value= value self.succ = succ def set_next(self, succ): self.succ = succ class linked_list(object): """ Single linked list class. """ def __init__(self, iterable): """ Make a linked list from an iterable. """ it = iter(iterable) try: self.first = Node(it.next()) except StopIteration: return None end = self.first for item in it: end.set_next(Node(item)) end = end.succ def __iter__(self): """ Traverse the list. """ curr = self.first while curr is not None: yield curr.value curr = curr.succ def search(self, val): """ Return the node that contains the value val. If not found return None. """ curr = self.first # current node while curr is not None: if curr.value == val: return curr curr = curr.succ return None # val is not found. def insert(self, val, node=None): """Insert a node with the value val behind node in a singly linked list. If the node parameter is not specified, insert at the beginning of the list. """ if node == None: self.first = Node(val, succ=self.first) return right_node = node.succ new_node = Node(val, succ = right_node) node.set_next(new_node) def delete(self, node): """Delete node from the singly linked list l_list.""" if node == self.first: # check first if the node is first self.first = node.succ return # find predecessor pred = self.first while pred.succ is not node: try: pred = pred.succ except AttributeError: return # node is not in l_list, can't delete succ = node.succ # successor pred.succ = succ class ll_tests: """ >>> my_ll = linked_list(range(11)) >>> my_ll.search(3).value 3 >>> my_ll.search(3).succ.value 4 >>> my_ll.insert(3.5,my_ll.search(3)) >>> list(my_ll) [0, 1, 2, 3, 3.5, 4, 5, 6, 7, 8, 9, 10] >>> my_ll.insert(-1) >>> list(my_ll) [-1, 0, 1, 2, 3, 3.5, 4, 5, 6, 7, 8, 9, 10] >>> my_ll.delete(my_ll.search(3.5)) >>> list(my_ll) [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> my_ll.delete(my_ll.search(-1)) >>> list(my_ll) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ pass if __name__=="__main__": import doctest doctest.testmod()
true
c6fbba0a37904098a6326bb2e6fb2307c7c92dbd
benho25/Python-lessons
/Lesson_2_Variables_and_Assigment.py
2,896
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 23:09:49 2019 @author: cho01 """ """ Taken from : http://swcarpentry.github.io/python-novice-gapminder/02-variables/index.html" Use VARIABLES to store values. VARIABLES are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it. Here, Python assigns an age to a variable age and a name in quotes to a variable first_name. Variable names can only contain letters, digits, and underscore _ (typically used to separate words in long variable names) cannot start with a digit Variable names that start with underscores like __alistairs_real_age have a special meaning so we won’t do that until we understand the convention. """ age = 42 first_name = 'Ahmed' """ Use print() to display values. Python has a built-in function called print that prints things as text. Call the function (i.e., tell Python to run it) by using its name. Provide values to the function (i.e., the things to print) in parentheses. To add a string to the printout, wrap the string in single or double quotes. The values passed to the function are called arguments """ print(first_name, 'is', age, 'years old') """ kernel -> restart & run all """ # VARiables can be used in calculations age = age + 3 print ('Age in three years:', age) # INDEXING pythons counts from 0 atom_name = 'helium' print (atom_name[0]) """ A part of a string is called a substring. A substring can be as short as a single character. An item in a list is called an element. Whenever we treat a string as if it were a list, the string’s elements are its individual characters. A slice is a part of a string (or, more generally, any list-like thing). We take a slice by using [start:stop], where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want. Mathematically, you might say that a slice selects [start:stop). The difference between stop and start is the slice’s length. Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string. """ atom_name = 'sodium' print (atom_name[0:3]) print (atom_name[:7]) # count the number of elements print(len('sodium')) #It is important to help other people understand what the program does flabadab = 42 ewr_422_yY = 'Ahmed' print(ewr_422_yY, 'is', flabadab, 'years old') ''' Summary Use variables to store values. Use print to display values. Variables persist between cells. Variables must be created before they are used. Variables can be used in calculations. Use an index to get a single character from a string. Use a slice to get a substring. Use the built-in function len to find the length of a string. Python is case-sensitive. Use meaningful variable names. '''
true
7ac9f4bc649ba0cbcb1ddc877f36510863753680
atlisnaer98/mappa
/Q5.py
422
4.25
4
def palindrome(s): '''Returns True if the given string is a palindrome and False otherwise.''' s_clean = '' for ch in s: if ch.isalnum(): s_clean += ch.lower() return s_clean == s_clean[::-1] s = input("input a sentence: ") if palindrome(s) == True: print("""" """ + s + """" """ + " is a palindrome") else: print("""" """ + s + """" """ + " is not a palindrome")
false
93bae0bd446ec535c89bfd655367e43d58846778
refeed/StrukturDataA
/meet1/G_suit.py
913
4.21875
4
""" PETUNJUK MASUKAN Dua baris simbol yang terdiri dari dua karakter: [] = Kertas, () = Batu, 8< = Gunting. Baris Pertama adalah simbol yang dipilih Pak Blangkon dan baris kedua adalah simbol yang dipilih Pak Semar. PETUNJUK KELUARAN Pemenang suit. "Blangkon" atau "Semar" atau "Seri". """ blangkon = input().strip() semar = input().strip() BATU_STR = '()' GUNTING_STR = '8<' KERTAS_STR = '[]' BLANKGON_STR = 'Blangkon' SEMAR_STR = 'Semar' if semar == blangkon: print('Seri') elif semar == BATU_STR: if blangkon == GUNTING_STR: print(SEMAR_STR) elif blangkon == KERTAS_STR: print(BLANKGON_STR) elif semar == GUNTING_STR: if blangkon == KERTAS_STR: print(SEMAR_STR) elif blangkon == BATU_STR: print(BLANKGON_STR) elif semar == KERTAS_STR: if blangkon == BATU_STR: print(SEMAR_STR) elif blangkon == GUNTING_STR: print(BLANKGON_STR)
false
3996bd4e352096ea016488db92be2373f5718c25
dmkok/python3
/hw9.py
2,143
4.34375
4
""" Special Pythagorean triplet Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ import time start_time = time.time() print("Problem 9 - the product abc is: ",[(a*b*c) for a in range(190,450) for b in range(190,450) for c in range(190,450) if a**2+b**2==c**2 and a+b+c==1000][0]) print("calculating time for problem 9: %s seconds" % (time.time() - start_time)) """ Sum square difference Problem 6 The sum of the squares of the first ten natural numbers is, 1^2+2^2+...+10^2=385 The square of the sum of the first ten natural numbers is, (1+2+...+10)^2=55^2=3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025-385=2640 Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ print("Problem 6 - the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum: ",(sum(i for i in range(101))**2)-(sum(i**2 for i in range(101)))) """ Self powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 1010 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000 """ print("Problem 48 - the last ten digits of the series: ",(str(sum(i**i for i in range(1001)))[-10:])) """ Champernowne's constant Problem 40 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 """ new_list= "".join([str(i) for i in range(1,500000)]) print("Problem 40 - d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000= ", (int(new_list[0])*int(new_list[9])*int(new_list[99])*int(new_list[999])*int(new_list[9999])*int(new_list[99999])*int(new_list[999999])))
true
e11566cfe9a157ba4efbf7d865f07874eb0e79bd
alirezaaali/LearnPyhthon
/Begginer/Conditions_If_Elif_else.py
567
4.21875
4
''' Here is some useful methods You can find more information in https://www.w3schools.com/python/python_conditions.asp ''' a = input('Enter a:') a = int(a) b = 230 c = 330 if a > b: print('a is greater than b') elif a < b: print('b is greater than a') else: print(c) # This technique is known as Ternary Operators, or Conditional Expressions. # One line if else statement, with 3 conditions: print("a is greater than b") if a > b else print( "b is greater than a") if a == b else print("C") # to pass the if statement use pass if a > b: pass
true
bdfd26e542abccdfc231dcbc1311cb9af2728369
JHowell45/advent-of-code
/shared_functions.py
1,367
4.15625
4
"""Use the functions in this file in all of the other src files. This file contains the functions that will be used across all of the challenges and for every year. """ from os.path import abspath def generate_file_data(file_path: str): """Use this function to return the data a line at a time. This function is used for returning the data from the text file one line at a time, the data is being returned as generator. :param file_path: the path to the data file to use. """ with open(abspath(file_path), "r") as f: for line in f: yield line def banner(puzzle_title: str): """Use this function as a banner decorator for wrapping the puzzle answers. This function is used for decorating the functions for running the puzzle functions to help separate out the results and display the information. :param puzzle_title: the title for the banner. :return: the results of the wrapped function. """ title_length = len(puzzle_title) banner_length = 30 def dec(function): def func(*args, **kwargs): print("\n|{1}| {0} |{1}|\n".format(puzzle_title, "-" * banner_length)) result = function(*args, **kwargs) print("\n|{}|\n".format("-" * ((banner_length * 2) + title_length + 4))) return result return func return dec
true
a147d04d6f4fca70c8aa14cd2a3c93f8a8aceacd
theurikenneth/alx-higher_level_programming
/0x06-python-classes/1-square.py
345
4.375
4
#!/usr/bin/python3 """Defines the square class""" class Square: """Square class with size as private instance attribute""" def __init___(self, size): """Sets the initial size of the new square object Args: size (int): the size of the square once instance is created """ self.__size = size
true
5ccfe1fd4f2da0679182fa2079cc230fe1bd3269
kjohna/py-learning
/is_anagram.py
869
4.25
4
# determine if a string of any unicode char is anagram, case sensitive # change strings to lowercase for simple anagram testing def is_anagram(str1, str2): if len(str1) != len(str2): return 'False, not same length' tally = {} for char in str1: if char in tally: tally[char] = tally[char] + 1 else: tally[char] = 1 for char in str2: if char in tally: tally[char] = tally[char] - 1 else: return 'False, "' + char + '" exists in str2 but not str 1' for key in tally: if tally[key] > 0: return 'False, more "' + key + '" chars in str 1' elif tally[key] < 0: return 'False, more "' + key + '" chars in str 2' return True def main(): str1 = 'aB^09f' str2 = 'a0b9^9' print is_anagram(str1, str2) main()
true
1a662dd16a115e23ee17ded27769c4b3ea020d5b
arunsechergy/TSAI-DeepNLP-END
/assignments/assignment8/sample.py
524
4.3125
4
# write a python program to add two numbers num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(f'Sum: {sum}') # write a python function to add two user provided numbers and return the sum def add_two_numbers(num1, num2): sum = num1 + num2 return sum # write a program to find and print the largest among three numbers num1 = 10 num2 = 12 num3 = 14 if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print(f'largest:{largest}')
true
05e246b351f97fec7f423abb56c8b6597515a4d7
krish-1010/mycaptain
/stringcounter.py
514
4.15625
4
text = input("Please enter a string: ") def diction(x): dictionary = {} for txt in x: dictionary[txt] = 1 + dictionary.get(txt, 0) return dictionary def most_frequent(text): txts = [txt.lower() for txt in text if txt.isalpha()] dictionary = diction(txts) result = [] for key in dictionary: result.append((dictionary[key], key)) result.sort(reverse=True) for count, txt in result: print(txt,'=',count, end=' ') most_frequent(text)
true
c5c18efb59d0e6e979cf5d867d7d1ea25b7cd2d8
kill-gear/robust-algos
/interview-bit/binary_tree_from_inorder_and_postorder.py
1,805
4.125
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : list of integers # @param B : list of integers # @return the root node in the tree def buildTree(self, A, B): d = dict() # Dict is to store the indices of inorder elems # In inorder array, if any elem's index > than root/other element, # then that element is considered greater. # Using dict we can identify which elem is greater in O(1) time. for i in range(len(A)): d[A[i]] = i # since it is postorder, last elem is root # Reverse array B, or traverse from right to left real_root = TreeNode(B[-1]) B.reverse() # Call insert_tree() for all the susequent elements in postorder for item in B[1:]: self.insert_tree(real_root, item, d) return real_root def insert_tree(self, root, elem, d): node = root prev = node while node: place_value = d[elem] - d[node.val] prev = node # Element is larger than current node if place_value > 0: node = node.right # Element is smaller than current node elif place_value < 0: node = node.left # Create a new TreeNode with elem as its value. new_node = TreeNode(elem) # Prev holds the object at which node will be inserted node = prev # since node becomes None # Isert the element at correct position if d[node.val] > d[elem]: node.left = new_node elif d[node.val] < d[elem]: node.right = new_node
true
1d3dafe619095ff06d21cd5373822c86b1c5aa58
whomikedao/PythonExercises
/phonebookApp.py
1,585
4.125
4
def menu(): print(""" Electronic Phone Book ===================== 1. Look up an entry 2. Set an entry 3. Delete an entry 4. List all entries 5. Quit =====================""") def question(): menu() answer = int(input("What do you want to do (1-5)? ")) return answer def searchEntry(name): name = str(name) return phonebook.get(name) def setEntry(inputName, inputPhonenumber): name = str(inputName).lower() phonenumber = str(inputPhonenumber) phonebook[name] = phonenumber def deleteEntry(name): del phonebook[name] def listEntry(): for k, v in phonebook.items(): print("-----") print(k +":" + v) phonebook = {} session = True while session == True: answer = question() while answer != 5: if answer == 1: nameLookup = input("Who would you like to look for? ") nameLookupL = nameLookup.lower() print("Found entry for {}: {}".format(nameLookup, searchEntry(nameLookupL))) break elif answer == 2: name = input('Name: ') number = str(input('Phone Number: ')) setEntry(name, number) print("Entry stored for {}.".format(name)) break elif answer == 3: name = input('Who would you like to delete? ') nameL = name.lower() deleteEntry(nameL) print("Entry deleted for {}.".format(name)) break elif answer == 4: listEntry() break if answer == 5: session = False print("Bye")
true
8b5f9e45777406f3b5ef644e9efbcbfe037aa2df
atruslow/programming
/alex_answers/hackerrank/time_conversion.py
1,012
4.15625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'timeConversion' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def timeConversion(s): """ Given a time in -hour AM/PM format, convert it to military (24-hour) time. Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock. - 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock. """ hour = int(s[:2]) am_pm = s[-2:] middle_digits = s[2:-2] is_12 = hour == 12 is_am = am_pm == "AM" is_pm = not is_am if is_am and not is_12 or is_pm and is_12: return s[:-2] if is_am and is_12: return f"00{middle_digits}" hour = (hour+12) return f"{hour}{middle_digits}" if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = timeConversion(s) print(result) #fptr.write(result + '\n') #fptr.close()
true
550e1849ae588764b7776f561d7f2ee8a3d2b8e2
surjitchoudhary/hellogit
/listintro.py
2,268
4.46875
4
""" List are mutable Here we learn about making list""" list1=['surjit','mandeep','kuldeep','ramandeep','hello'] print(list1) #call by index print(list1[0]) print(list1[1]) print(list1[2]) print(list1[3]) print(list1[4]) #Below will give an error which is IndexError:list index out of range #print(list1[5]) #Now we try to print with negative number print('this is using minus(-)',end=" ") print(list1[-1]) print(list1[-2]) print(list1[-3]) print(list1[-4]) print(list1[-5]) ### another list in python mixed with numbers lets see what will happen list2=['my','name','surjit','singh','Roll No.',19,123.4] print(list2) print(list2[-2]*10) #so our above example succeed we can put numbers in list print(list2[-1]+34.4) # yes we can also add float value print(list2[1]+list2[3]) # we can also add strings in list ########################FUNCTION############################# #print(list2.sort()) #Above will produce an error can't sort numbers and strings numbers=[94,53,23,23,22,1,2,4,5] numbers.sort() print(numbers) # IT will make permanent changes to list numbers.reverse() print(numbers) #It will reverese the order in the string #####slicing###### numbers=[1,3,4,3,5,7,456,77,34,223,2,2] print(numbers[0:10]) print(numbers[:32]) print(numbers[2:4]) # above will print 2 and 3rd element print(numbers[::-2]) #first it will reverse the output than skip by 2 print(numbers[0:12:-1]) #now it will display empty list print(len(numbers)) # len() usage numbers.append('append') print(numbers) #it will add at the end """ #making an empty list and ask user to add the numbers i=0 emptylist=[] n=int(input("How many attributes you want to add in your list")) while i<n: emptylist.append(int(input('enter the number'))) i=i+1 print(emptylist) """ #you can add more number in the list by using 'insert' function list3=[1,2,3,4,5,6,7,8,9] list3.insert(1,1) print(list3) #for above example #insert(index,element) ###Remove### list3.remove(1) print(list3) #it will remove first element with the same name #it will give error if you submit something ###Pop### list4=[1,3,4,2,34,32,1,21] print(list4.pop()) print(list4) #if pop() is empty it will pop the last element #you can change the value of list till now list4[3]=234234 print(list4)
true
8526c980273ea2b82870234dc1993b5e1a4129ff
tuanvpham/DataStructureAlgoPrep
/tree_height_of_tree.py
2,551
4.15625
4
# https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/copy-from/99201341?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=trees class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) class BinarySearchTree: def __init__(self): self.root = None def create(self, val): if self.root == None: self.root = Node(val) else: current = self.root while True: if val < current.info: if current.left: current = current.left else: current.left = Node(val) break elif val > current.info: if current.right: current = current.right else: current.right = Node(val) break else: break # Enter your code here. Read input from STDIN. Print output to STDOUT ''' class Node: def __init__(self,info): self.info = info self.left = None self.right = None // this is a node of the tree , which contains info as data, left , right ''' def height(root): # print('this is root: ') # print(root) # print('left: ') # print(root.left) # print('end') left_height = 0 right_height = 0 if root.left: left_height = recursive(root.left) if root.right: right_height = recursive(root.right) # print('right height: ', right_height) # print('left height: ', left_height) if left_height + right_height == 0: return 0 return max(left_height, right_height) + 1 # return right_height + 1 def recursive(node): if node.right is None and node.left is None: # print('node has no left or right: ', node) return 0 if node.left is None and node.right: # print('node has no left, has right: ', node) return recursive(node.right) + 1 if node.right is None and node.left: # print('node has no right, has left: ', node) return recursive(node.left) + 1 # print('node has both left and right: ', node) # print('node.left: ', node.left) # print('node.right: ', node.right) return recursive(node.left) + recursive(node.right) + 1
false
8201c4b234681b282212a80bb70a33b5fddfef62
bisalex/algs4
/dynamic/strings.py
383
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def permutate(string, i=0): if i == len(string): return [''] subsequent = permutate(string, i + 1) permutations = [] for s in subsequent: for index in range(len(s) + 1): permutations.append(s[:index] + string[i] + s[index:]) return permutations def main(): print(permutate('abc')) if __name__ == '__main__': main()
false
dbe413ccee7a809c0b4a0b2f342ffe8c8c8f0bae
bisalex/algs4
/elementary-sorts/interview/dutch.py
2,784
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Dutch national flag. Given an array of N buckets, each containing a Color.Red, Color.White, or Color.Blue pebble, sort them by color. The allowed operations are: swap(i,j): swap the pebble in bucket i with the pebble in bucket j. color(i): color of pebble in bucket i. The performance requirements are as follows: At most N calls to color(). At most N calls to swap(). Constant extra space. """ from enum import Enum, unique @unique class Color(Enum): Red = 0 White = 1 Blue = 2 class Dutch(object): def __init__(self, seq): self.seq = seq self.color_count = 0 self.swap_count = 0 def swap(self, i, j): self.swap_count += 1 self.seq[i], self.seq[j] = self.seq[j], self.seq[i] def color(self, i): self.color_count += 1 return self.seq[i] def sort(self): i = j = 0 n = len(self.seq) - 1 while j <= n: color = self.color(j) if color == Color.Red: self.swap(i, j) i += 1 j += 1 elif color == Color.Blue: self.swap(j, n) n -= 1 else: j += 1 return self.seq def three_way_partition(seq, left, right): """ Three-way-partisions a sequence. Partitions a sequence of values consisting of three distinct different types of elements such that the resulting sequence is sorted. Loop invariants: 1. All values to the left of i are of type 'left' 2. All values to the right of n are of type 'right' 3. Values after j have not been looked at. 4. j <= n for all iterations. Makes at most N swaps. Arguments: seq (iterable): The sequence to partition. left: The first category, will end up on the left. right: The third category, will end up on the right. Returns: The sorted (three-way-partitioned) sequence. """ i = j = 0 n = len(seq) - 1 while j <= n: value = seq[j] if value == left: seq[i], seq[j] = seq[j], seq[i] i += 1 j += 1 elif value == right: seq[j], seq[n] = seq[n], seq[j] n -= 1 else: j += 1 return seq def partition(seq, left, middle, right, stop=False): i = 0 j = len(seq) - 1 while i < j: while i < j and seq[i] != right: i += 1 while j > i and seq[j] != left: j -= 1 seq[i], seq[j] = seq[j], seq[i] if not stop: a = partition(seq[:i], left, right, middle, True) b = partition(seq[i:], middle, left, right, True) return a + b return seq def main(): l = [Color.Red, Color.Blue, Color.White, Color.Red, Color.White, Color.Blue, Color.Red, Color.Red, Color.White, Color.Blue] dutch = Dutch(l[:]) print([i.value for i in dutch.sort()]) result = three_way_partition(l[:], Color.Red, Color.Blue) print([i.value for i in result]) result = partition(l[:], Color.Red, Color.White, Color.Blue) print([i.value for i in result]) if __name__ == '__main__': main()
true
3a95d0af049a6493c9bad52cb719cc4be77ad8c3
bisalex/algs4
/analysis/interview/bitonic.py
2,075
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Search in a bitonic array. An array is bitonic if it is comprised of an increasing sequence of integers followed immediately by a decreasing sequence of integers. Write a program that, given a bitonic array of N distinct integer values, determines whether a given integer is in the array. Standard version: Use ∼ 3lg(N) compares in the worst case. Signing bonus: Use ∼ 2lg(N) compares in the worst case (and prove that no algorithm can guarantee to perform fewer than ∼ 2lg(N) compares in the worst case). [1, 5, 10, 15, 20, 3, 2, 0] """ def find_boundary(sequence): if len(sequence) < 3: return -1 mid = len(sequence)//2 if (sequence[mid - 1] < sequence[mid] and sequence[mid + 1] < sequence[mid]): return mid elif sequence[mid - 1] < sequence[mid]: return find_boundary(sequence[mid:]) else: return find_boundary(sequence[:mid + 1]) """ First solution: def find(sequence, x, comp=lambda x,y: x < y): if not sequence: return False mid = len(sequence)//2 if sequence[mid] == x: return True elif comp(x, mid): return find(sequence[:mid], x, comp) else: return find(sequence[mid + 1:], x, comp) def bitonic(sequence, x): boundary = find_boundary(sequence) if find(sequence[:boundary], x): return True return find(sequence[boundary:], x, lambda x,y: x > y) """ def find(left, right, key): if not left and not right: return False if left: left_mid = len(left)//2 if right: right_mid = len(right)//2 if ((left and left[left_mid] == key) or (right and right[right_mid] == key)): return True if left: if key < left[left_mid]: left = left[:left_mid] else: left = left[left_mid+1:] if right: if key > right[right_mid]: right = right[:right_mid] else: right = right[right_mid+1:] return find(left, right, key) def bitonic(sequence, x): boundary = find_boundary(sequence) return find(sequence[:boundary], sequence[boundary:], x) def main(): l = [1, 2, 3, 4, 5, 3, 2, 1] print(bitonic(l, 5)) if __name__ == "__main__": main()
true
41bd9f61f6a79e7b682382b46e7782cd82cb2804
manojl711/demo
/Learning Python/pandas/Data School/02.py
1,212
4.40625
4
# select a pandas Series from a DataFrame # Pandas have 2 datatypes - dataframe and series # Series is one column of a dataframe # Dataframe is table with rows and cols import pandas as pd # read_table assumes tab seperated by cols # ufo = pd.read_table('data/ufo.csv',sep=',') ufo = pd.read_csv('data/ufo.csv') # read_csv is the shortcut to read comma seperated values print('\n') print(type(ufo)) print(ufo.shape) print(ufo.head()) # To select a series print(type(ufo['City'])) print(ufo['City'].head()) # Each column in a dataframe is created as an attribute of that dataframe # Hence we can access a series using a dor operator print(type(ufo.City)) print(ufo.City.head()) # How to create a new pandas series (eg. to create a new column that has both City and State print(ufo.City + ufo.State) # or for more readability print(ufo.City + ', ' + ufo.State) # Now if you think by using dot operator to create a new series, you are wrong # it will not work # the below statement gives error # ufo.Location = ufo.City + ', ' + ufo.State # For this to work, use [] braces ufo['Location'] = ufo.City + ', ' + ufo.State print('\n') print(ufo.shape) print(ufo.head())
true
631fc89a11407a9651af0b44f6a21427888902ef
thund3rstorm/python_solutions
/tcs-nqt/nqt2.py
571
4.15625
4
""" TCS Ninja | coding you are given a series like 0 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 ....can go upto N find the Nth term, or print upto Nth term index :- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 term :- 0 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 Even terms is multiple of 2 series.. Odd term is 0,1,2,3,4,5,6,7 """ def calc(n): ip = [] even = 0 odd = 0 for i in range(0,n): if i%2 == 0: ip.append(even) even += 2 elif i%2 != 0: ip.append(odd) odd += 1 return(ip) n = int(input("Enter the Nth term\n")) print(calc(n))
false
01264d6e8303ab857c1fe3260d418d9c916fc28f
thund3rstorm/python_solutions
/edabit/prc1.py
887
4.21875
4
# Generate a series, such that even position will be series # of Fibonacci series, and odd positions will be Prime Numbers. # Example :- [0, 2, 1, 3, 1, 5, 2, 7] # Take input N from user and print the series upto N. # Alternate number will be a prime number and a fibonacci series def fibonacci(n): if n<0 : print("Invalid") elif n == 0: return 0 elif n==1 : return 1 else: return fibonacci(n-1)+fibonacci(n-2) def prime(num): if num > 1: for i in range(2,num): if (num % i) == 0: break else: primes.append(num) else: pass n = int(input("enter N \n")) fibos = [] primes = [] final = [] for i in range(0,n): fibos.append(fibonacci(i)) prime(i) #print(fibos) #print(primes) for i in range(0,len(primes)): one = fibos[i] two = primes[i] final.append(one) final.append(two) print(final)
true
5bf2ebb86d0781f7b990724137e214466a51340c
thund3rstorm/python_solutions
/tcs-nqt/nqt3.py
548
4.34375
4
''' You are given a string, print the Nth term, or series upto Nth term 1,1,2,3,4,9,8,27,16,81,32,243,64,729,128,2187 first series : 1,2,4,8,16,32,64,128, --> 2 ^ (i++) series in even term second series : 1,3,9,27,81,243,729,2187 --> 3 ^ (i++)series in odd term ''' def compute(n): even = 0 odd = 0 series = [] for i in range(0,n): if (i%2 == 0): series.append(pow(2,even)) even += 1 elif (i%2 != 0): series.append(pow(3,odd)) odd += 1 return(series) n = int(input("Enter the N\n")) print(compute(n))
false
9ebf226a72a61ffa38a261547f37a6fda52286c8
RitRa/MPP---Assignment-2
/q8_print_array.py
585
4.3125
4
#8. Print an array Given an array of integers prints all the elements one per line. This #is a little bit different as there is no need for a ’return’ statement just to print and #recurse. # using recursion. def printArr(arr, N): # stopping the recursion when it gets to 0 if len(arr)== 0: return True else: # print value print(arr[0]) # continue recursion printArr(arr[1:], N) # array of values arr = [3, 4, 5, 6, 7] # calculating length of array N = len(arr)+1 # call the funtion ans =printArr(arr,N) # print print (ans)
true
c02e4a42f6fe45eb4090b12448806e0bcf981c85
rgsriram/Algorithms
/Others/find_non_duplicate.py
903
4.125
4
# def nonDuplicate(arr): # # for i in range(len(arr)): # # if arr[abs(arr[i])] >= 0: # arr[abs(arr[i])] = -arr[abs(arr[i])] # # for i in range(len(arr)): # if arr[i] < 0: # print arr[i] # # # nonDuplicate([12, 1, 12, 3, 12, 1, 1, 2, 3, 3]) def printRepeating(arr, n): # First check all the # values that are # present in an array # then go to that # values as indexes # and increment by # the size of array for i in range(0, n): index = arr[i] % n arr[index] += n # Now check which value # exists more # than once by dividing # with the size # of array for i in range(0, n): if (arr[i] / n) > 1: print i # Driver's code arr = [1, 6, 3, 150, 3, 100, 100] arr_size = len(arr) print ("The repeating elements are:") printRepeating(arr, arr_size)
false
c3473e881ca6ce57073b4195cd2c3454e323587d
Remnaut/math_definitions
/Chapter_2/Exercises/Exercise2_1.py
635
4.46875
4
""" Exercise 2.1 ------------------------------------------ Another Ball Dropped From a Tower ------------------------------------------ Function: The program finds the time it takes for the ball to reach the ground. Input: The user inputs the height of the tower. Output: The program outputs the time for the ball to reach the ground. """ # User inputs the height h = float(raw_input('Enter the height of the tower: ')) # Time taken to reach the bottom g = 9.81 #meters/seconds**2 t = (2*h/g)**(0.5) #seconds # Print the height based on user parameters print 'It takes', t, 'seconds to reach the ground.'
true
a8ba33f217ed73bc9b75cf9973478cfd3995d7ca
avikabra/idtech-python-tensorflow
/IDTECH - 2018/Monday - operators.py
268
4.125
4
'''print(5/2) print(2%3) print(3%2) // --> Integer Division ''' #int can also be around the input minimum = input("Enter the lower bound") maximum = input("Enter the upper bound") range = int(maximum) - int(minimum) range = range/2 print(int(minimum)+int(range))
true
ca79079238de783b2997acbdf5f87a6b308023c3
LucasRizzo/OOSD-2019-2020
/OOP/Week2/decimalToBinary.py
409
4.28125
4
# get input number_str = input("Please enter a decimal number to convert:") number = int(number_str) binary = "" # number = 12 // 2 = 6 // 2 = 3 // 2 = 1 # binary = "0011" # remainder = 0, 0, 1, 1 while number // 2 > 0: remainder = number % 2 binary = binary + str(remainder) number = number // 2 remainder = number % 2 binary = binary + str(remainder) binary = binary[::-1] print (binary)
true
2ec43aef845de71d6eccb91b26afbe90092a0e0d
LucasRizzo/OOSD-2019-2020
/OOP/Week5/Test1_3.py
2,346
4.5
4
import string def format_time(date_time): # Separate date and time by the space character # "21/02/2020 18:06:00" date, time = date_time.split() # Separate date by the / character. If the resulting number of elements is different than 3 # then date does not have the right number of parameters if len(date.split("/")) != 3: print ("Date has not correct number of parameters") return # Separate time by the : character. If the resulting number of elements is different than 3 # then time does not have the right number of parameters if len(time.split(":")) != 3: print ("Time has not correct number of parameters") return # Since we know we can split data, split it in three variables day, month, year = date.split("/") # Check whether days is between 1 and 31. Not checking leap years or if number of days match the month if not 1 <= int(day) <= 31: print("Days are wrong") return # Check whether month is between 1 and 12 if not 1 <= int(month) <= 12: print("Months are wrong") return # Check whether year is between 0 and 9999. 9999 could be changed if not 0 <= int(year) <= 9999: print("Year is wrong. Only values between 0 and 9999 accepted") return # Since time was checked it can be split in three variables hour, min, sec = time.split(":") # Check whether hour is between 0 and 23 if not 0 <= int(hour) <= 23: print("Hour is wrong") return # Check whether minutes is between 0 and 59 if not 0 <= int(min) <= 59: print("Minutes are wrong.") return # Check whether seconds is between 0 and 59 if not 0 <= int(sec) <= 59: print("seconds are wrong.") return # Print as required in the question line1 = "-> " + str(day) + "/" + str(month) + "/" + year line2 = "-> " + str(hour) + ":" + str(min) + ":" + sec line3 = "-> " + str(month) + "/" + year # Add am and change to pm if necessary line4 = "-> " + "a.m." if int(hour) > 11: line4 = "-> " + "p.m." print(line1) print(line2) print(line3) print(line4) # Main code and tests format_time("21/02/2020 18:06:00") print() format_time("37/05/1950 12:00:00") print() format_time("01/01/1900 25:06:00")
true
740e12f9fb5604c522f6f0710f4fe4f9ca2b2162
LucasRizzo/OOSD-2019-2020
/OOP/Week4/jumble.py
897
4.15625
4
import random # swap letters at index i and j # assume i<j, otherwise don't swap and print error message def swap_two_letters(string, i, j): if (i >= j): print("Problem with the index of letters to swap. Not swapped") return string return string[:i] + string[j] + string[i + 1:j] + string[i] + string[j + 1:] def jumble_word_once(string): length = len(string) if length <= 3: print("Word too short to jumble") return string i = random.randint(1, length - 2) j = random.randint(1, length - 2) while i >= j: i = random.randint(1, length - 2) j = random.randint(1, length - 2) s1 = swap_two_letters(string, i, j) return s1 def jumble_word(string): for i in range(0, 3): string = jumble_word_once(string) return string # main program s1 = "abracadabra" s1 = jumble_word(s1) print(s1)
true
ddd7e137965b7b29706cbbafdb75c4990016f081
lymilenea/amis_python71
/km71/Lukina_Milena/3/task4.py
464
4.125
4
apples = int(input("Введите кол-во яблок:")) students = int(input("Введите кол-во студентов:")) res1 = apples//students res2 = apples%students print("Количество яблок у каждого студента: " + str(res1), "\nКоличество яблок в корзине: " + str(res2)) print(input("Нажмите клавишу \"Enter\" для окончания работы программы"))
false
51868b8794e2e3f16db75a3319630ec9a8f40f46
gaodayue/algo_snippets
/longest-unique-substring/longest_unique_substr.py
1,387
4.125
4
# -*- coding:utf-8 -*- #! /usr/bin/env python ''' File: longest_unique_substr.py Author: gaodayue Description: Given a string, find the length of the longest substring without repeating characters. Example: longest_unique_substr('BBB') == 'B' longest_unique_substr('ABDEFGABEF') in ('ABDEFG', 'BDEFGA', 'DEFGAB') ''' def longest_unique_substr(s): cur_start, cur_len = (0, 0) max_start, max_len = (0, 0) # use hashmap to fast check character repeatness char_pos = {} # char_pos['a'] is the last index we see 'a' for i in xrange(len(s)): last_idx = char_pos.get(s[i], -1) if last_idx < cur_start: # encounter a new character or a character not in current substring cur_len += 1 else: # encounter a repeated character if cur_len > max_len: (max_start, max_len) = (cur_start, cur_len) cur_start = last_idx + 1 cur_len = i - cur_start + 1 char_pos[s[i]] = i if cur_len > max_len: (max_start, max_len) = (cur_start, cur_len) return s[max_start : max_start+max_len] if __name__ == '__main__': assert longest_unique_substr('') == '' assert longest_unique_substr('ABCA') in ('ABC', 'BCA') assert longest_unique_substr('BBB') == 'B' assert longest_unique_substr('ABDEFGABEF') in ('ABDEFG', 'BDEFGA', 'DEFGAB')
true
66942bbcfb328b2c5a9979f229bd6a39bf530942
haris-rizwan/Projects
/PycharmProjects/pythontutorial/Object_oriented/object_demo.py
698
4.15625
4
""" object oriented programming # """ # # # class car(object): # # def __init__(self, make,model,year,): # # self.make = make # # # __init__ command is like the constructe in python language # c1 = car("honda") # # print(c1.make) # class product(object): def __init__(self,name,quantity,color): self.name = name self.quantity = quantity self.color = color def getQuantity(self): return (self.quantity) def add(self,num): self.quantity=self.quantity + num p1 = product("shampoo",20,"yellow") p2 = product("salt",10,"white") # p1.add(40) # # print(p1.getQuantity()) # # p1.add(60) # # print(p1.getQuantity())
true
74249084175080987d3be2392de97fe507322a38
haris-rizwan/Projects
/PycharmProjects/pythontutorial/python_practice/python_questions.py
1,285
4.125
4
""" Write a sample program to print a string in a specefic format """ # # print("Twinkle, twinkle, little star,\ # \n\t\tHow I wonder what you are!\ # \n\t\t\t\tUp above the world so high, \ # \n\t\t\t\tLike a diamond in the sky. \ # \nTwinkle, twinkle, little star, \ # \n\t\tHow I wonder what you are") #write a program to print the version of python you are using # # import sys # # print(sys.version) #write a program to print date and time import time # print(time.strftime("%H:%M:%S")) # # print(time.strftime("%I:%M:%S")) # print(time.strftime("%d/%m/%y")) ################################################### #area of circle program # import math # # # Radi_circle=int(input("Please enter the desired radius:")) # # x=Radi_circle**2*math.pi # # print(x) # write a program that recives first and last name as input and prints them reverse # F_name = input("Your First Name: ") # L_name = input("Your Last Name: ") # # print(L_name + " "+ F_name) ### commaa seperated input will assign different indexes # values = input("Input some comma seprated numbers : ") # # list = values.split(",") # # print('List : ',list) a = int(input("Input an integer : ")) n1 = int( a ) n2 = int("%s%s" %(a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) print (n1) print(n2) print(n3)
true
72f284bea5c32c2dfa9b3122df453e9bd01f485f
AhmedRaafat14/Solutions-Of-Cracking-the-Coding-Interview-Gayle-5th-Edition
/Chapter 1/1-1.py
957
4.21875
4
""" Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? """ # First approach with Hash Map DS def check_unique_chars_using_map(s): uniq_chs = {} for ch in s: if ch in uniq_chs: return False uniq_chs[ch] = 1 return True # Second approach without any DS def check_unique_chars_without_map(s): for ch in s: if s.count(ch) > 1: return False return True # Another approaches def check_unique_using_list_set(s): if list(set(s)) == list(s): return True return False if __name__ == "__main__": print(check_unique_chars_using_map("ahmed")) print(check_unique_chars_using_map("aaahmed")) print(check_unique_chars_without_map("ahmed")) print(check_unique_chars_without_map("ahmmad")) print(check_unique_using_list_set("ahmed")) print(check_unique_using_list_set("aaahmed"))
true
51465dff1130048b5c853fbd785084f4de456a72
Klevtsovskyi/PythonAud1
/t07/t07_05_e1001.py
472
4.15625
4
def to_binary(n): if n == 0: return "0" binary = "" while n: bit = n % 2 n //= 2 binary = str(bit) + binary return binary def to_decimal(binary): decimal = 0 n = 1 for bit in binary[::-1]: decimal += int(bit) * n n *= 2 return decimal if __name__ == '__main__': A = input() B = input() a = to_decimal(A) b = to_decimal(B) c = a + b C = to_binary(c) print(C)
false
a4743fbb228df7643551dd75e51855b22b260531
nanihari/python_lst-tple
/count till last element is a tuple.py
327
4.125
4
##program to count the elements in a list until an element is a tuple. num=[10,20,30,(10,30),40] count=0 for n in num: if isinstance(n,tuple):##The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument). break count+=1 print(count)
true
2e7cfe422968e355e66261388dcdc00b37a014bf
ameer17x/phs_adventure
/engine.py
812
4.15625
4
import sys # Functions for PHS Adventure. def get_choice(choices): # This function takes in a dictionary of choices, # and returns the user's choice. # The dictionary has the form: # {'choice_token': 'choice text', } # The function forces the user to make one of the given choices, # or quit. print("\nWould you like to: ") for choice_token in choices: print("[%s]: %s" % (choice_token, choices[choice_token])) # Always offer the choice to quit. print("[q]: Quit.") choice_token = '' while choice_token not in choices.keys(): choice_token = input("\nWhat is your choice? ") choice_token = str(choice_token) if choice_token == 'q': print("Thanks for playing! Bye.") sys.exit() return choice_token
true
db44e71382cfae0e90dc0128aa7ff44c0133e6c8
shaikmujahed/DataStructures_and_Algorithms
/largest_continuous_sum.py
1,466
4.125
4
'''Largest Continuous Sum Problem Given an array of integers (positive and negative) find the largest continuous sum. Solution If the array is all positive, then the result is simply the sum of all numbers. The negative numbers in the array will cause us to need to begin checking sequences. The algorithm is,we start summing up the numbers and store in a current sum variable. After adding each element, we check whether the current sum is larger than maximum sum encountered so far. If it is, we update the maximum sum. As long as the current sum is positive, we keep adding the numbers. When the current sum becomes negative, we start with a new current sum. Because a negative current sum will only decrease the sum of a future sequence. Note that we don’t reset the current sum to 0 because the array can contain all negative integers. Then the result would be the largest negative number.''' def large_count_sum(arr): # check to see if length 0 if len(arr) == 0: return 0 # start the max and current sum at the first element max_sum = current_sum = arr[0] # for every element in array for num in arr[1:]: # set the current sum as the higher of the two current_sum = max(current_sum + num , num) # set the max as the heigher between the current sum and current max max_sum = max(current_sum, max_sum) return max_sum print(large_count_sum([1,2,-1,3,4,10,10,-10,-1]))
true
b164cbb4878bd328f2c5357fc1d4cf4a2d564cf9
koanzen/python_scripts
/data_structures.py
690
4.3125
4
import pprint #data structure organize and can represent real world objects #creating data structure for a tic tac toe game #for this data structure we will use the dictionary data dsboard = { 'ul':' ', 'um':' ', 'ur':' ', 'ml':' ', 'mm':' ', 'mr':' ', 'll':' ', 'lm':' ', 'lr':' ' } #This function will represent the data structure in a presentable view def showBoard(board): print(f"{board['ul']}|{board['um']}|{board['ur']}") print("-----") print(f"{board['ml']}|{board['mm']}|{board['mr']}") print("-----") print(f"{board['ll']}|{board['lm']}|{board['lr']}") print(showBoard(dsboard)) #prints the view of the data structure
false
374362f9cd594d2032991e2f0d77476201fe539d
koanzen/python_scripts
/num_guessing_game.py
579
4.21875
4
# this a guess a number game from random import randint name = input("What is your name: ") secretNum = randint(1,20) print(f"Well {name} I'm thinking a number between 1 and 20") for i in range(1,7): guess = int(input("Guess a number: ")) if guess < secretNum: print("Your number is lower than my number.") elif guess > secretNum: print("Your number is greater than my number.") else: break if guess == secretNum: print(f"{name} You guess my number in {i} guesses.") else: print(f"The number I was thinking is {secretNum}")
true
229f490333ae57fc036796106f96092abe4c0b0a
koanzen/python_scripts
/generator_and_iterator.py
652
4.125
4
lst = [1,2,3] def topten(): n = 1 while n <= 10: sq = n*n yield sq #yield is a keyword for a generator and a iterator is generated n +=1 vals = topten() #vals is a new iterator from a method yielded data vals2 = iter(lst) #vals2 is a new iterator from a list data print(vals2.__next__()) #beginning iterate the iteration data of the vals2 print(next(vals2)) #second iterate the iteration data of the vals2, using a next() method they are thesame as __next__ print("----------------------------------------------------------------") #use for loop to iterate through data yielded vals for i in vals: print(i)
true
8cf419d93eb0564e36a8b2ba49528ccf746a96f3
koanzen/python_scripts
/classes.py
1,087
4.15625
4
# some empty class class Person: pass # another class with constructor and functions class Point: #Constructor is defined in __init__ function def __init__(self, x, y): #variables inside __init__ are called instance variable self.x = x self.y = y def move(self): print("move") def draw(self): print("draw") point1 = Point(10,20) ##Can assign objects with value point1.x = 30 point1.y = 20 print(point1.x) point1.draw() #constructor point2 = Point(20,20) print(point2.x) # Set and Get Attributes from a variable to the Class object person = Person() first_key = 'first' first_val = 'Secret' # setting an attribute inside the class # using the value of a variable setattr(person, first_key, first_val) # check the created attribute # this will throw some linting problem in python cause first is not existent #print(person.first) # to solve the above linting problem we can use the getattr method first = getattr(person, first_key) print(first)
true
a8389b22d3e4c209d11d5f2b4e7ef92cba5ea7ad
RoanPaulS/For_Loop_Python
/chr_function.py
685
4.3125
4
print("Without chr function : "); for letter in range(65 , 91): print(letter,end=","); print(""); print(""); print("With chr function : "); for letter2 in range(65 , 91): print(chr(letter2),end=","); print(""); print(""); print("With chr function : "); for letter3 in range(ord('A'),ord('Z')+1): print(chr(letter3),end=","); print(""); print(""); print("With chr function : "); for letter4 in range(97 , 123): print(chr(letter4),end=","); print(""); print(""); print("With chr function : "); for letter5 in range(ord('a'),ord('z')+1): print(chr(letter5),end=","); """ chr function returns ascii value """
false
9b1ed1274baf8b05358690da6a729d8d79b2e607
KeelerNation/CIS1415CH8
/Chapter 8 problem 4.py
655
4.53125
5
my_dict = {'John': '55', 'Brian': '50', "Bob": '84', 'Bill': '92'} # prints the keys and values best used in a loop, there are also methods for just values and keys for key, values in my_dict.items(): print('Name: %s, Age: %s' % (key, values)) print('') #gets rid of a key value form the dictionary my_dict.pop('Bill') print(my_dict) print('') #adds onto the dictionary my_dict.update({'John Jr': '34'}) print(my_dict) print('') #turns the dictionary into a list value = list(my_dict.values()) key = list(my_dict.keys()) print(my_dict.values()) print(my_dict.keys()) print('') #turns two lists into dictionarys dict(zip(key, value)) print(my_dict)
true
3f50f66c631cfedac2e80bb80fe69f159e4bf99e
stepi777/pdb
/classCalculatorCA5.py
2,956
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 19 19:40:55 2018 @author: stepi77 """ import math class calculator(): def menu(): print(' 1 Addition\t 2 Subtraction\t 3 Multiplication\n 4 Division\t 5 Exponent\t 6 Square Root\n 7 Square\t 8 Cube\t\t 9 Sine\n 10 Cosine\t 11 Factorial\t 12 Tangent\n 13 Arc Tangent\t 14 Exit') def choice(): return int(input('Make your choice (between 1 and 14): ')) def askList(): def is_number(s): try: float(s) return True except ValueError: return False print('Type list of numbers. Press the letter a when finished') value = 0 sequence = [] while value != 'a': value = input('insert value: ') if is_number(value): sequence.append(float(value)) elif value != 'a': print('Please input only numers') return sequence def addition(a,b): add = list(map(lambda x,y: x+y, a,b)) return add def subtraction(a,b): sub = list(map(lambda x,y: x-y, a,b)) return sub def multiplication(a,b): mul = list(map(lambda x,y: x*y, a,b)) return mul def division(a,b): if b == 0: print('It is not possible to divide a number by zero') else: div = list(map(lambda x,y: x/y, a,b)) return div def powerOfTwo(a): def powerOf(a): return math.pow(a,2) power = list(map(powerOf, a)) return power def squareRoot(a): def squareRootFunction(a): return math.sqrt(a) values = (list(map(squareRootFunction, a))) return values def square(a): def squareFunction(a): return (float(a)*float(a)) values = (list(map(squareFunction, a))) return values def cube(a): def cubeFunction(a): return(float(a)*float(a)*float(a)) values = (list(map(cubeFunction, a))) return values def sine(a): def sineFunction(a): return(math.sin(a)) values = (list(map(sineFunction, a))) return values def cosine(a): def cosineFunction(a): return (math.cos(a)) values = (list(map(cosineFunction, a))) return values def fact(a): def factFunction(a): return (math.factorial(a)) values = (list(map(factFunction, a))) return values def tangent(a): def tangentFunction(a): return (math.tan(a)) values = (list(map(tangentFunction, a))) return values def arcTan(a): def arcTanFunction(a): return(math.atan(a)) values = (list(map(arcTanFunction, a))) return values
true
20adb711ad5fced4d1c3d46a08a01a4d7539b960
PatrycjaK/codewars-katas-python
/8-kyu/Reversed Words.py
333
4.34375
4
# Complete the solution so that it reverses all of the words within the string passed in. # Example: # reverseWords("The greatest victory is that which requires no battle") # // should return "battle no requires which that is victory greatest The" def reverseWords(s): x = s.split(" ") r = x[::-1] return ' '.join(r)
true
bca520aa4e7c10f8d26eebc19274982a41b9d62a
ilkera/EPI
/Queue/CircularQueue/CircularQueue.py
2,239
4.125
4
# Problem: Implement a circular queue # Circular Queue definition class CircularQueue: def __init__(self, capacity): self.capacity = capacity self.queue = [0] * capacity self.front = 0 self.rear = -1 self.count = 0 def enqueue(self, item): if not self.isFull(): self.rear = self.increment(self.rear) self.queue[self.rear] = item self.count += 1 return raise Exception("Queue is full") def dequeue(self): if not self.isEmpty(): popped = self.queue[self.front] self.front = self.increment(self.front) self.count -= 1 return popped raise Exception("Queue is empty") def first(self): if not self.isEmpty(): return self.queue[self.front] raise Exception("Queue is empty") def isEmpty(self): return self.count == 0 def isFull(self): return self.count == self.capacity def clear(self): self.count = 0 self.front = 0 self.rear = -1 def increment(self, index): if index + 1 == self.capacity: index = 0 else: index += 1 return index # Unit tests import unittest class CircularQueueTests(unittest.TestCase): def test_IsEmpty(self): cq = CircularQueue(5) self.assertEqual(cq.isEmpty(), True) def test_IsFull(self): cq = CircularQueue(3) cq.enqueue(1) cq.enqueue(2) cq.enqueue(3) try: cq.enqueue(4) except Exception as inst: print(inst) def test_CircularQueue(self): q = CircularQueue(5) q.enqueue(1) q.enqueue(2) q.enqueue(3) self.assertEqual(q.dequeue(), 1) self.assertEqual(q.dequeue(), 2) q.enqueue(4) q.enqueue(5) q.enqueue(6) q.enqueue(7) self.assertEqual(q.isFull(), True) self.assertEqual(q.dequeue(), 3) self.assertEqual(q.dequeue(), 4) self.assertEqual(q.dequeue(), 5) self.assertEqual(q.dequeue(), 6) self.assertEqual(q.dequeue(), 7) self.assertEqual(q.isEmpty(), True)
true
722f5ef1aede392265488b0a494610331f6c527a
ilkera/EPI
/LinkedList/MergeKSortedLists/MergeKSortedLists.py
1,310
4.1875
4
# Problem: Merge k sorted linked lists. # e.g. # list1 [1, 4, 7] # list2 [2, 6, 9[ # list3 [3, 5, 8] # Output = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Linked List class Node: def __init__(self, value, next = None): self.value = value self.next = next # Functions import heapq # Print Linked list def printList(head): if not head: print("Empty") return iterator = head while iterator: print("%d - " %iterator.value, end="") iterator = iterator.next print("") def merge(lists): if not lists: return None heap = [] for list in lists: heapq.heappush(heap, (list.value, list)) iterator = heapq.heappop(heap)[1] result = iterator if iterator.next: heapq.heappush(heap, (iterator.next.value, iterator.next)) while heap: current = heapq.heappop(heap)[1] iterator.next = current if current.next: heapq.heappush(heap, (current.next.value, current.next)) iterator = iterator.next return result # Main Program list1 = Node(1, Node(4, Node(7, Node(11)))) list2 = Node(2, Node(6, Node(9))) list3 = Node(3, Node(5, Node(8))) printList(list1) printList(list2) printList(list3) lists = [list1, list2, list3] merged = merge(lists) printList(merged)
false
c9396012b18355549b31b5f4d2edf4f1222a6932
ilkera/EPI
/Arrays/MultiplicationOfNumbers/MultiplicationOfNumbers.py
881
4.125
4
# Problem: Multiplication of numbers #There is an array A[N] of N numbers. # You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. # Solve it without division operator and in O(n). # For example Output[0] will be multiplication of A[1] to A[N-1] # and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. #Example: #A: {4, 3, 2, 1, 2} #OUTPUT: {12, 16, 24, 48, 24} def multiply(array): if not array: return None result = [1] * len(array) left, right = 1, 1 length = len(array) for index in range(0, len(array)): result[index] *= left result[length - index -1] *= right left *= array[index] right *= array[length - index-1] return result # Main program print(multiply([4, 3, 2, 1, 2])) print(multiply([4, 3, 2, 0, 2]))
true
9f4dba74ff346229ede15b0ea4374fcf9a93497f
E-Murajda/VariousChallenges
/euler/euler9.py
638
4.3125
4
'''Special Pythagorean triplet Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.''' n = 1000 def sp_pyth_triplet(n): for i in range(1, int(n / 3) + 1): for j in range(i + 1, int(n / 2) + 1): k = n - i - j if (i * i + j * j == k * k): print(i, ", ", j, ", ", k, sep="") print(i*j*k) return print("No Triplet") sp_pyth_triplet(n)
false
6d5e897d138ae2f99552e529977dab11284589b7
Kamesh-Bakshi/Tree-Traversals-
/Morristraversal.py
1,690
4.15625
4
class Node: def __init__(self,data): self.data = data self.left = None self.right = None def insert(self,data): temp = Node(data) if self.data: if data < self.data: if self.left is None: self.left = temp else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = temp else: self.right.insert(data) else: self.data = data # function for inorder order traversing without recursion or using stack def Morristraversal(root): cur = root while cur: #if left subtree exist if cur.left is None: print(cur.data) cur = cur.right else: #finding inorder predecessor pred = cur.left while pred.right is not None and pred.right != cur: pred = pred.right #linking root to inorder predecessor if pred.right is None: pred.right = cur cur = cur.left #breaking link between predecessor and root else: pred.right = None print(cur.data) cur = cur.right # example """ 20 / \ 15 52 / \ \ 7 18 78 """ root = Node(20) root.insert(15) root.insert(52) root.insert(78) root.insert(7) root.insert(18) Morristraversal(root) # Morristraversal => 7 15 18 20 52 78
true
f08791db04ece104de692bdb9069193aea0ba6c1
andyyvo/CS131
/ps6/ps6.py
2,091
4.46875
4
# Python code that checks if a set of sets 'p' (a list of sets in Python because Python does not allow for sets of sets) # is a partition of a set 's'. # 'p' is a partition of 's' if and only if the union of the elements 'p' is equal to 's' # and the intersection of any two elements of 'p' is an empty set. def are_parts_nonoverlapping(p): """ returns True iff the intersection of any two elements of 'p' is the empty set. """ for x in range(len(p)): for y in range(x+1,len(p)): if p[x].intersection(p[y]): return False return True def do_parts_contain_element(x, p): """ returns True iff the element 'x' is an element of some element 'p'. """ for a in range(len(p)): if x in p[a]: return True return False def do_parts_cover_set(s, p): """ returns True iff every element of 's' is in some element of 'p'. """ total = len(s) count = 0 for i in s: if do_parts_contain_element(i,p): count += 1 if count == total: return True else: return False def do_parts_have_nothing_extra(s, p): """ returns True iff every element of every element of 'p' is in 's'. """ for i in p: for j in i: if not j in s: return False return True def is_partition(s, p): """ return True iff 'p' is a partition of 's'. """ return are_parts_nonoverlapping(p) and do_parts_cover_set(s, p) and \ do_parts_have_nothing_extra(s, p) #print(are_parts_nonoverlapping([{0, 1}, {3, 5, 1}]))#false #print(do_parts_contain_element(3, [{0, 1}, {3, 5}]))#true #print(do_parts_cover_set({0,1,2,3,4}, [{0,5},{1,2},{3}]))#false #print(do_parts_have_nothing_extra({0,1,2,3,4,5},[{0,1},{2},{3,4,5}]))#true #print('\n') #s = {1,2,3,4,5,6} #p = [{1,4,5},{2,3},{6}] #p1= [{1,4},{2,3},{6}] #p2= [{1,4,5},{2,3},{6},{6}] #p3= [{1,4,5},{},{2,3},{6}] #print(is_partition(s,p))#true #print(is_partition(s,p1))#false #print(is_partition(s,p2))#false #print(is_partition(s,p3))#false
true
84e595644da1974bee3a7206f2049c1a33f7b4ff
ASim-Null/revision
/generate_phrase.py
2,024
4.59375
5
""" Create required phrase. ---------------------- ​ You are given a string of available characters and a string representing a word or a phrase that you need to generate. Write a function that checks if you cab generate required word/phrase using the characters provided. If you can, then please return True, otherwise return False. ​ NOTES: You can only generate the phrase if the frequency of unique characters in the characters string is equal or greater than frequency in the document string. ​ FOR EXAMPLE: ​ characters = "cbacba" phrase = "aabbccc" ​ In this case you CANNOT create required phrase, because you are 1 character short! ​ IMPORTANT: The phrase you need to create can contain any characters including special characters, capital letter, numbers and spaces. ​ You can always generate an empty string. ​ """ ​ ​ def generate_phrase(characters, phrase): for char in phrase: phrase_frequency = count_char_frequency(char, phrase) char_frequency = count_char_frequency(char, characters) if phrase_frequency > char_frequency: return False return True ​ ​ def count_char_frequency(char, target): f = 0 for c in target: if c == char: f += 1 return f ​ ​ ################################################### ​ # Test case 1 -- False ​ # characters = "odeC stFir slrG" # phrase = "Code First Girls" # # print(generate_phrase(characters, phrase)) ​ ################################################### ​ # Test case 2 -- False ​ # characters = "A" # phrase = "a" # # print(generate_phrase(characters, phrase)) ​ ################################################### ​ # Test case 3 -- True ​ # characters = "odeC stFir slrG" # phrase = "" # # print(generate_phrase(characters, phrase)) ​ ################################################### ​ # Test case 4 -- True ​ # characters = "aheaollabbhb" # phrase = "hello" # # print(generate_phrase(characters, phrase))
true
c9779b1d6f8b73c09a218f2971dc2ac9077b9e19
kodkoder/pforcs-problem-sheet
/bulletProof.py
2,209
4.1875
4
# bulletProof.py # Write a (bullet proof) function called averageTo(aList, toIndex) # The function should take in a list and an index. # The function will return the average of the numbers upto and including the toIndex in the aList. # When I say "bullet proof", I would like the function to always return an integer, even if a error occurs (say return -1), # but it will use logging to make a meaningful log warning, for any error that occurs (eg the aList contains an entry that is not a number/ toIndex is not valid, # there are many things that could go wrong) # Write the code to test all the things that could go wrong with this function, and a test to check the function does work. # The test code can be in the same file or different file. # # author: Tomasz import logging logging.basicConfig(level=logging.DEBUG) def averageTo(aList, toIndex): count = len(aList) total = 0 average = -1 # to compensate the index range # Check if toIndex is longer then the length of aList plus higher than 0 try: if (toIndex <= count) and (toIndex >= 0): try: for i in range(toIndex): total = total + aList[i] average = total / toIndex # Error for TypeError except TypeError: logging.debug("At least one of the entries in the list was not a number.") # Error for toIndex = 0 except ZeroDivisionError: logging.debug("Index appears to be 0, please ensure the index is no equal zero.") # negative index elif toIndex <=0: logging.debug("The index is below Zero.") # index longer than list else: logging.debug("The index is out of range.") # Exception for index out of range except TypeError: logging.debug("There was a problem with the index type.") # successfully ran function return average if __name__ == '__main__': assert averageTo([1, 2, 3, 4], 3) assert averageTo([1, 2, 3, 4], 0) assert averageTo([1, 2, 3, 4], 5) assert averageTo([1, 2, 3, 4],-4) assert averageTo([1, 2, 3, 4], 'x') assert averageTo([1, 2, 3, 'test'], 4)
true
b20997253ffd7056e8ff2834b1cccfc2b5af92c9
bardia-p/Simulations
/Projectile.py
879
4.1875
4
""" This program simulates a projectile. It takes the initial velocity, angle, and the coefficient of the friction and simulates its motion""" import time import math from compusic import * sc=initScreen(644,470) x=20 y=460 a=90 v=int(input("Enter a value for the velocity (in pixle/s) "))*10 t=int(input("Enter a value for the angle (0 to 90) ")) friction=float(input("Enter a value for the coefficient of friction (0 to 1)")) u=(t*(3.14))/180 vy=v*math.sin(u) vx=v*math.cos(u) g=-vy dt=0.01 while 1: checkQuit() circle(sc,(x,y),20,WHITE) y=y+(vy*dt) vy=vy+(a*dt) x=x+(vx*dt) if y>=450: vy=g*friction vx=vx*friction y=450 if x>=624: x=624 vx=vx*-1*friction if x<=20: x=20 vx=vx*-1*friction time.sleep(dt) updateScreen() clearScreen(sc)
true
12b35199553afa6ad379198820c63ff8b0e2e6c2
JmcRobbie/novaRoverDemos
/nova_rover_demos/utils/python_benchmarking/lib/module.py
1,644
4.46875
4
# The following codes for sorting algorithms are taken from GeekforGeeks # (https://www.geeksforgeeks.org/) # SAMPLE CODE # YOU CAN DELETE THIS # Function to do insertion sort def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n-1): # range(n) also work but outer loop will repeat one time more than needed. # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Implementation of Selection sort def selectionSort(arr): # Traverse through all array elements for i in range(len(arr)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(arr)): if arr[min_idx] > arr[j]: min_idx = j # Swap the found minimum element with # the first element arr[i], arr[min_idx] = arr[min_idx], arr[i]
true
bd39509d58a14911a5cf602d1beefd4a0589585b
LKY769215561/PythonCar
/PythonCar/venv/src/基础知识/函数/调用函数.py
464
4.1875
4
# -*- coding: UTF-8 -*- ''' 调用abs函数 ''' print(abs(100)) print(abs(-20)) print(abs(12.34)) ''' 调用max函数 ''' print(max(1,2)) print(max(2,3,1,-9)) ''' 数据类型转换 ''' print(int('123')) print(int(12.34)) print(float('12.34')) print(str(1.23)) print(str(100)) print(bool(1)) print(bool('')) ''' 请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串: ''' n1 = 255 n2 = 10000 print(hex(n1)) print(hex(n2))
false
8e6e532e3af73c0c4869d9a838e2b9807ef97b74
xiayun666/AID1909
/one_day/11-输入.py
673
4.40625
4
# 主要学习python3.x的输入 # python3.x程序的输入使用的input # input 得到的结果是字符串类型 my_name = input("请输入您的名字:") # 输入年龄 my_age = input("请输入您的年龄:") # <class 'str'> print(type(my_age)) # 小明 22 # 如果想通过打印完成多个变量的输出 print(变量名1, 变量名2, ....) # print(my_name, my_age) # 名字:小明 年龄:22岁 print("名字:%s 年龄:%s岁" %(my_name, my_age)) # python2.x 了解 # python2.x中的raw_input 等价于 python3.x中的input 无论输入是什么类型 最终都是字符串 # python2.x中的input 对应的变量类型是看用户的数据类型
false
831410c5c44f0183d054e7924ccab572299182eb
Cloudb2020/AWS-restart
/strings.py
441
4.1875
4
# The String Data Type myStr = "This a string" print(myStr,"\n",type(myStr)) print(myStr,"is of data type",type(myStr)) # String Concatenation str1, str2 = "water", "fall" str3 = str1 + str2 print(str3) # Input String name = input("What is your name? ") print(name) # Format Output String color = input("What is your favorite color? ") animal = input("What is your favorite animal? ") print("{}, you like a {} {}!".format(name,color,animal))
true
d5cd1b5e5ab418738eef0a4a798c9da874967011
fdima/GB-algAndStructData
/HW1/task1.py
1,793
4.25
4
# Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6. Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака. Объяснить полученный результат. print("5 and 6 is %d" % 5 and 6) print("Оператор 'and' инициирует проверку операндов \ \nсначала слева, потом справа (если приведенный \ \nк булевому значению операнд слева вернул True). \ \nB т.к. и 5 и 6 при приведении дают True, \ \nвыражение возвращает второй операнд - 6\n") print("5 or 6 is %d" % 5 or 6) print("Оператор 'or' инициирует проверку операндов \ \nсначала слева, потом справа (если приведенный \ \nк булевому значению операнд слева вернул False). \ \nB т.к. и 5 и 6 при приведении дают True, \ \nвыражение возвращает первый операнд - 5'\n") print("not 5 is %s" % str(not 5)) print("5 приводится к True, значит результат выражения - False\n") print("not 6 is %s" % str(not 6)) print("Аналогично.\n") print("5 xor 6 is %d" % (5 ^ 6)) print("Опранд xor выполняется на битах, а значит\ \n5 -> 101\n6 -> 110\n101 xor 110 = 011 -> 3\n") print("5 >> 2 is %d" % (5 >> 2)) print("5 -> 101\n101 >> 2 = 1 -> 1\n") print("5 << 2 is %d" % (5 << 2)) print("5 -> 101\n101 << 2 = 10100 -> 20\n")
false
b4104f720c0891b5eb0ad150de907ad49c36b75b
fdima/GB-algAndStructData
/HW7/task1.py
728
4.3125
4
""" 1. Отсортировать по убыванию методом «пузырька» одномерный целочисленный массив, заданный случайными числами на промежутке [-100; 100). Вывести на экран исходный и отсортированный массивы. """ def bubble_sort(array): n = len(array) while n > 0: for i in range(1, n): if array[-i] > array[-(i + 1)]: array[-i], array[-(i + 1)] = array[-(i + 1)], array[-i] n -= 1 return array import random array = [random.randint(-100, 99) for _ in range(10)] print(f'source: {array}') print(f'sorted: {bubble_sort(array[:])}')
false
4b727e8b363859c0130af044c2bad02cd848a398
GoblinDynamiteer/pyt_cfb_book
/Övning 14.2/remove_last.py
930
4.21875
4
# -*- coding: latin-1 -*- from sys import stdin #From book 'C frn brjan' #vning 14.2, Sida 348 #Lgg till i modulen 'array_list': en funktion 'remove_last', som tar bort det sista elementet. #Funktionen ska returnera en pekare till det borttagna elementet om det gick bra, annars NULL. list = []; #creates empty list print("Skriv in heltal: ") for line in stdin: print("Skriv in heltal (avsluta med ctrl+z): ") list.append(int(line)) #float(x) converts string x to float print("Antal element i listan:", len(list)) #len(x) gets number of elements in list x for i in range(len(list)): #range(x) returns a list of integers from 0 to x print("Sista vrdet i listan:", list[len(list)-1]) #list[x] returns element x in list print("Tog bort sista vrdet i listan: ", list.pop()) # list.pop() removes and returns the last element in list #more on range #http://pythoncentral.io/pythons-range-function-explained/
false
98214a103ed1a19c0753ecf05e1a58738e729509
abhisoniks/Leetcode
/Data-Structure/stack.py
461
4.15625
4
# Creating a stack class stack: def __init__(self): self.stack = [] # Adding items into the stack def push(self, item): self.stack.append(item) print("pushed item: " + item) # Removing an element from the stack def pop(self): if (self.check_empty()): return "stack is empty" return self.stack.pop() def check_empty(self): return True if len(self.stack)==0 else return False
true
ee631be6c953d164cfe17dc1f40f9c9a27346feb
Doviman/conversion_program
/converion_program.py
260
4.25
4
# 1 cup = 250 ml def convert(cups): ml =round(float(cups) * 250) return ml print ("This program will convert cups to ml") cups = raw_input("how many cups? ") milliliters = convert(cups) print (cups + " cups is equal to " + str(milliliters) + " ml")
true
983a54089c16b8a1fbae39dbee74a33a2f3719c9
gdhGaoFei/Python01
/20181201001/数据类型/基本数据类型及运算符/Hello.py
1,953
4.25
4
print("Hello Python one World") ''' 变量命名规范:只能由字母、数字、下划线组成 首字母不能是数字 不能以关键字 多以驼峰命名规则 数据类型?数据类型就是 不同的盒子放不同的物品 那么物品就是数据,盒子就是指的一块内存地址 1. 基本数据类型:整型、浮点型、布尔型 2.字符串 3.列表 4.元组集合Set 5.集合 6.字典 ''' # 声明一个变量 firstNumber = 1 print(firstNumber) print(type(firstNumber))#整数类型 secondNumber = 8.0 print(secondNumber) print(type(secondNumber))#浮点类型 #布尔型 thirdNumber = False print(thirdNumber) print(type(thirdNumber))#bool 型数据 ''' 基本运算符 加+ 减— 乘* 除/ ''' first1 = 5 first2 = 6 result1 = first1+first2 print(result1)#加 print(first2-first1)#减 print(first1*first2)#乘 print(first1/first2)#除 print(type(first1/first2))#类型 浮点型 ''' 算术运算符 ''' #取模运算 求余数 i1 = 10 j1 = 3 z = i1%j1 print(z) #幂运算 print(j1**i1) #取整除运算 print(i1 // j1) ''' 赋值运算符 ''' #加等于 减等于 除等于 乘等于 求余等于 求幂等于 取整等于 i = 1 i /= 5 print(i) ''' 进制等于 十进制 二进制 八进制 十六进制 ''' #十进制 转化成其他的进制 # 十进制转化成二进制 i = 16 j = bin(i) print(j) # 十进制转成八进制 print(oct(i)) # 十进制转成十六进制 print(hex(i)) # 二进制转成十进制 i = "10" print(int(i, 16)) ''' ''' # 按位与运算 & 两个值相对应的位置都是1为 -> 1 # 按位或运算 | 两个值相对应的位置一个为1即是1 # 按位异或运算 ^ 两个值相对应的位置不同则是1 # 按位取反运算 ~ 对应的值取反-1 # 左移运算符 << # 右移运算符 >> ''' 条件控制 比较运算符 == if 条件: 语句 else: 语句 --------- if 条件: 语句 elif 条件: 语句 ... else: 语句 '''
false
64837cafafd1b67e02a1a7b444778b148612e8af
ryanhalabi/2015-Python
/HW2/random_walk.py
2,099
4.25
4
''' A two-dimensional random walk simulator and animator. ''' # The turtle package is part of Python's standard library. It provides some # very primitive graphics capabilities. For more details see # # https://docs.python.org/3/library/turtle.html # import turtle import numpy as np def random_walk(n, x_start=0, y_start=0,P = None ): ''' Simulate a two-dimensional random walk. Args: n number of steps Returns: Two Numpy arrays containing the x and y coordinates, respectively, at each step (including the initial position). ''' if P != None: if (sum(P) != 1) | (len(P) != 4) : raise ValueError('p does not have length 4!') x =0 y =0 z = np.zeros([n,2]) zz = np.zeros([n,2]) A = np.array([0,1,2,3]) for i in range (1,n): dir = np.random.choice( A,replace = True, p = P) if dir == 0: z[i,0] = 1 if dir == 1: z[i,0] = -1 if dir == 2: z[i,1] = 1 if dir == 3: z[i,1] = -1 xx = np.cumsum(z[:,0]) yy = np.cumsum(z[:,1]) zz[:,0] = xx + x_start zz[:,1] = yy + y_start x = sum(z[:,0]) y = sum(z[:,1]) x = x+x_start y = y+y_start print(x , y) print(zz) return zz # Notice that the documentation automatically shows up when you use ? def draw_walk(x, y, speed = 'slowest', scale = 20): ''' Animate a two-dimensional random walk. Args: x x positions y y positions speed speed of the animation scale scale of the drawing ''' # Reset the turtle. turtle.reset() turtle.speed(speed) # Combine the x and y coordinates. walk = zip(x * scale, y * scale) start = next(walk) # Move the turtle to the starting point. turtle.penup() turtle.goto(*start) # Draw the random walk. turtle.pendown() for _x, _y in walk: turtle.goto(_x, _y) P = [.35,.15,.45,.05] a = random_walk(1000) draw_walk( a[:,0], a[:,1])
true
d5eb7798bcc226b2d53f9ccf6484cd39c67e0754
AJLightfoot/hello-world
/CH4-Min-Max-Sum.py
802
4.21875
4
for value in range(1,6): print(value) numbers = list(range(1,6)) print(numbers) even_nums = list(range(2,11,2)) print(even_nums) squares = [] for value in range(1,11): squares.append(value**2) print(squares) digits = [1,2,3,4,5,6,7,8,9,0] print(min(digits)) print(max(digits)) print(sum(digits)) #list comprehension allows creating the list for squares as example into one line of code squares = [value**2 for value in range(1,11)] print(squares) for value in range(1,6): print(value) nums = list(range(1,1000001)) print(min(nums)) print(max(nums)) print(sum(nums)) odds = list(range(1,10,2)) print(odds) cubes=[] for value in range(1,10): cubes.append(value**3) print(cubes) cubes = [value**3 for value in range(1,10)] print(cubes)
true
9abccf758aafd2afe5fe36038c7bd207dbf22240
william19-meet/meet2017y1lab4
/fruit_sorter.py
233
4.28125
4
newfruit = input(' what is your fruit? ') if newfruit == 'Apples': print('bin1') elif newfruit == 'Oranges': print('bin2') elif newfruit == 'Olives': print('bin3') else: print('Error! I do not recognise this fruit!')
false
58841b77a8929e9c3ae2e2ca510220425ebf8f5e
hasanibnmansoor/PythonLearning
/flatten_list.py
1,194
4.25
4
def count_of_leaf(arr: list) -> int: count = 0 for item in arr: if not isinstance(item, list): count += 1 else: count += count_of_leaf(item) return count def flatten_list_recursive(arr: list) -> None: flattened = [] for item in arr: if not isinstance(item, list): flattened.append(item) else: flattened.extend(flatten_list_recursive(item)) return flattened def flatten_list_iterative(arr: list) -> None: flattened = [] while arr: if not isinstance(arr[0], list): flattened.append(arr.pop(0)) else: l = arr.pop(0) arr = l + arr return flattened if __name__ == "__main__": nested_list = [ 1, [2, 3, 4], [5, 6, [7, 8, [9, 10]]], 11, [12, 13, [14, 15, 16, [17, [18, 19, [20, 21, [22, 23, [24, [25, [26]]]]]]]]], ] print(f"Length of Nested List: {len(nested_list)}") print(f"Number of Leaf elements: {count_of_leaf(nested_list)}") print(f"Flattened List: {flatten_list_recursive(nested_list)}") print(f"Flattened List: {flatten_list_iterative(nested_list)}")
true
8b3b3d3d3eb1d6afd54d8c3d9e89efe5e5f6bf28
Foreman1980/GitRepository
/GeekBrains/01 Основы языка Python/Basics_lesson_4.2.py
341
4.34375
4
# 2: Создайте функцию, принимающую на вход 3 числа и возвращающую наибольшее из них. def max_number(n1, n2, n3): numbers_list = [] for i in n1, n2, n3: numbers_list.append(i) return max(numbers_list) print(max_number(5, 2, 3)) # Вывод вида - "5"
false
2a3f17534cb1ba583f751fbdb483e8553da6f1c5
githubgrk/python-examples
/intro/iterations.py
2,506
4.40625
4
print("__________________________Iterating Through an Iterator next()__________________________________") # define a list my_list = [4, 7, 0, 3] # get an iterator using iter() my_iter = iter(my_list) # iterate through it using next() # Output: 4 print(next(my_iter)) # Output: 7 print(next(my_iter)) # next(obj) is same as obj.__next__() # Output: 0 print(my_iter.__next__()) # Output: 3 print(my_iter.__next__()) # This will raise error, no items left # next(my_iter) print("__________________________Printing sum till 20 using while() loop_______________________________") a = 10 # Initialization while a <= 20: # Condition -- used for linkedList or DB queries.When you do not know when to exit print(a) a = a + 2 # Increment print("__________________________Printing sum till 20 using while() with else loop____________________") x = 1 while (x < 5): print('inside while loop value of x is ', x) x = x + 1 else: print('inside else value of x is ', x) print("__________________________for loop_____________________________________________________________") # for loop - when both initial and termination condition is known to us, e.g. iterating collectionz for c in range(1, 10): print(c) print("__________________________for loop using list________________________________________________") lang = ("Python", "C", "C++", "Java") for i in range(len(lang)): print(lang[i]) print("__________________________for loop using list________________________________________________") a_list = ["a", "b", "c", "d"] for iteration, item in enumerate(a_list): if iteration == 2: break else: print(iteration, item) print("_________________________Building Custom Iterators____________________________________________") # Building an iterator from scratch is easy in Python. # We just have to implement the __iter__() and the __next__() methods class PowTwo: """Class to implement an iterator of powers of two""" def __init__(self, max=0): self.max = max def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.max: result = 2 ** self.n self.n += 1 return result else: raise StopIteration # create an object numbers = PowTwo(3) # create an iterable from the object i = iter(numbers) # Using next to get to the next iterator element print(next(i)) print(next(i)) print(next(i)) print(next(i)) # print(next(i))
true
63323aa88c3322de4c3163a24748de049597ff3a
OmarMohammed92/Learning_Python
/Notes Lessons From [ 019 ] To [ 020 ].py
678
4.5
4
# --- Numbers --- # Integer print(type(10)) print(type(100)) print(type(-10)) print(type(-110)) # Float print(type(1.500)) print(type(-1.500)) print(type(0.990)) print(type(1000.590)) # Complex print(type(5+6j)) myComplexNumber = 5+6j print("Real Part is: {}".format(myComplexNumber.real)) print("Imaginary Part is: {}".format(myComplexNumber.imag)) # [1] You can convert from Int to Float or Complex # [2] You can convert from Float to Int or Complex # [3] You can not convert from Complex to any type print(100) print(float(100)) print(complex(100)) print(10.50) print(int(10.50)) print(complex(10.50)) print(5+6j) # print(int(5+6j)) # This is an error convertion
true
79ec4acaa47c21aeea70bbd965413efb65dec2c4
gitchrisadams/LibraryCommonTasks2
/Python/AlgorithmsCS/recursion_palindrome.py
243
4.25
4
# Example of using recursion to detect palindrome def palindrome(word): if len(word) <= 1: return True if word[0] != word[-1]: return False word = word[1:-1] return palindrome(word) print(palindrome('racecar'))
false
5a8f824678ca739dd16cccac0a4befa9787923a1
gitchrisadams/LibraryCommonTasks2
/Python/ClassesOOP/classInheritanceOOPEx2.py
829
4.21875
4
#!/usr/bin/python3 # Christopher Adams # date here. # Code description here. # Imports import sys # Create base/super/parent class: class Animal: def talk(self): print("I have something to say") def walk(self): print("Hey! I'm walking here!") def clothes(self): print("I have nice clothes.") # Inherits from Animal class: class Duck(Animal): def quack(self): print("Quaaaack!") # Call the super classes walk function. (The Animals walk function) # After that is output, Walks like a duck still displays. def walk(self): super().walk() print("Walks like a duck.") class Snuffalupokus(Animal): def walk(self): print("Snuffy be walking!") def main(): donald = Duck() donald.quack() donald.walk() snuffy = Snuffalupokus(); snuffy.walk() print("Snuffy:") snuffy.talk() if __name__ == '__main__': sys.exit(main())
true
3c6d9c98212ccb6d05a3af0fc9adbf88eb221ff4
dukedududu/hanshu-de-yun-yong
/yuanzu.py
1,785
4.28125
4
''' #直接赋值与浅拷贝 深拷贝 dict1={'name':('jack','mike'),'age':(12,23),'from':('china','african')} dict2=dict1 dict3=dict1.copy() print(dict1) print(dict2) print(dict3) dict1['name']='fan' print(dict1)#原来的jack mike被新给的'fan'覆盖了 print(dict2)#直接赋值的dict2的值也被改变了 print(dict3)#浅拷贝的值还是原来的值 没有改变 ''' ''' import copy a=[1,2,3] b=a#直接赋值 c=a.copy() d=copy.deepcopy(a) a.append(4) print(a) print(b)#直接赋值和原始列表变了 print(c) print(d)#浅拷贝 和深拷贝都木有变 ''' ''' import copy#用深拷贝需要使用copy模块 a=[1,2,3,['a','b']] b=a#直接赋值 c=a.copy()#浅拷贝 d=copy.deepcopy(a)#深拷贝 a[3].append('c') a.remove(2) print(a) print(b)#直接赋值和原函数一起同步改变 print(c)#浅拷贝的子对象''['a','b']''改变了 print(d)#深拷贝不受影响和原来的a一样 ''' ''' a=[1,3,4,[1,2,3,4],'c'] #如何向子对象中加入元素??? #list中可以添加元素的函数 a.append(5) #append用于在列表末尾 只接受一个参数 参数可以是任何数据类型,被追加的元素在List中保持着原结构类型。 print(a) a.insert(3,5) #insert相比较append可以指定位置插入元素在列表中 print(a) b=['a','b'] a.extend(b)#将一个列表中每个元素分别添加到另一个列表中,只接受一个参数。 print(a) ''' a=[1,3,4,[1,2,3,4],'c'] #可以删除List中元素的函数 #pop 和del 除格式有啥不同 ''' a.remove([1,2,3,4]) #remove函数是可以指定删除存在list中的元素 没有指定元素会报错 print(a) del a[3] print(a) #del 是靠位置删除元素的 与remove指定不同 a.pop() print(a) #pop()默认弹走最后一个数,和del一样靠索引弹元素 '''
false
1e62c472b562a30cf42f1be049425df9e35ce1c8
danny135/MIT-6.00.1x
/Final Exam/frob.py
2,234
4.1875
4
# -*- coding: utf-8 -*- class Frob(object): def __init__(self, name): self.name = name self.before = None self.after = None def setBefore(self, before): self.before = before def setAfter(self, after): self.after = after def getBefore(self): return self.before def getAfter(self): return self.after def myName(self): return self.name def __str__(self): return self.name def __repr__(self): return self.name def insert(atMe, newFrob): """ atMe: a Frob that is part of a doubly linked list newFrob: a Frob with no links  This procedure appropriately inserts newFrob into the linked list that atMe is a part of. """ before = atMe.getBefore() after = atMe.getAfter() if atMe.name < newFrob.name: if after == None: atMe.setAfter(newFrob) newFrob.setBefore(atMe) elif newFrob.name < after.name: atMe.setAfter(newFrob) newFrob.setBefore(atMe) newFrob.setAfter(after) after.setBefore(newFrob) else: insert(after, newFrob) elif newFrob.name < atMe.name: if before == None: newFrob.setAfter(atMe) atMe.setBefore(newFrob) elif before.name < newFrob.name: before.setAfter(newFrob) newFrob.setBefore(before) newFrob.setAfter(atMe) atMe.setBefore(newFrob) else: insert(before, newFrob) else: if before == None: newFrob.setAfter(atMe) atMe.setBefore(newFrob) else: before.setAfter(newFrob) newFrob.setBefore(before) newFrob.setAfter(atMe) atMe.setBefore(newFrob) eric = Frob('eric') andrew = Frob('andrew') ruth = Frob('ruth') fred = Frob('fred') martha = Frob('martha') danny = Frob('danny') bob = Frob('bob') jeff = Frob('jeff') john = Frob('john') jeb = Frob('jeb') frobs = [eric, andrew, ruth, fred, martha, danny, bob, jeff, jeb, john, jeb] for frob in frobs [1:]: insert(eric,frob) frob = andrew while frob != None: print frob frob = frob.getAfter()
true
09f2cbfbd54129c32fe69753152d3dc6c4fd0e33
sonadarshan/Python_basic_programs
/venv/directory_basic.py
693
4.15625
4
from pathlib import Path print("1.Search for all the files with extensions(*,*.txt,*.py)\n2.Create a directory\n3.Remove direcetory") try: n=int(input('Enter your choice : ')) except ValueError: print("Enter the number properly") exit(0) if n == 1: p = Path() inp = input("Enter the extension : ") for file in p.glob(inp): print(file) elif n == 2: inp = input("Enter the name of new directory") p1 = Path(inp) if p1.exists(): print('Directory already exists') else: p1.mkdir() print("Directory created") else: inp = input("Enter the name of directory") p = Path(inp) p.rmdir() print('Directory removed')
true
85ea5d9fbbfa388d9d75c5db715004c1c719fa92
yuraratu/Udacity_IntroToComputerScience
/Lesson 6 How to Have Infinite Power/Lesson 6.1.4 Faster Fibonacci.py
794
4.28125
4
# Define a faster fibonacci procedure that will enable us to computer # fibonacci(36). def fibonacci(n): if n == 0 or n == 1: return n else: last = 1 before_last = 0 i = 2 while i <= n: before_last, last = last, last + before_last i += 1 return last # def fibonacci(n): # current = 0 # after = 1 # for i in range(0, n): # current, after = after, current + after # return current print(fibonacci(36)) # >>> 14930352 # import time # # start = time.clock() # # for i in range(0, 250): # print(int(time.clock() - start), i, fibonacci(i)) mass_of_earth = 5.9722 * 10 ** 24 mass_of_rabbit = 2 n = 1 while fibonacci(n) * mass_of_rabbit < mass_of_earth: n += 1 print(n, fibonacci(n))
false
2d914843130d93a7c44061b37225b8515b4fd63b
kyleclo/practice
/binary-conversion/binary-conversion.py
1,655
4.28125
4
""" Binary conversion to/from Decimal """ def decimal_to_binary(integer): """ Integer 11 has binary representation '1011'. To check, '1011' => 2^(4-1) + 2^(2-1) + 2^(1-1) = 8 + 2 + 1 = 11. 1. 11 / 2 = 5 remainder 1. Hence, the right-most binary digit is '1'. 2. 5 / 2 = 2 remainder 1. Hence, left-append '1' to obtain '11'. 3. 2 / 2 = 1 remainder 0. Hence, left-append '0' to obtain '011'. 4. 1 is left, so left-append '1' to obtain '1011'. """ if integer < 0: return None elif integer == 0: return integer else: string = '' while integer / 2 > 0: string = str(integer % 2) + string integer = integer / 2 string = '1' + string return int(string) def decimal_to_binary_recursive(integer): if integer < 2: return str(integer % 2) return decimal_to_binary_recursive(integer / 2) + str(integer % 2) def binary_to_decimal(binary): """ Again, integer 11 has binary representation '1011'. 1. Right-most digit '1' contributes +1 = +2^k where k = 0 2. Next digit '1' contributes +2 = +2^k where k = 1 3. Next digit '0' contributes nothing 4. Last digit '1' contributes +8 = +2^k where k = 3 """ string = str(binary) num_digits = len(string) integer = 0 for k in range(num_digits): digit = string[num_digits - k - 1] if digit == '1': integer += 2 ** k return integer if __name__ == '__main__': binary_numbers = [decimal_to_binary(i) for i in range(15)] print binary_numbers print [binary_to_decimal(i) for i in binary_numbers]
true
9339c9fc24de85166c2241154ada1a64d997db26
Se1juro/curso-python-udemy
/Introduccion a Python/Calculadora.py
1,430
4.21875
4
continuar = 1 numero_operacion = 0 while continuar == 1: print("Bienvenido a la calculadora") print("Estas son las operaciones que puedes realizar: ") while numero_operacion == 0 and numero_operacion < 5: print("1 - Suma \n2 - Resta \n3 - Multiplicación \n4 - División") try: numero_operacion = int( input("Introduce el número de operaciones que quieres realizar: ")) except ValueError: print("Elige una opción correcta") try: numero1 = int(input("Ingresa el primer número: ")) numero2 = int(input("Ingresa el segundo número: ")) except ValueError: print("Ingresa un número correcto.") else: if numero_operacion == 1: resultado = numero1+numero2 print("El resultado es: "+str(resultado)) elif numero_operacion == 2: resultado = numero1-numero2 print("El resultado es: "+str(resultado)) elif numero_operacion == 3: resultado = numero1*numero2 print("El resultado es: "+str(resultado)) elif numero_operacion == 4: resultado = numero1/numero2 print("El resultado es: "+str(resultado)) else: print("Por favor, ingresa una opción que este disponible") continuar = int(input("¿Desea continuar? 1. Si - 2. No\n")) numero_operacion = 0 print() print()
false
7025efb1cb705abe89d747bc5646adbb1601514d
caneslms83/treehousepython
/masterticket.py
1,480
4.15625
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 #calcualte price function. takes number of tickets and returns num tickets * TICKET_PRICE def calculate_price(wanted_tickets): # create a new constant for the 2 dollar service charge and add to what is due return (wanted_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining >= 1: print (f"There are {tickets_remaining} tickets remaining.") name = input("What is your name? ") wanted_tickets = input(f"How many tickets would you like {name}? ") #expect a value error and handle appropriately try: wanted_tickets = int(wanted_tickets) #raise an exception if request more than available tickets if wanted_tickets > tickets_remaining: raise ValueError(f"There are only {tickets_remaining}") except ValueError as err: #include the error in the text in the output print(f"Oh no, we ran into an issue. {err}. Please try again.") else: price = calculate_price(wanted_tickets) print(f"The total due is ${price}.") decision = input("Would you like to purchase these tickets? Y/N ") if decision.lower() == "y": #TODO proceed to gather cc info print(f"SOLD to {name}!!!") tickets_remaining -= wanted_tickets else: print(f"No worries, {name} maybe next time!") print("Sorry, there are no more tickets!! :(")
true
ef131a699ffe9daf4a4dcd2a4331d5ad0b8e0c40
caneslms83/treehousepython
/popvending.py
625
4.125
4
candy = ["twix","caramel","snickers"] soda = ["coca-cola", "sprite", "Dr. Pepper",] chips = ["doritos", "fritos", "lays",] while True: choice = input("Would you like SODA, CANDY, or CHIPS? ").lower() try: if choice == 'soda': snack = soda.pop() elif choice == 'candy': snack = candy.pop() elif choice == 'chips': snack = chips.pop() else: print("Sorry, I didn't get that.") continue except IndexError: print(f"Sorry we are all out of {choice}! Pick again.") print(f"Here's your {choice}: {snack}.")
true
0f77e35119573739b2d2f973ab54ca49c1a24377
hairneeorlah/class09_code
/guessgame.py
1,233
4.125
4
# import random # number_of_guesses = 0 # number = random.randint(1,100) # name = input("Hello! What is your name? ") # print(name + ", I am thinking of a number between 1 and 100. Can you guess what number it is?") # while number_of_guesses < 5: # guess = input("Take a guess ") # guess = int(guess) # number_of_guesses = number_of_guesses + 1; # number_of_guesses_remaining = 5 - number_of_guesses; # if guess < number: # number_of_guesses_remaining = str(number_of_guesses_remaining) # print(" The number you guessed is too low! You have " + number_of_guesses_remaining + " number_of_guesses_remaining ") # if guess > number: # number_of_guesses_remaining = str(number_of_guesses_remaining) # print("The number you guessed is too high! You have " + number_of_guesses_remaining + " number_of_guesses_remaining ") # if guess == number: # break # if guess == number: # number_of_guesses = str(number_of_guesses) # print("cheers! You guessed the number in " + number_of_guesses + " tries :)") # if guess != number: # number = str(number) # print("Oops! Better luck next time " + name + " the number i was thinking of is " + number + " :) ")
true
cb2bf63b81f8dd5990296d77890b22a8716dcdb3
GouchinHub/Pythonn
/database/week6.py
1,017
4.1875
4
#CT60A4304_01.06.2020 Basics of Database Systems #week6, python and SQL #Aatu Laitinen import sqlite3 yhteys = sqlite3.connect('week6.db') print("connection success.") yhteys.execute('''CREATE TABLE employees (id INT PRIMARY KEY NOT NULL, name TEXT NOT NULL, address TEXT NOT NULL, phone INT NOT NULL);''') print("Table emplyees created successfully") yhteys.execute("INSERT INTO employees \ VALUES(1,'John','5th avenue','300423942'),\ (2,'Julie','3rd road','309432424'),\ (3,'Max','8th boulevard','32135464'),\ (4,'Chris','2nd street','38532453')") yhteys.commit() print("Values inserted successfully\n") data = yhteys.execute("SELECT * FROM employees") for info in data: print("employeee",info[0]) print("id =",info[0]) print("name =",info[1]) print("address =",info[2]) print("phone =",info[3],"\n") yhteys.close()
true
5708525f8ac46765b99d7838d2440186d6db7ec4
toastding/collections
/Mile to Kilometers Converter/main.py
832
4.125
4
from tkinter import * # Window window = Tk() window.title("Mile to Km Converter") window.config(padx=20, pady=20) # unit label(Miles) label1 = Label(text="Miles", font=("Arial", 12)) label1.grid(column=2, row=0) # unit label(is equal to) label2 = Label(text="is equal to", font=("Arial", 12)) label2.grid(column=0, row=1) # unit label(Km) label3 = Label(text="Km", font=("Arial", 12)) label3.grid(column=2, row=1) # label(convert km) km_label = Label(text=0, font=("Arial", 12)) km_label.grid(column=1, row=1) # input input = Entry(width=7) input.insert(END, string=0) input.grid(column=1, row=0) # button def button_clicked(): miles = float(input.get()) km = miles * 1.609 km_label.config(text=f"{km}") button = Button(text="Calculate", command=button_clicked) button.grid(column=1, row=2) window.mainloop()
true
c914bf226c8a96a29fad34abf1e2463ef07a63d6
GreenTGreenT/GPA
/calGPA.py
2,799
4.1875
4
import csv #import operator data = [] grade = {"A": 4, "B+": 3.5, "B": 3, "C+": 2.5, "C": 2, "D+": 1.5, "D": 1, "F": 0} def read_csv(): with open('grade.csv', 'r') as f: reader = csv.reader(f) for i in reader: data.append(i) #data = sorted(data, key = operator.itemgetter(0)) def edit_csv(): read_csv() term = input("Enter term that you want to edit: ") print("----------------------------------------------------------------------------------") #print("|order|", "|term|", "| subject |", "|credit|", "|grade|") for i in range(len(data)): if data[i][0] == term: print("| ", i, " |", data[i][0], "|", data[i][1], "|", data[i][2], "|", data[i][3], "|") print("----------------------------------------------------------------------------------") edit_point = int(input("What's number you want to edit: ")) for i in range(len(data)): if edit_point == i: subject = input("Enter your subject: ") credit = input("Enter your credit: ") grade = input("Enter your grade: ").upper() data[i][1] = subject data[i][2] = credit data[i][3] = grade save_csv(term) def insert_csv(): read_csv() print("If you want to save, please enter S \n if you want to exit, please enter Q") num_subject = int(input("Enter total number of your subjects: ")) for i in range(num_subject): term = input("Enter your term number: ") subject = input("Enter your subject: ") credit = input("Enter your credit: ") grade = input("Enter your grade: ").upper() data.append([term, subject, credit, grade]) save = input("Do you want to save?: ").upper() if save == "S": save_csv(term) elif save == "Q": exit() def save_csv(term): #print(data) with open('grade.csv', 'w') as f: writer = csv.writer(f) writer.writerows(data) calculation(term) def calculation(term): sum_multiple = 0 sum_credit = 0 to_result = 0 for i in range(len(data)): if data[i][0] == term: #print(grade.get(data[i][3])) sum_multiple += int(data[i][2]) * grade.get(data[i][3]) sum_credit += int(data[i][2]) to_result = sum_multiple / sum_credit print("Your GPA is ", "%.2f " % to_result) def main(): print("Please choose your mode \n Edit(E) Insert(I)") mode = input("Enter your mode: ").upper() if mode == "E": edit_csv() elif mode == "I": insert_csv() else: print("Please try again") main() main()
false
f1c8bf1fdba19e7e793b9eea9366e448e57e63f3
anjmhrjn/python-s-prgram
/Lab exercise 2.py
653
4.25
4
#6. to print last digit of integer # a=int(input('Enter an integer:')) # if a>=10: # b=a//10 # c=a-(b*10) # print('The last digit is ',c) # else: # print('The only digit is ',a) #7. to print fractional part of a positive real number # a=float(input('Enter a positive real number:')) # x=a-int(a) # print(x) #8. to print sum of three digits of a given number # a=int(input('Enter a three digit number:')) # b=a//100 # c=(a-(b*100))//10 # d=(a-((b*100)+(c*10))) # print(b+c+d) print(10**3) print('APPLE'<'apple') a=2 b=3 c=4 d=3 print(a==b) print(a!=d) print(b==d) print(a!=c) print(b-a==c-b) print(b>=d) b/=d a+=c print(b) print(a)
false