blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
133cae86497cf23f3b6c68beb291b0840b269b23
rickbr6/dojo
/python_stack/python/radix_sort.py
2,227
4.28125
4
def get_digit(num, place): """ :param num: A single or multi digit number :param place: A number representing the place value of the number to return. i.e, 1 would represent the ones position and 2 would represent the 10s position :return: the number in the position requested with the place parameter. For the request with args (345,2) the return value would be 4 (since 2 represents the tens position). """ if len(str(num)) < place: return 0 else: number = (str(num))[-place] # print("Returning", number, "The original number was", num, "Place was:", place) return int(number) def get_max_iterations(num_array): """ :param num_array: An array of numbers :return: Returns the length value of the longest number in the array. For example: [1, 10, 300, 4) would return 3 which is the length of the longest value(300). """ max_num = 0 for num in num_array: if len(str(num)) > max_num: max_num = len(str(num)) return max_num def radix_sort(numbers): """ :param numbers: An array of unsorted numbers. :return: An array of numbers sorted from lowest to highest """ # Place represent the number position. 1 for ones position, 2 for tens position, 3 for hundreds position, etc place = 1 # Determines how many times we need to iterate through the array based on the length of the largest number # in the array. max_iterations = get_max_iterations(numbers) count = 1 # Sort each number into the appropriate bucket based on the current place number while count <= max_iterations: buckets = [[], [], [], [], [], [], [], [], [], []] for num in numbers: current_num = get_digit(num, place) buckets[current_num].append(num) # add the numbers back to the numbers array index = 0 for bucket in buckets: for digit in bucket: numbers[index] = digit index += 1 count += 1 place += 1 return numbers sorted_array = radix_sort([3221, 1, 10, 9680, 577, 9420, 7, 5622, 4793, 2030, 3138, 82, 2599, 743, 4127]) print(sorted_array)
true
74351ecf55a4f7c986f556f42856455dc8ec7808
niktechnopro/linux101
/algorithm2.py
750
4.125
4
#Fibonacci #make the fib function which returns the value of the fib number if you put an argument in it def fib(position): if(position ==0 or position ==1): return 1; else: return fib(position-2) + fib(position-1); #loop through the fib function to find the sum from 1 to when sum of fib numbers exceeds 4000000 sum = 0; #final_position = int(input("enter the number position in Fibonacci sequence: ")) counter = 1 while True: if fib(counter) >= 4000000: print ("fibonacci number is higher than 4000000,") print ("Position: %s and Fib number: %d" % (counter, fib(counter))) break else: if fib(counter)%2 == 0: sum +=fib(counter); counter += 1 print("Total sum of even numbers: %s" % (sum));
true
46660183744daeeed73374ab15d4a671be887753
dpdahal/python7pm
/function.py
2,420
4.125
4
# A function is a block of code that only runes when it is called # Types of function: # 1. Inbuilt function: print(), len(),int() # 2. User define function or custom function # define function # def course(): # # function body part # print("Online python class") # # # # calling # course() # def add(x, y): # print(x + y) # # # add(20,20,40) # # def course(name): # print(f"Online {name} class") # # # course('python') # course('java') # course('web development') # def introduction(name, age=10): # print(name, age) # # # introduction('ram', 20) # # introduction('sita',40) # def add(x, y): # print(x + y) # # # add(20, 20) # function return value # def add(x, y): # # print(x + y) # return x + y # # # a = add(30, 20) # print(a) # None # print(add(10, 20)) # def add_sub(x, y): # add = x + y # sub = x - y # return [add, sub] # # # print(add_sub(20, 10)) # def test(): # print("hello test") # # # def get(): # test() # # # get() # def take_value(): # pass # # # def calculate(): # pass # # # def display_value(): # pass # def my_rep(data, times): # pass # # # my_rep('python', 200) # function scope # global # local # x = 10 # # # def test(): # global x # x = x + 20 # print(x) # # # test() # # def students(names): # print(names) # # # students(['sita', 'ram', 'hari']) # * args: array arguments # ** kwrgs: keyword arguments # def students(*args, **kwargs): # print(args) # print(kwargs) # # # students('sita', 'ram', name='hari', age=20, phone=98798) # def test(): # """ # this is test # function # """ # return "Hello" # # # print(test.__doc__) # print(test.__name__) # add = lambda x, y: x + y # # print(add(20, 30)) # def introduction(): # def get_function(name): # return f"I am {name} function" # # return get_function # # # # print(introduction()()) # obj = introduction() # # print(obj('ram')) # recursive # 5 = 120 # # def recursive(n): # if n == 1: # return 1 # else: # return n * recursive(n - 1) # # # print(recursive(5)) # 5-1 =4 # 4-1 =3 # 3-1=2 # 2-1 =1 # # import calculator # # print(calculator.add(20, 40)) # print(calculator.sub(40, 50)) # * all from calculator import add from database import add as test print(add(10, 20)) print(test()) # from calculator import * # # print(add(30, 60)) # print(sub(5, 8))
true
cc437d93c07cdf8eafe3f66fd46d19cd401367a5
Athul-R/ds-algo
/python_code/arrays/array.py
1,528
4.28125
4
""" This file has the array implemention using Python Class. """ class ArrayWithDict(object): """ This is the array implementation with data as the Dict Object """ def __init__(self, arg): self.data = {} self.length = 0 def get(self, index): return self.data.get(index) def push(self, item): self.data[self.length] = item self.length += 1 return self.length def pop(self): last_item = self.data[self.length-1] del self.data[self.length-1] self.length -= 1 return last_item def delete(self, index): item = self.data[index] self.shift_items(index) return item def shift_items(self, index): for i in range(index, self.length): self.data[i] = self.data[i+1] del self.data[self.length-1] self.length -= 1 def size(self): return self.length class ArrayWithList(object): """ This is the array implementation with data as the List Object """ def __init__(self, arg): self.data = list() self.length = 0 def get(self, index): return self.data[index] def push(self, item): self.data[self.length] = item self.length += 1 return self.length def pop(self): last_item = self.data[self.length-1] del self.data[self.length-1] self.length -= 1 return last_item def delete(self, index): item = self.data[index] self.shift_items(index) return item def shift_items(self, index): for i in range(index, self.length): self.data[i] = self.data[i+1] del self.data[self.length-1] self.length -= 1 def size(self): return self.length
true
128dd012fb956d2aaa29b4c962020e7e96da43cd
ghills3620/csce093
/python/03PyBasicOperators.py
1,898
4.4375
4
#Basic Operators #http://www.learnpython.org/en/Basic_Operators #Just as any other programming languages, the addition, subtraction, # multiplication, and division operators can be used with numbers. number = 1 + 2 * 3 / 4.0 print( number ) #Another operator available is the modulo (%) operator, # which returns the integer remainder of the division. # dividend % divisor = remainder. remainder = 11 % 3 print( remainder ) #Using two multiplication symbols makes a power relationship. squared = 7 ** 2 cubed = 2 ** 3 print( "squared %d" % squared) print( "cubed %d" % cubed) #Python supports concatenating strings using the addition operator: helloworld = "hello" + " " + "world" #Python also supports multiplying strings to form a string with a repeating sequence: lotsofhellos = "hello" * 10 #Using Operators with Lists #Lists can be joined with the addition operators: even_numbers = [2,4,6,8] odd_numbers = [1,3,5,7] all_numbers = odd_numbers + even_numbers #Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator: print([1,2,3] * 3 ) #Exercise #The target of this exercise is to create two lists called x_list and #y_list, which contain 10 instances of the variables x and y, # respectively. You are also required to create a list called # big_list, which contains the variables x and y, 10 times each, # by concatenating the two lists you have created. x = object() y = object() x_list = [x] y_list = [y] big_list = [] print( "x_list contains %d objects" % len(x_list) ) print( "y_list contains %d objects" % len(y_list) ) print( "big_list contains %d objects" % len(big_list) ) # testing code if x_list.count(x) == 10 and y_list.count(y) == 10: print( "Almost there..." ) if big_list.count(x) == 10 and big_list.count(y) == 10: print( "Great!" )
true
5eac0415e9ab36961d78765856320e6f91b41754
gyratory/NPTfP3
/12 - Boolean Expressions/exercise01.py
486
4.21875
4
# Write a program that has a user guess your name, but they only get 3 # chances to do so until the program quits. print("=========") print("You will now try to guess my name!\nYou have 3 tries.") print("=========") attempt = 0 while attempt != 3: attempt += 1 guess = input("Take a guess: ") if guess == "gyratory": print("Congratulations! You win nothing.") quit() elif attempt <= 2: print("Try again.") else: print("You failed!")
true
143b9e148598f400c67f35b97ee68489364980e1
zf2169/Pythons
/primefactors.py
920
4.15625
4
# -*- coding: utf-8 -*- """ @title: Prime Factorization @function: Enter a number and find all Prime Factors (if there are any) and display them @author: Zhilin """ def findprime(n): ''' find all the prime numbers smaller than n ''' num= list(range(2,n+1)) pnum= list() while True: a= num[0] pnum.append(a) for i in num: if i%a == 0: num.remove(i) if num==list(): break return(pnum) def findfac(n): ''' find all prime factors of the number ''' for i in findprime(n): if n%i == 0: print(i, end=' ') def main(): while True: try: num= int(input('Please input a number:')) except ValueError: print('Please input a valid integer.') continue else: findfac(num) break main()
true
bdf5689c233e9206f60057dcdff2e4c8ff06903c
duybui2905/C4T-13
/session5/season.py
279
4.375
4
month = int(input("Insert month: ")) if month <= 3 and month > 0: print("this is winter") elif month <= 6: print("this is spring") elif month <= 9: print("this is summer") elif month <= 12: print("this is fall") else: print("THIS IS NOT A MONTH !!!!!!!")
true
80eb6d3e3ee146c3fd8026058a25f1637f7e031c
duybui2905/C4T-13
/session10/read_dict.py
220
4.21875
4
person = { "name" : "Felix", "nickname" : "Pewdiepie", "job" : "youtuber", } print(person) # print(person["name"]) key_of_value = input("enter the key of value you wanna find: ") print(person[key_of_value])
false
1fadb4adbdb5e74712ef45c9ef8bb9f321073a11
vaishnavisaindane/Hacktoberfest2021-4
/Scripts/smallest_and_largest_of_n_different_numbers.py
353
4.3125
4
#python program to display smallest and largest of n different numbers n=int(input("Enter a limit")) m=int(input("Enter first number")) min=m max=m print("Enter next",n-1,"numbers") for i in range(2,n+1): m=int(input()) if m>max: max=m elif m<min: min=m print("\nlargest number is",max) print("\nsmallest number is",min)
true
3741df1d5e4b3388d4134057edc43889e6a16886
danielrincon-m/AYED
/Arenas/Arena 1/11220 - Decoding the message.py
1,735
4.125
4
# Algoritmo: # 1. Leer la entrada, una lista de oraciones en donde cada oración es una lista de palabras. # 2. Para cada lista de oraciones, definir una variable para la posición de letra, una lista de palabras de salida y una variable para la palabra de salida, recorrer la lista. # 2.1. Verificar si la posición de la letra se encuentra en la palabra. # 2.2. Si es así, agregar la letra a la palabra destino, agregar 1 a la posición de letra. # 2.3. agregar la palabra final a la lista de salida. # 3. Imprimir cada elemento de la lista de salida. from sys import stdin def leerEntrada(): oraciones = [] while True: oracion = stdin.readline().strip().split(" ") if oracion == [""]: break else: oraciones.append(oracion) return oraciones def obtenerLetra(oracion, indiceDeLetra): return oracion[indiceDeLetra] def construirSalida(oraciones): respuestas = [] for i in range(len(oraciones)): indiceDeLetra = 0 palabraConstruida = "" for j in range(len(oraciones[i])): if indiceDeLetra < len(oraciones[i][j]): palabraConstruida += obtenerLetra(oraciones[i][j], indiceDeLetra) indiceDeLetra += 1 respuestas.append(palabraConstruida) return respuestas def imprimirSalida(caso, respuestas): if caso != 1: print() print('Case #' + str(caso) + ":") for respuesta in respuestas: print(respuesta) def main(): casos = int(stdin.readline().strip()) stdin.readline() for i in range(casos): oraciones = leerEntrada() respuestas = construirSalida(oraciones) imprimirSalida(i + 1, respuestas) main()
false
800801cbdeb294ab5d70f3f6e5a625d8f377343f
chimaihueze/EDD-calculator
/EDD 2.py
1,223
4.21875
4
""" This promgram computes the Expected Date of Delivery (EDD) when a user enters the date of their Last Menstrual Period (LMP). """ from datetime import timedelta, date try: #getting LMP from the user lmp = input("Enter the date of your last period in DD-MM-YYYY format: ") lst = lmp.split("-") #splitting the date to change to int numbers day, month, year = int(lst[0]), int(lst[1]), int(lst[2]) lmp_date = date(year, month, day) #converting the LMP to datetime object delta = timedelta(days = 280) edd_date = lmp_date + delta #adding 280 days which is the duration of pregnancy print(f"Your expected date of delivery is {edd_date}.") except: print("Error! Please enter a valid date in the specified format.") #another method by adding 40 weeks to LMP # delta5 = timedelta(weeks = 40) # date5 = date1 + delta5 # print(date5) #using Naegle's rules are # delta1 = timedelta(days = 7, weeks = -13) # date2 = date + delta1 #adding 7 to days and subtracting 3 months i.e 13 weeks # delta2 = timedelta(weeks = 52) # date3 = date2 + delta2 #adding 1 year to the date i.e 52 weeks # print(date3)
true
394ca88761791dcf488c19a06d0a85c424c28f46
rup3sh/leetcode
/src/101_symmetricTree
766
4.25
4
#!/bin/python3 #101. Symmetric Tree class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isSymmetric(self, root): def _isSym(l,r): if not l and not r: return True if l and r and l.val==r.val and _isSym(l.left, r.right) and _isSym(l.right, r.left): return True print(l.val, r.val) return False if not root: return True return _isSym(root.left, root.right) def main(): sol = Solution() tree = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(2, TreeNode(4), TreeNode(3)) ) is_symmetric = sol.isSymmetric(tree) print(is_symmetric) if __name__=="__main__":main()
false
24953a25857a31fb6d41955aa7d0e8774bfb5235
CristofferJakobsson/sepm-team-a
/src/user_interface/centeredtext.py
1,770
4.125
4
class centeredtext(object): """ centeredtext extends the object class and centers text within an object """ def __init__(self, text, x,y,w,h, pygame, fontsize, color=(0,0,0)): """ Construct a new centeredtext object. :param self: A reference to the centeredtext object itself :param text: The text to center within the given object :param x: The leftmost coordinate of the given object of which to center a text within :param y: The rightmost coordinate of the given object of which to center a text within :param w: The width of the given object of which to center a text within :param h: The height of the given object of which to center a text within :param pygame: The pygame instance running :param fontsize: The fontsize of the text to center :param color: The color of the text to center :return: returns nothing """ self.pygame = pygame self.x, self.y, self.w, self.h = x,y,w,h self.pygame.font.init() font = self.pygame.font.SysFont("sans", fontsize) width, height = font.size(text) xoffset = (self.w-width) // 2 yoffset = (self.h-height) // 2 self.coords = self.x+xoffset, self.y+yoffset self.txt = font.render(text, True, color) def draw(self, screen, bordercolor): """ Display the centered text object within the given object. :param self: A reference to the centeredtext object itself :param screen: The screen where to display the text :param bordercolor: The border color of the testing rect :return: returns nothing """ screen.blit(self.txt, self.coords) # for testing purposes, draw the rectangle too rect = self.pygame.Rect(self.x, self.y, self.w, self.h) self.pygame.draw.rect(screen, bordercolor, rect, 1)
true
1d280bcb97fb37bd9f3e77a8e9031a2d59226277
Stephanie-Spears/LC101-Complete
/Unit1/aFraction.py
1,523
4.15625
4
#helper function--a function outside a class that is used by a method #A mutator method -- a method with no return which modifies the object itself def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class aFraction: def __init__(self, num, den): self.num = num self.den = den def __str__(self): return str(self.num) + "/" + str(self.den) def __add__(self, other): newnum = self.num * other.den + self.den * other.num newden = self.den * other.den common = gcd(newnum, newden) return aFraction((newnum // common), (newden // common)) def __mul__(self, other): newnum = self.num * other.num newden = self.den * other.den common = gcd(newnum, newden) return aFraction(newnum // common, newden // common) def reciprocal(self): newnum = self.den newden = self.num return aFraction(newnum, newden) def simplify(self): common = gcd(self.num, self.den) self.num = self.num // common self.den = self.den // common f1=aFraction(1,2) f2=aFraction(1,4) f3=f1 + f2 print("addition should be 3/4--->", f3) f4 = aFraction(12, 16) f4.simplify() print("simplify should be 3/4--->", f4) f5 = aFraction(1,2) f6 = aFraction(2,5) f7 = f5 * f6 print("multiply should be 2/10, which simplifies to 1/5--->", f7) f8 = aFraction(7, 8) f9 = f8.reciprocal() print("reciprocal should be 8/7--->", f9)
false
011964435a3b4ba0046bebb406f45eababcf886f
Stephanie-Spears/LC101-Complete
/Unit1/Crypto/caesar.py
1,010
4.21875
4
"""caesar shift module""" from helpers import rotate_character, validate #, alphabet_position def encrypt(text, rot): """shift string rot positions""" new_text = "" for char in text: new_text += rotate_character(char, rot) return new_text def main(): """encapsuate execution main""" from sys import argv message = input("Type a message:\n") prompt = "Rotate by:\n" shift = int(validate(prompt, *argv)) print(encrypt(message, shift)) if __name__ == "__main__": main() # def encrypt(message, shift): # """encrypt message with specified shift""" # encrypted_message = "" # alpha = string.ascii_letters # for char in message: # if char not in alpha: # encrypted_message += char # else: # if (shift+alpha.find(char)) > 52: # encrypted_message += chr(ord(char)+shift-26) # else: # encrypted_message += chr(ord(char)+shift) # return encrypted_message
true
911bf7bae8aefb880ffa09b7268665f002bb2fa8
Ainnop/PYTHON-LEARNING
/nested_function.py
425
4.1875
4
def outer_function(x): """ enclosing function """ def inner_function(): """ nested function """ # nonlocal x x = 5 print("The x value inside inner function is: {}".format(x)) x_local = x * 2 print("The x local value inside inner function is {}".format(x_local)) inner_function() print("The x value outside inner function is: {}".format(x))
true
b10d6dff6edd5f5e8da586f0a7ad4b51bb1b8c05
patterson-dtaylor/100_Days_Of_Python
/Day_10/calculator.py
1,842
4.3125
4
calculator_power = True first_calculation = True total = 0 def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): return num1 / num2 def calculator(function=None, num1=0, num2=0): if function == "+": return add(num1, num2) elif function == "-": return subtract(num1, num2) elif function == "*": return multiply(num1, num2) elif function == "/": return divide(num1, num2) def calculator_functionality(result, recaculate="no"): if recaculate == "yes": function = input("What function would you like to use? (+,-,*,/) ") num1 = result num2 = float(input("What is the second number you want to use? ")) answer = calculator(function, num1, num2) print((f"The answer is {answer}.")) return answer elif recaculate == "no": function = input("What function would you like to use? ") num1 = float(input("What is the first number you want to use? ")) num2 = float(input("What is the second number you want to use? ")) answer = calculator(function, num1, num2) print((f"The answer is {answer}.")) return answer while calculator_power: if first_calculation: total = 0 result = calculator_functionality(total) total += result user_choice = input(f"Would you like to use {result} in a new equation, startover, or poweroff (yes, no, off) ") if user_choice == "yes": first_calculation = False result = calculator_functionality(total, recaculate="yes") total = 0 total += result if user_choice == "no": first_calculation = True elif user_choice == "off": print("Powering off...") break
true
58f684be09fc2c363841b1f2696cdb472de70121
Sheldonan2142/backup
/practice3.py
411
4.375
4
day = input("hey what day of the week is it? im mega lost ") if day == "Monday" or day == "monday": print("ah the weekend is over; it's monday") if day == "Friday" or day == "friday": print("friday !! the weekend is close friends") if day == "Saturday" or day == "saturday" or day == "Sunday" or day == "sunday": print("its the weekend fellas :))") else: print("oh no thats not the weekend :((")
true
25faa2b23248280b65d4924bfce16e8ed4559e5f
Sheldonan2142/backup
/list.py
1,300
4.40625
4
# how to make a list favMovies = ["Dora the Explorer", "The Emoji Movie", "High School Musical"] # print the whole list print(favMovies) # print individuals print(favMovies[2]) # to add you can append or insert # append adds to the end favMovies.append("High School Musical 2") print(favMovies) # insert will put them wheverever you want favMovies.insert(1, "High School Musical 3") print(favMovies) # how to remove items # remove by name or index # remove by name use "remove" favMovies.remove("Dora the Explorer") print(favMovies) # pop will remove the last item unless you add an index favMovies.pop() print(favMovies) favMovies.pop(1) # will remove the index print(favMovies) # get the length of a list # this is a function # the function na,e is len print("My List has" + str(len(favMovies))+ "items") favMovie = input("What is your favorite movie? :) ") favMovies.append(favMovie) print(favMovies) print(favMovies[len(favMovies) - 1]) # loop through a list count = 1 for movie in favMovies: print("My number "+ str(count)+"movies is"+ movie) count = count + 1 numList=[1,2,43,665,3465,545643] #challenge: loop through the list and add all the numbers together, print the answer total = 0 for number in numList: total = total + number
true
3078b5dae76dd8e48600fca851c334639314d919
irandjelovic/data-parser
/string_parser/remove_adjacent_same_letters.py
2,124
4.21875
4
#!/usr/bin/env python ''' Simple string parser module with function(s): - Remove adjacent pairs of same letters for an input string ''' # standard lib import argparse arg_parser = argparse.ArgumentParser(description="Argument parser") arg_parser.add_argument('-i', dest="input", help="Input string") arg_parser.add_argument('-r', action="store_true", dest="recursion", help="Call recursion function") def remove_adjacent_same_letters(input_str): # return if input length is less than two letters if not input_str or len(input_str) < 2: return input_str i = 0 while i < len(input_str) - 1: if input_str[i] == input_str[i+1]: # if same letters, then cut them input_str = input_str[:i] + input_str[i+2:] if i > 0: # if same letters, move index pointer to previous letter i -= 1 else: # if letters are not the same continue with processing i += 1 return input_str def remove_adjacent_same_letters_recursion(input_str): # return if input length is less than two letters if not input_str or len(input_str) < 2: return input_str found_same_letters = False parsed_input = '' i = 0 while i < len(input_str): # append letter if it's the last letter or adjacent letters are not the same if i == len(input_str) - 1 or input_str[i] != input_str[i+1]: parsed_input += input_str[i] i += 1 else: found_same_letters = True i += 2 if found_same_letters: return remove_adjacent_same_letters_recursion(parsed_input) return parsed_input def main(): args = arg_parser.parse_args() if args.recursion: func = remove_adjacent_same_letters_recursion else: func = remove_adjacent_same_letters print "Input: {}".format(args.input) output = func(args.input) print "Output: {}".format(output) if __name__ == "__main__": main()
true
781a2697af4973290bf7e988189430de4616a97d
KuldipSharma/hacktober2020
/fizzBuzz.py
270
4.15625
4
def fizzbuzz(number): if(number%3 == 0 and number%5 == 0): print("fizzbuzz") elif(number%3 == 0): print("fizz") elif(number%5 == 0): print("buzz") else: print(number) number = int(input("Enter Number: ")) fizzbuzz(number)
false
569fe91d22e2487d6db5136ff8a5fde2e829ff16
hu22333/git
/python learn/应用基础/Python入门/week_L2/ex3.py
1,209
4.40625
4
# 分支循环操作小练习 if 0: print("Hello") if 1: print("hello") if "": print("Hello") if []: print("Hello") if {}: print("Hello") if "Not Empty": print("Hello") if [10, "101"]: print("hello") if True: print("Hello") if False: print("Hello") if 0 == 1: print("hello") a = 10 if a > 10 or a < 10: print("a is not 10") else: print("a is 10") a is 10 if a > 10: print("a>10") elif a < 10: print("a<10") else: print("a=10") a = 10 print(range(10)) print(list(range(10))) for i in range(10): print(i, end="") for i in [0, 1, 2, 3, 4]: print(i, end="") for i in range(1, 10, 2): print(i, end="") print(list(range(1, 10, 2))) for c in "Python语言": print(c) for c in "Python语言": print(c, end=",") while a > 5: print(a) a = a-1 while False: print("Hello") while True: print("Hello") break print(a) while a > 0: a = a - 1 if a % 2 == 0: continue print(a) try: a=10/0 except: print("error") try: a=oprn("no-exist") except: print("error") try: if x: print("Hello") except: print("error") try: anyerror except: print("error")
false
951b5cfbb9d28aa1547c077ddac0b0d5fcfd146b
Jiaweihu08/EPI
/4 - Primitive types/4.0 - count_bits.py
567
4.1875
4
def count_bits_naive(x): """ x is a 64-bits integer, so the number of iterations here is 64. for each bit from the right, we check if it's 1 and then remove it. """ num_bits = 0 while x: num_bits += x & 1 x >>= 1 return num_bits def count_bits_wegner(x): """ x & (x - 1) returns x with its last set bit removed so if the input integer is 1000....0 then the number of iterations will be 1 instead of 64 which is the case of the naive approach """ num_bits = 0 while x: num_bits += 1 x &= x - 1 return num_bits print(count_bits_wegner(1))
true
7bed948376991aa597310ec4fd65fefae91a431c
Jiaweihu08/EPI
/9 - Binary Trees/9.10 - inorder_traversal_no_recursion_with_parent_field.py
511
4.1875
4
""" Implement inorder traversal for binary trees without using recursion. Hint: Analize cases depending on what the previous node is. """ def inorder_traversal(tree): prev, results = None, [] while tree: if prev is tree.parent: if tree.left: next = tree.left else: results.append(tree.data) next = tree.right or tree.parent elif prev is tree.left: results.append(tree.data) next = tree.right or tree.parent else: next = tree.parent prev, tree = tree, next return results
true
4eab229f75cc28e91230150e4525b5e9bd567471
Jiaweihu08/EPI
/12 - Hash Tables/12.3 - ISBN_cache.py
2,681
4.40625
4
""" Create a cache for looking up prices of books identified by their ISBN. Implement lookup, insert, and erase methods. Use the LRU policy for cache eviction - If the number of books exceeds the capacity of the cache when inserting a new book, replace the oldest operated book with the new one Use a hash table to store ISBN identifiers of the books and their prices, ISBN are used as keys. We also keep a counter to keep track of the number of insertions and lookups done to each book, when the size of the hash table exceeds the capacity, the book with the least count is removed to free space This requires O(n) time to find the ISBN with the least count, remove it, and place the new book in the hash table, so insertion will take O(n) time To improve the efficienty we can avoid processing all entries in the hash table when looking for the oldest ISBN. Use a queue to store the insertion order of the items. Move the elements to the end of the queue each time we do an insert or lookup. When the capacity is reached, remove the element at the front of the queue and insert the new one An OrderedDict is ideal in this scenario since it keeps track of the order of insertion of the items in the dictionary. When performing insertions or lookups, we first remove the element from the dictionary and then add it back, the looked or inserted element will now be the most recently used on, the LRU element is always at the begining of the queue """ import collections class LruCache: def __init__(self, capacity): self._isbn_price_table = collections.OrderedDict() self._capacity = capacity def lookup(self, isbn): if isbn not in self._isbn_price_table: return -1 price = self._isbn_price_price.pop(isbn) self._isbn_price_table[isbn] = price return price def insert(self, isbn, price): if isbn in self._isbn_price_table: price = self._isbn_price_price.pop(isbn) elif len(self._isbn_price_table) == self.capacity: self._isbn_price_price.popitem(last=False) self._isbn_price_table[isbn] = price def erase(self, isbn): return (self._isbn_price_table.pop(isbn, None) is not None) # class LRU(collections.OrderedDict): # def __init__(self, maxsize=128, /, *args, **kwds): # self.maxsize = maxsize # super().__init__(*args, **kwds) # def __getitem__(self, key): # value = super().__getitem__(key) # self.move_to_end(key) # return value # def __setitem__(self, key, value): # if key in self: # self.move_to_end(key) # super().__setitem__(key, value) # if len(self) > self.maxsize: # oldest = next(iter(self)) # del self[oldest]
true
f8ce17590dcc54d24997126e3c75d39a732fc8ea
Jiaweihu08/EPI
/7 - Linked Lists/7.12 - is_palindromic_list.py
1,873
4.3125
4
""" Given a singly linked list, test is the data stored in the list for a palindrom """ class Node: def __init__(self, data=0, next_=None): self.data = data self.next = next_ def __repr__(self): return f'Node: {self.data}' def build_list(l): L = [Node(l[0])] for i in range(1, len(l)): L.append(Node(l[i])) L[i - 1].next = L[-1] return L def is_palindromic_naive(L): """ O(n) space and time complexity """ s = [] while L: s.append(L.data) L = L.next return all(s[i] == s[~i] for i in range(len(s) // 2)) def is_palindromic(L): """ Compare the first half of the list with the second half First iterate through the list and stop at the middle, this is achieved by using two pointers with the second pointer moving with the twice the speed of the first one. Then reverse the part of the list starting from the middle and compare the beginig of list with its reversed second half VISUALLY: original list L: 0 -> 1 -> 2 -> 3 -> 2 -> 1 -> 0 L with its seconf half reversed: 0 -> 1 -> 2 -> 3 <- 2 <- 1 <- 0 | | L second half iter The same function used to reverse the second half of the list can be used again to restore the original list """ def reverse_list(s): iter_head = Node(0, s) it = iter_head.next while it.next: temp = it.next it.next, temp.next, iter_head.next = (temp.next, iter_head.next, temp) return iter_head.next slow = fast = L while fast and fast.next: fast, slow = fast.next.next, slow.next first_half_iter, second_half_iter = L, reverse_list(slow) while second_half_iter and first_half_iter: if second_half_iter.data != first_half_iter.data: return False second_half_iter, first_half_iter = (second_half_iter.next, first_half_iter.next) return True L = build_list([0,1,2,3,1,0])[0] is_palindromic(L)
true
4e76efbcb5bba05f25fe376b11ee5b94ea7a2535
Jiaweihu08/EPI
/9 - Binary Trees/9.2 - is_symmetric.py
540
4.3125
4
""" Check if a given binary tree is symmetric. If we draw a vertical line through the root node, is the left tree the mirror image of the right tree? """ def is_symmetric(tree): def check_symmetric(subtree_0, subtree_1): if not subtree_0 and not subtree_1: return True elif subtree_1 and subtree_1: return (subtree_0.data == subtree_1.data and check_symmetric(subtree_0.left, subtree_1.right) and check_symmetric(subtree_0.right, subtree_1.left)) return False return not tree or check_symmetric(tree.left, tree.right)
true
2be38ddf8b258931a9052e73c74e2f983de93ef5
prince5609/Implementation_DataStructure
/Bubble_Sort.py
413
4.125
4
def bubble_sort(array): n = len(array) - 1 for j in range(n): swapped = False for i in range(n - j): if array[i] > array[i + 1]: temp = array[i] array[i] = array[i + 1] array[i + 1] = temp swapped = True if not swapped: break return array print(bubble_sort([8, 4, 6, 1, 2, 3, 7, 9, 5]))
false
feea036966d71a2225f6c8510207b95c8d3a10e4
DevBveasey/Code
/Python/extra/functions practice.py
265
4.25
4
#Brandon Veasey def sqrMe(num1): print("the number squared is", num1 * num1) num1 = int(input('Enter a number to be squared:(negative number to end) ')) while (num1 > 0): sqrMe(num1) num1 = int(input('Enter a number to be squared: (negative number to end)'))
false
94a22acddb2b2197e8949ae301af4f0330156cb9
wonju5332/source
/PythonClass/Chap_11_oBject_cLass/6_1_overriding.py
512
4.25
4
""" Overriding :짓밟다. 무효로 하다. ~에 우선하다. :부모 클래스로부터 상속받은 메소드를 다시 정의하다 """ class grandfather: def __init__(self): print("튼튼한 두 다리") class father2(grandfather): def __init__(self): super().__init__() print("지혜") father1 = father2() #지혜만 출력되게 된다. 즉, 오버라이드 되었기 때문이다. 할아버지의 튼튼한 두 다리도 물려받고 싶다면? super()를 적자
false
b38e80672246acac1f15ecbd209edde5980e1be1
aml-spring-19/homework-1-nanshanli
/task1/task12.py
420
4.125
4
"""Spring 2019 COMSW 4995: Applied Machine Learning. UNI: nl2643 Homework 1 Task 1.2 Contains function that computes fibonacci sequence """ def fib(n): """Find fibonacci sequence for a given value n.""" prev = 1 curr = 1 if n == 1: return 1 elif n == 2: return 1 for i in range(3, n + 1): temp = prev + curr prev = curr curr = temp return curr
true
2fa075710a19cd2db6c9704d6733665b9f568a19
wajdm/ICS3UR-2-05-Python
/global_variables.py
886
4.4375
4
#!/usr/bin/env python 3 # Created by: Wajd Mariam # Created on: Sept 2019 # This program shows how local and global variables works # global variable variable_X = 25 def local_variable(): # This variable shows what's happening with local_variable variable_X = 10 variable_Y = 30 variable_A = variable_X + variable_Y print("local variable_X, variable_Y, variable_A: {0} + {1} = {2}" .format(variable_X, variable_Y, variable_A)) def global_variable(): # This variable shows what's happening with global_variable global variable_X variable_X = variable_X + 1 variable_Y = 30 variable_A = variable_X + variable_Y print("Global variable_X, variable_Y, variable_A : {0} + {1} = {2}" .format(variable_X, variable_Y, variable_A)) def main(): local_variable() global_variable() if __name__ == "__main__": main()
true
5d66d36221fa71d445d5e9baf2968441591020a5
FBecerra2/MachineLearning-Data
/python/python recetas/5 receta - Objetos/13-Iterar-un-dataframe.py
434
4.28125
4
#Iterar un DataFrame import pandas as pd import numpy as np datos = {'col1':[1,2,3], 'col2':[4,5,6], 'col3':[7,8,9]} df = pd.DataFrame(data=datos) # iteracion por columnas for columna in df: #obtener columnas de un DataFrame print(columna) for columna in df: #ver columnas y sus datos print(df[columna]) #Ierar indice fla for indice, fila in df.iterrows():#muestra print('Indice:{}'.format(indice)) print(fila)
false
cbee5a85ad921f68d1e925cf70cec15eb0afb788
Aarom5/python-newbie
/dictionary.py
275
4.28125
4
classmates={'Tony':' cool but smells','Zack':' Sits at the front','Lucy': ' Weird'} # creates a set with key and values print(classmates) print(classmates['Zack']) # info about specific object for k,v in classmates.items():# iterates through every item print(k+v)
true
b49e59a06330afe5676d7a172b232948700d6b7b
YannisSchmutz/PythonTipsAndTricks
/generators/compute1.py
981
4.1875
4
""" Just the fundamental principe. """ from time import sleep # Bad example def compute(): """ We would have to wait for the whole list, even though we might just need the first few element of it. - takes a lot of time (for the first element being returned) - needs much more memory than using an iterable class :return: """ ret = [] for i in range(0, 10): ret.append(i) sleep(.5) # simulate some computing process, which takes its time return ret # Goode example class Compute(object): def __iter__(self): self.last = 0 return self def __next__(self): ret = self.last self.last += 1 if self.last > 10: raise StopIteration() sleep(.5) # simulate some computing process, which takes its time return ret if __name__ == '__main__': for val in Compute(): print(val) # You are able to do something right now with your value
true
b5ed67afcf55f697d277aa0f714bf6ee7f091d12
sarathrajkottamthodiyil/python
/Practise/list1.py
299
4.125
4
numbers = [] strings = [] names = ["sarath", "ajay", "arun"] numbers.append(1) numbers.append(2) numbers.append(3) strings.append("hello") strings.append("friends") second_name = names[1] print(numbers) print(strings) print("the second name on the name list is !! %s !!" % second_name)
true
7a7728a8c8b413ec8fcd0225b47bef6a6b40d61e
Khalu/ROT135_decoder
/rot13.py
1,506
4.3125
4
import string def shift_digit(digit): """Shifts the number 5 positions forward or if the sum is over 9, 5 positions backward""" if int(digit) + 5 > 9: return(str(int(digit) - 5)) else: return(str(int(digit) + 5)) def shift_letter(letter): """this shifts the letter 13 positions forward or in the case of going over z 13 backward""" #this uses ord and chr to perform the letter shift if letter.isupper() == True: if (ord(letter) + 13) > 90: return(chr((ord(letter) - 13))) else: return(chr((ord(letter) + 13))) elif letter.islower() == True: if (ord(letter) + 13) > 122: return(chr((ord(letter) - 13))) else: return(chr((ord(letter) + 13))) def crypt13(string): """This decrypts and encrypts string using ROT 13.5""" out='' for i in string: if i.isalpha() == True: out+=shift_letter(i) elif i.isdigit() == True: out+=shift_digit(i) else: out+=str(i) print(out) def menu(): """This starts the main menu""" active = True while active == True: user_input = input("\ninput the string to be encrypted/decrypted \n") crypt13(user_input) cont = input("\nwould you like to do another? (yes/no) \n") if cont == "no": print("\nGoodbye!") active = False elif cont != "yes": print("Please select yes or no \n") #main menu()
false
5fb2dfa1d6d4d29f761d1e1593f0c5aa3b5de8d5
RawandKurdy/snippets
/5_functions/function.py
600
4.3125
4
# Functions in Python # 1- Traditional function # also used to demonstrate how an anonymous func can be useful # It runs a function passed as a param then prints its result def traditionalFunc(anotherFunc): text_with_duplicates = anotherFunc("NYC!", 3) print(text_with_duplicates) # 2- Anonymous Function # I passed it as a parameter # it duplicated the text as many time as the user wishes traditionalFunc(lambda text, times : text * times) # 3- Function Expression anotherFunc = lambda text: text[len(text)-1] # Exec Expr. function last_char = anotherFunc("NYC") print(last_char) # C
true
2f382b4e09e87038478b6fe8f6de67f0ddc50c0c
bcongdon/leetcode
/200-299/232-implement-queue-with-stacks.py
1,164
4.28125
4
class Queue(object): def swap(self): while self.inStack: self.outStack.append(self.inStack.pop()) def __init__(self): """ initialize your data structure here. """ self.inStack = list() self.outStack = list() def push(self, x): """ :type x: int :rtype: nothing """ self.inStack.append(x) def pop(self): """ :rtype: nothing """ if not self.outStack: self.swap() if self.outStack: self.outStack.pop() def peek(self): """ :rtype: int """ if not self.outStack: self.swap() return self.outStack[-1] def empty(self): """ :rtype: bool """ return not self.inStack and not self.outStack # Explanation # Have one stack handle inputs and the other handle outputs. When you need # to output, take all of the elements in the 'in' stack and put them in the # 'out' stack. The result is queue behavior. # Runtime: # Push - O(1) # Pop - O(n) # Peek - O(n) # Empty - O(1) # Space Complexity - O(n)
false
a6d6943be5220151308566d706edaf7a2e7e23ed
zcesur/algo
/tree_diam.py
2,727
4.3125
4
#!/usr/bin/env python # A script that finds the diameter of a tree, which is defined as the # maximum length of a shortest path. It runs in O(n+m) time, i.e., in # time linear in the number of vertices and edges, which is equivalent # to O(n) for trees. # # The main idea used in the algorithm is that the longest path through # any root node is found by taking 2 children that have the largest # height. Also note that a tree's diameter is at least as big as its # children's diameters, or equivalently, the proper sub-tree with the # largest diameter is the lower bound for a tree's diameter. # # Zafer Cesur class Tree(object): def __init__(self, value, children=[]): self.value = value self.children = children def __repr__(self, level=0): """Print the tree in level-order (when read from left to right)""" ret = "\t"*level+repr(self.value)+"\n" for child in self.children: ret += child.__repr__(level+1) return ret def isLeaf(self): return True if len(self.children) is 0 else False def find_diam(node): """ Require: A tree (equivalently a node) Ensure: A tuple that contains the height and the diameter of the tree """ # Leaf node has height 0 and diameter 0 if (node.isLeaf()): return 0, 0 childHeights = [] largestChildDiameter = 0 # For each child node, recursively invoke the algorithm for child in node.children: height, diameter = find_diam(child) if (largestChildDiameter < diameter): largestChildDiameter = diameter childHeights.append(height) height = max(childHeights)+1 childHeights.remove(height-1) if (len(childHeights) is not 0): secondHeight = max(childHeights)+1 longestPathThruThis = height+secondHeight else: longestPathThruThis = height diameter = largestChildDiameter \ if largestChildDiameter>longestPathThruThis else longestPathThruThis return height, diameter def main(): tree1 = Tree('*', [Tree('*'), Tree('*'), Tree('*', [Tree('*'), Tree('*')])]) print tree1 print "tree1 has a diameter of %d" % find_diam(tree1)[1] tree2 = Tree('*', [Tree('*', [Tree('*', [Tree('*'), Tree('*')]), Tree('*', [Tree('*'), Tree('*')])])]) print tree2 print "tree2 has a diameter of %d" % find_diam(tree2)[1] if __name__ == '__main__': main()
true
c6ee234dcb13924182c3c0691b125481233bd68d
bliutwo/bliutwo_project_euler
/DigitFactorials/digitfactorials.py
1,182
4.375
4
# Filename: digitfactorials.py # Description: https://projecteuler.net/problem=34 def factorial(num): total = 1 while num > 0: total *= num num -= 1 return total def lengthOfNum(num): string = str(num) return len(string) def sumOfFactorialOfDigits(num): total = 0 string = str(num) for char in string: digit = int(char) total += factorial(digit) return total def main(): # how do i know when to stop? there should be a point where # the sum of the digits is greater than the number itself? but 3! > 3 num = 3 total = 0 actualSumOfFactorialOfDigits = sumOfFactorialOfDigits(num) # frank's hint: recursive function # another way to do this is to simply return a boolean whether it does: # this allows you to exit early if you know that the sum of factorial # of digits, based on the numbers so far, will never equal the num while lengthOfNum(num) < lengthOfNum(actualSumOfFactorialOfDigits) + 6: if actualSumOfFactorialOfDigits == num: print "WOW: num: %d ; sum: %d" % (num, actualSumOfFactorialOfDigits) total += num num += 1 actualSumOfFactorialOfDigits = sumOfFactorialOfDigits(num) print "Sum: %d" % total if __name__ == "__main__": main()
true
0abfa75272a8d4c9f57030830718f4cd8b54ca91
angelaTv/Luminar-Python
/languagefundamentals/functions/function basics.py
476
4.125
4
#cube of a number # def cub(): # n= int(input("enter number")) # res=n**3 # print(res) # cub() #is even or not # def isevenodd(): # # if(n%2!=0): # print("even") # else: # print("odd") # isevenodd(21) #fibonocii series up to nth term def fibonocii(): n1=0 n2=1 count=0 terms=int(input("how many terms")) while (count<terms): print(n1) nth=n1+n2 n1=n2 n2=nth count+=1 fibonocii()
false
12dcf665f4e0edf0299a3254854ce72d5d7ae9b6
briwyatt/MITcomputerScience101
/lecture03/lecture03.py
1,261
4.15625
4
# find the square root of a perfect square # x = 16 # ans = 0 #counter variable # while ans*ans <= x: # ans = ans + 1 # print(ans) # Is the number Even or Odd? # # if (x/2)*2 == x: # print("Even") # else: # print("Odd") # x = 150 #the number we are testing in this case # ans = 0 #counter variable # if x >= 0: # while ans*ans < x: # ans = ans +1 # print("ans=", ans) # if ans*ans != x: # print(x, 'is not a perfect square') # else: print(ans) # else: print( x, ' is a negative number') # #what are all the divisors of an integer? x = 10 i = 1 #counter is initalized while i < x: #the end test if x%i === 0: print('divisor', i) i = i +1 # #the for loop does the same thing as the divisor above # x = 10 # for i in range(1,x): #give you all numbers up to, but not including x # if x%i == 0: # print('divisor:', i) x = 1515361 if x > 0: for ans in range(1,x): if ans*ans == x: print(ans) break #collect the divisors that are printed as we go along x = 100 divisors = () for i in range(1,x): if x%i == 0: divisors = divisors + (i) #run a loop where I need to collect things together #
true
5842de32ce5fc0fba622d0d07b63eea91cd7471f
Panmax/codewars-python
/look_and_say.py
1,524
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: 'Panmax' """ There exists a sequence of numbers that follows the pattern 1 11 21 1211 111221 312211 13112221 1113213211 . . . Starting with "1" the following lines are produced by "saying what you see", so that line two is "one one", line three is "two one(s)", line four is "one two one one". Write a function that given a starting value as a string, returns the appropriate sequence as a list. The starting value can have any number of digits. The termination condition is a defined by the maximum number of iterations, also supplied as an argument. """ def look_and_say(data='1', maxlen=5): results = [] for i in range(maxlen): index = 0 _data = '' while True: n = 1 d = data[index] for _ in data[index+1:]: if _ == d: n += 1 index += 1 else: break _data += str(n) + d index += 1 if index >= len(data): break data = _data results.append(data) return results from itertools import groupby def _look_and_say(data='1', maxlen=5): L = [] for i in range(maxlen): data = "".join(str(len(list(g)))+str(n) for n, g in groupby(data)) L.append(data) return L if __name__ == '__main__': print look_and_say()
true
7b2e29ff849736e653137cc107b14d8eb58bc9bb
hwei-cs/leetcode-training
/solutions/greedy/solution123.py
1,126
4.25
4
""" 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成两笔交易。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 """ from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: buy1 = prices[0] buy2 = prices[0] profit1 = 0 profit2 = 0 for price in prices: buy1 = min(buy1, price) profit1 = max(profit1, price - buy1) buy2 = min(buy2, price - profit1) profit2 = max(profit2, price - buy2) print("Current Price:{}, Hold1:{}, Release1:{}, Hold2:{}, Release2:{}" .format(price, buy1, profit1, buy2, profit2)) return profit2 if __name__ == '__main__': solution = Solution() # prices = [3, 3, 5, 0, 0, 3, 1, 4] prices = [3, 5, 1, 7, 2, 6] ans = solution.maxProfit(prices) print(ans) prices = [2, 6, 1, 7, 3, 5] ans = solution.maxProfit(prices) print(ans)
false
1a955c47291f3a2c6e22549649a25957c431c2f4
naray89k/Python
/DeepDive_1/4_Numeric_Types/Comparison_Operators.py
1,584
4.34375
4
#!/usr/bin/env python # coding: utf-8 # ### Comparison Operators # #### Identity and Membership Operators # The **is** and **is not** operators will work with any data type since they are comparing the memory addresses of the objects (which are integers) 0.1 is (3+4j) 'a' is [1, 2, 3] # The **in** and **not in** operators are used with iterables and test membership: 1 in [1, 2, 3] [1, 2] in [1, 2, 3] [1, 2] in [[1,2], [2,3], 'abc'] 'key1' in {'key1': 1, 'key2': 2} 1 in {'key1': 1, 'key2': 2} # We'll come back to these operators in later sections on iterables and mappings. # #### Equality Operators # The **==** and **!=** operators are value comparison operators. # They will work with mixed types that are comparable in some sense. # For example, you can compare Fraction and Decimal objects, but it would not make sense to compare string and integer objects. 1 == '1' from decimal import Decimal from fractions import Fraction Decimal('0.1') == Fraction(1, 10) 1 == 1 + 0j True == Fraction(2, 2) False == 0j # #### Ordering Comparisons # Many, but not all data types have an ordering defined. # For example, complex numbers do not. 1 + 1j < 2 + 2j # Mixed type ordering comparisons is supported, but again, it needs to make sense: 1 < 'a' Decimal('0.1') < Fraction(1, 2) # #### Chained Comparisons # It is possible to chain comparisons. # For example, in **a < b < c**, Python simply **ands** the pairwise comparisons: **a < b and b < c** 1 < 2 < 3 1 < 2 > -5 < 50 > 4 1 < 2 == Decimal('2.0') import string 'A' < 'a' < 'z' > 'Z' in string.ascii_letters
true
457e4e90bda9e53e8554ca1064e184f4d4e4b841
naray89k/Python
/DeepDive_1/4_Numeric_Types/Floats_Equality_Testing.py
2,478
4.3125
4
#!/usr/bin/env python # coding: utf-8 # ## Floats - Equality Testing # Because not all real numbers have an exact ``float`` representation, equality testing can be tricky. x = 0.1 + 0.1 + 0.1 y = 0.3 x == y # This is because ``0.1`` and ``0.3`` do not have exact representations: print('0.1 --> {0:.25f}'.format(0.1)) print('x --> {0:.25f}'.format(x)) print('y --> {0:.25f}'.format(y)) # However, in some (limited) cases where all the numbers involved do have an exact representation, it will work: x = 0.125 + 0.125 + 0.125 y = 0.375 x == y print('0.125 --> {0:.25f}'.format(0.125)) print('x --> {0:.25f}'.format(x)) print('y --> {0:.25f}'.format(y)) # One simple way to get around this is to round to a specific number of digits and then compare x = 0.1 + 0.1 + 0.1 y = 0.3 round(x, 5) == round(y, 5) # We can also use a more flexible technique implemented by the ``isclose`` method in the ``math`` module from math import isclose help(isclose) x = 0.1 + 0.1 + 0.1 y = 0.3 isclose(x, y) # The ``isclose`` method takes two optional parameters, ``rel_tol`` and ``abs_tol``. # ``rel_tol`` is a relative tolerance that will be relative to the magnitude of the largest of the two numbers being compared. Useful when we want to see if two numbers are close to each other as a percentage of their magnitudes. # ``abs_tol`` is an absolute tolerance that is independent of the magnitude of the numbers we are comparing - this is useful for numbers that are close to zero. # In this situation we might consider x and y to be close to each other: x = 123456789.01 y = 123456789.02 # but not in this case: x = 0.01 y = 0.02 # In both these cases the difference between the two numbers was ``0.01``, yet in one case we considered the numbers "equal" and in the other, not "equal". Relative tolerances are useful to handle these scenarios. isclose(123456789.01, 123456789.02, rel_tol=0.01) isclose(0.01, 0.02, rel_tol=0.01) # On the other hand, we have to be careful with relative tolerances when working with values that are close to zero: x = 0.0000001 y = 0.0000002 isclose(x, y, rel_tol=0.01) # So, we could use an absolute tolerance here: isclose(x, y, abs_tol=0.0001, rel_tol=0) # In general, we can combine the use of both relative and absolute tolerances in this way: x = 0.0000001 y = 0.0000002 a = 123456789.01 b = 123456789.02 print('x = y:', isclose(x, y, abs_tol=0.0001, rel_tol=0.01)) print('a = b:', isclose(a, b, abs_tol=0.0001, rel_tol=0.01))
true
fd9e35d12f169d1abb5a971360db723c511f390f
naray89k/Python
/DeepDive_1/4_Numeric_Types/Booleans_Boolean_Operators.py
1,833
4.375
4
#!/usr/bin/env python # coding: utf-8 # ### Booleans: Boolean Operators # The way the Boolean operators ``and``, ``or`` actually work is a littel different in Python: # #### or # ``X or Y``: If X is falsy, returns Y, otherwise evaluates and returns X '' or 'abc' 0 or 100 [] or [1, 2, 3] [1, 2] or [1, 2, 3] # You should note that the truth value of ``Y`` is never even considered when evaluating the ``or`` result! # Only the left operand matters. # Of course, Y will be evaluated if it is being returned - but its truth value does not affect how the ``or`` is being calculated. # You probably will notice that this means ``Y`` is not evaluated if ``X`` is returned - short-circuiting!!! # We could (almost!) write the ``or`` operator ourselves in this way: def _or(x, y): if x: return x else: return y print(_or(0, 100) == (0 or 100)) print(_or(None, 'n/a') == (None or 'n/a')) print(_or('abc', 'n/a') == ('abc' or 'n/a')) # Why did I say almost? # Unlike the ``or`` operator, our ``_or`` function will always evaluate x and y (they are passed as arguments) - so we do not have short-circuiting! 1 or 1/0 _or(1, 1/0) # #### and # `X and Y`: If X is falsy, returns X, otherwise evaluates and returns Y # Once again, note that the truth value of Y is never considered when evaluating `and`, and that ``Y`` is only evaluated if it needs to be returned (short-circuiting) s1 = None s2 = '' s3 = 'abc' print(s1 and s1[0]) print(s2 and s2[0]) print(s3 and s3[0]) print((s1 and s1[0]) or '') print((s2 and s2[0]) or '') print((s3 and s3[0]) or '') # This technique will also work to return any default value if ``s`` is an empty string or None: print((s1 and s1[0]) or 'n/a') print((s2 and s2[0]) or 'n/a') print((s3 and s3[0]) or 'n/a') # The ``not`` function not 'abc' not [] bool(None) not None
true
121a2e796782216cde5bc857209565ce5e79738d
naray89k/Python
/DeepDive_1/2_A_Quick_Refresher_Basics_Review/Break_Continue_and_Try_Statements.py
2,400
4.28125
4
#!/usr/bin/env python # coding: utf-8 # ### Loop Break and Continue inside a Try...Except...Finally # Recall that in a ``try`` statement, the ``finally`` clause always runs: a = 10 b = 1 try: a / b except ZeroDivisionError: print('division by 0') finally: print('this always executes') # ----------------- a = 10 b = 0 try: a / b except ZeroDivisionError: print('division by 0') finally: print('this always executes') # ----------------- # So, what happens when using a ``try`` statement within a ``while`` loop, and a ``continue`` or ``break`` statement is encountered? a = 0 b = 2 while a < 3: print('-------------') a += 1 b -= 1 try: res = a / b except ZeroDivisionError: print('{0}, {1} - division by 0'.format(a, b)) res = 0 continue finally: print('{0}, {1} - always executes'.format(a, b)) print('{0}, {1} - main loop'.format(a, b)) # ----------------- # As you can see in the above result, the ``finally`` code still executed, # even though the current iteration was cut short with the ``continue`` statement. # This works the same with a ``break`` statement: a = 0 b = 2 while a < 3: print('-------------') a += 1 b -= 1 try: res = a / b except ZeroDivisionError: print('{0}, {1} - division by 0'.format(a, b)) res = 0 break finally: print('{0}, {1} - always executes'.format(a, b)) print('{0}, {1} - main loop'.format(a, b)) # ----------------- # We can even combine all this with the ``else`` clause: a = 0 b = 2 while a < 3: print('-------------') a += 1 b -= 1 try: res = a / b except ZeroDivisionError: print('{0}, {1} - division by 0'.format(a, b)) res = 0 break finally: print('{0}, {1} - always executes'.format(a, b)) print('{0}, {1} - main loop'.format(a, b)) else: print('\n\nno errors were encountered!') # ----------------- a = 0 b = 5 while a < 3: print('-------------') a += 1 b -= 1 try: res = a / b except ZeroDivisionError: print('{0}, {1} - division by 0'.format(a, b)) res = 0 break finally: print('{0}, {1} - always executes'.format(a, b)) print('{0}, {1} - main loop'.format(a, b)) else: print('\n\nno errors were encountered!') # -----------------
true
4332748d486b75a1b82e17d59a71e6fdfb89bf02
naray89k/Python
/OOPS_Concepts/cls_VarsEx.py
1,188
4.21875
4
#! /usr/bin/python #class Employee Starts Here class Employee(object): num_of_emps = 0 raise_amount = 1.04 #constructor def __init__(self,first,second,pay): self.first = first self.second = second self.pay = pay self.email = '{}.{}@company.com'.format(self.first.lower(),self.second.lower()) Employee.num_of_emps += 1 def fullname(self): return '{} {}'.format(self.first,self.second) def raise_pay(self): self.pay=self.pay*self.raise_amount #class Employee Ends Here emp_1 = Employee('Narayanan','Krishnan',50000) emp_1.raise_pay() print emp_1.raise_amount print emp_1.__dict__ emp_2 = Employee('Indhumathi','Gopal',60000) emp_2.raise_amount=1.10 emp_2.raise_pay() print emp_2.raise_amount print emp_2.__dict__ # ========================= # Whats the take away from this Code. # When 'raise_amount' is available in the instance namespace scope, Then it will be used in the function 'raise_pay' # If that is not available, then 'raise_amount' in Class Variable will be used, In case that is not available in Class Scope. # Then it will be checked in its Parents Classes one by One, all the way till Object Class.
false
a8cd1fc49ca32a6a798216109975e0f68c8a4e25
jatiinyadav/Python
/Class/Abstract.py
957
4.1875
4
# Abstract class # Abstract Method, in a method where we have nothing in the method and we use pass from abc import ABC, abstractmethod class Computer(ABC): @abstractmethod def process(self): pass class Laptop(Computer): def process(self): print("Its running: ") class Programmer: def work(self, com): print("Solving bugs") com.process() com1 = Laptop() # com = Computer() com1.process() prog1 = Programmer() prog1.work(com1) print("---------") class Animal(ABC): def move(self): pass class Human(Animal): def move(self): print("I can walk and run") class Snake(Animal): def move(self): print("I can crawl") class Dog(Animal): def move(self): print("I can bark") class Lion(Animal): def move(self): print("I can roar") # Driver code R = Human() R.move() K = Snake() K.move() R = Dog() R.move() K = Lion() K.move()
true
59fa82d39490e6c10e8fc7a9b0c1ee04ef1838f2
KevinFTD/python_presentation
/exmaples/example8_cls_field.py
371
4.125
4
#!/usr/bin/env python2.7 #encoding=utf-8 ''' Created on 2015年4月7日 @author: kevinftd ''' class MyClass(object): key1 = 10 key2 = [] def __init__(self): ''' Constructor ''' self.key1 = 20 self.key2.append(30) instance = MyClass() print instance.key1 print MyClass.key1 print instance.key2 print MyClass.key2
true
e71d5f773f5f8236534832b40d2ddca0ad1b412b
KevinFTD/python_presentation
/exmaples/example_new_init.py
740
4.28125
4
#!/usr/bin/env python2.7 #encoding=utf-8 ''' Created on 2015年3月23日 @author: kevinftd __new__创建类实例,__init__做初始化 ''' class base(object): def __init__(self, arg="base"): self.str = arg def __str__(self): return self.str class strings(base): def __init__(self, arg=""): base.__init__(self, "%s__post"%(arg)) print strings() print strings("abc") ################## class inch1(float): "Convert from inch to meter" def __new__(cls, arg=0.0): return float.__new__(cls, arg*0.0254) print inch1(12) class inch2(float): def __init__(self, arg=0.0): float.__init__(self, arg*0.0254) print inch2(12) # just 12, because __init__ in float does nothing
true
9cee8bf4cf6ad3288a806267e0db89fd027533dc
Phillip215/digitalcrafts
/week1/day3/calculator.py
488
4.125
4
calc = int(input("I'm just your everyday calculator put in a number ")) opp = input("Now put in a operand please ") calc2 = int(input("Now the other number ")) # Subtract if opp == "-": ans = calc - calc2 print("Your answer is %s" % (ans)) # Multiply if opp == "*": wer = calc * calc2 print("Your answer is %s" % (wer)) # Add if opp == "+": sol = calc + calc2 print("Your answer is %s" % (sol)) if opp == "/": ution = calc / calc2 print("Your answer is %s" % (ution))
false
eb375ea245384001f96c4f74b6da6e266f97477a
Phillip215/digitalcrafts
/week1/day3/inputPython.py
1,255
4.25
4
# name_of_user = input("What is your name?") nameOfUser = input("What is your first name?") # Store the users first name into a number value that we can use lengthOfUserName = len(nameOfUser) # While loop # A condition has to be true to keep your loop running while (lengthOfUserName < 1): nameOfUser = input("What is your first name?") lengthOfUserName = len(nameOfUser) lastNameOfUser = input("What is your last name?") # Store the users last name into a number value that we can use lengthOfUserLastName = len(lastNameOfUser) # Take the users last name while (lengthOfUserLastName < 1): lastNameOfUser = input("What is your last name?") lengthOfUserLastName = len(lastNameOfUser) # if statements. Do something if a certain condition happens or doesn't happen if lengthOfUserName > 0: nameOfFriend = input("What is your friends name?") print("Your friends name is", nameOfFriend) else: print("Please enter at least one letter...PLEASE MY BOY") # print("This is the length of the users first name", lengthOfUserName) # print("This is the length of the users last name", lengthOfUserLastName) # print("The user name is %s %s " % (nameOfUser, lastNameOfUser)) # print("Hello %s %s, welcome to python" % (nameOfUser, lastNameOfUser))
true
9574c844cad27b40ae97235b8ce79510c9f814b8
Hadirback/python
/Lesson9_Lists/main.py
503
4.21875
4
# Пустой список empty_list = [] friends = ['Max', 'Leo', 'Kate'] # тип данных print(type(friends)) print(friends[1]) # С конца print(friends[-1]) # срезы print(friends[1:3]) print(friends[:2]) print(friends[1:]) print(len(friends)) friends.append('Ron') friend = friends.pop(3) print(friend) friends.remove('Leo') print(friends) friends.append('Ron') del friends[1] print(friends) print('Max' in friends) hero = 'Superman' if 'man' in hero: print('Усть!')
false
3fd11843ed03b30a3a694dd9508262418fa645f3
nagask/python-essentials
/basic_collections/lists/sorting.py
1,890
4.25
4
import operator # Sort a List Alphabetically my_list = ['mango', 'apple', 'pear', 'orange'] my_list.sort() for item in my_list: print (item) """ Outputs: apple mango orange pear """ # Return a Copy of a List, Sorted Alphabetically my_list = ['mango', 'apple', 'pear', 'orange'] my_sorted_list = sorted(my_list) for item in my_sorted_list: print (item) """ Outputs: apple mango orange pear """ # Sort a List in Reverse Alphabetical Order my_list = ['mango', 'apple', 'pear', 'orange'] my_list.sort(reverse=True) for item in my_list: print (item) """ Outputs: pear orange mango apple """ # Return a copy of a List Sorted in Reverse Alphabetical Order my_list = ['mango', 'apple', 'pear', 'orange'] my_sorted_list = sorted(my_list, reverse=True) for item in my_list: print (item) """ Outputs: pear orange mango apple """ # Sort a List by a Child List's (or Tuple's) Value my_list = [ ['z', '3'], ['a', '2'], ['g', '4'] ] my_list.sort(key=operator.itemgetter(0)) for item in my_list: print (item) """ Outputs: ['a', '2'] ['g', '4'] ['z', '3'] """ # Sort a List by a Child List's (or Tuple's) Value in Reverse my_list = [ ['z', '3'], ['a', '2'], ['g', '4'] ] my_list.sort(reverse=True, key=operator.itemgetter(0)) for item in my_list: print (item) """ Outputs: ['a', '2'] ['g', '4'] ['z', '3'] """ # Sorting a list by the length of an inner list from collections import namedtuple result_row = namedtuple('ResultRow', ['cell_count', 'reason', 'results']) a = result_row(cell_count=4, reason='AfternoonSnackManager', results=[1,2,4,5,6]) b = result_row(cell_count=4, reason='LunchManager', results=[1,2]) c = result_row(cell_count=4, reason='DinnerManager', results=[1,2,4,5]) rows = [a, b, c] print(sorted(rows, key=lambda x: len(x.results)), end='\n')
true
94790c09de2d538a75765223a3db2f7d6e98fad8
nagask/python-essentials
/advanced_collections/defaultdict.py
1,672
4.4375
4
""" The collections module has a handy tool called defaultdict. The defaultdict is a subclass of Python’s dict that accepts a default_factory as its primary argument. The default_factory is usually a Python type, such as int or list, but you can also use a function or a lambda too. It’s basically impossible to cause a KeyError to happen as long as you set the default_factory to something that makes sense. """ from collections import defaultdict # Assume we have no Counter collection and we want to create a frequency distribution of the words appearing in a list frequency_distribution = {} words = ['gaurav', 'keswani', 'gaurav', 'yelp', 'snowflake', 'yelp', 'gaurav'] for word in words: # If the word is already present in the dictionary, increment the count by 1 if word in frequency_distribution: frequency_distribution[word] += 1 # If the word is not present in the dictionary, set the count to 1 since this is the first occurence else: frequency_distribution[word] = 1 print(frequency_distribution) # We can simplify the above process by using default dicts # Here we specify the default value type of the dict to be int. Thus, the default value of any key will be the default # value of type int i.e. 0 frequency_distribution = defaultdict(int) for word in words: # The first time a word is encountered, it won't be in the dictionary. Thus, it frequency_distribution[word] will # have the value of 0 and will get 1 added to it. # Thus, the defaultdict will automatically assign zero as the value to any key it doesn’t already have in it frequency_distribution[word] += 1 print(frequency_distribution)
true
c4f40fb2866513f5e3fa663147cf4f6e17d317f0
nancymukuiya14/Password-Locker
/user_test.py
1,458
4.21875
4
import unittest from user import User class TestClass(unittest.TestCase): """ A Test class that defines test cases for the User class. Args: unittest.TestCase: TestCase class that helps in creating test cases """ def setUp(self): """ Method that runs before each individual test methods run. """ self.new_user = User('Nancykigotho','Maldives106') def test_init(self): """ Checking if the object has been initialized correctly """ self.assertEqual(self.new_user.username,'Nancykigotho') self.assertEqual(self.new_user.password,'Maldives106') def test_save_user(self): """ Test if a new user has been saved into the User list """ self.new_user.save_user() self.assertEqual(len(User.user_list),1) def test_delete_user(self): """ Test if a user can be deleted from the user list """ self.new_user.save_user() test_user = User('Nancykigotho','Maldives106') self.assertEqual(len(User.user_list),1) self.new_user.delete_user() self.assertEqual(len(User.user_list),0) def test_user_exists(self): """ Test if a user can be found by username """ self.user_exists = User.check_user('Nancykigotho','Maldives106') if __name__ == '__main__': unittest.main()
true
dc038c84242c9fc216880224a46dfc8f38a81607
sxlongwork/pythonPro
/列表-字符串/str4.py
455
4.125
4
# str的切片,倒序 str1 = "abcdefg" # 切片 print(str1[2:5]) # cde print(str1[0:2]) # ab print(str1[0:-1]) # abcdef print(str1[2:-2]) # cde print(str1[:]) # abcdefg print(str1[:3]) # abc print(str1[3:]) # defg print(str1[1:5:2]) # bd print(str1[:3:-1]) # gfe print(str1[::-2]) # geca print("================") # 倒序 str2 = "123456789" print(str2[::-1]) # 987654321
false
ec21e14cb1657634773d982f6f64c3b6ecd5a5be
sxlongwork/pythonPro
/列表-字符串/str_practice4.py
548
4.21875
4
# 字符串的常见操作 str1 = "abcdefg" # 字符串的长度 str1.__len__() len(str1) # 固定10个字符,不够的补* str1.center(10, '*') # 一共10个字符,str1居中,不够位补"*" str1.ljust(10, '*') # 一共10个字符,str1居左,不够位补"*" str1.rjust(10, '*') # 一共10个字符,str1居右,不够位补"*" # 判断字符串是否以"xxx"结尾或开头,"xxx"表示任务字符串 str1.startswith("abc") str1.endswith("bbc") # 判断字符'a'在字符串里共出现了多少次 str1.count('a')
false
75de2db9f2329d1b80d8321495e658f8d56e017c
sxlongwork/pythonPro
/if-for-while/for_practice2.py
250
4.28125
4
# for与range 使用 for i in range(3): print(i, end=" ") print() for i in range(1, 5): print(i, end=" ") print() for i in range(3, 10): print(i, end=" ") print() # help(range) for i in range(100, 0, -2): print(i, end=" ") print()
false
ac01d9f5773e53964b0e28aec3bafdf1a3a33860
sxlongwork/pythonPro
/if-for-while/tuple.py
1,925
4.375
4
# tuple 使用 # 元组tuple一旦定义,就不能改变,这里的不能改变指的是指向不变改变 classmates = ("zhangsan", "lisi", "wangwu", "xiaoming") print(len(classmates)) print(classmates) for i in range(len(classmates)): print(classmates[i]) # 在定义tuple时,元素就必须确定下来 aa = (1, "ok") # aa[0] = 2 tuple元素不能修改 print(aa) # 在定义只有一个元素的tuple时,注意要在第一个元素后加上",",aa=(2,),否则会被认为是赋值aa=(2) aa = (2, ) # tuple print(type(aa)) aa = (2) # int,被认为是一个数字 print(type(aa)) # tuple的元素指向不变,但指定的内容可变 classes = [1, 2] tuple1 = ("a", "b", classes) # tuple1指向classes没有变,但classes本身的内容是可以变的 print(tuple1) classes[0] = 11 classes[1] = 22 print(tuple1) ''' 总结 1.tuple与list类似,但是是不可变的,一旦定义,就不能修改 2.获取元素的方式和元素个数与list相同 3.当定义只有一个元素的tuple时,注意要在元素后加上"," 4.tuple一旦初始化后就不能改变指的是指向不能变,但被指的元素内容可变 ''' # 测试使用 print("===============================") tuple1 = (1, 2, 3, 2, 4, 5) # 获取元组元素个数,即元素长度 print(len(tuple1)) print(tuple1.__len__()) # for i in tuple1: # print(i) # print(tuple1[::]) # 获取所有元素 # print(tuple1[::-1]) # 倒序打印元组所有元素,tuple1元素本身不变 # print(tuple1[1:3]) # 获取下标为1, 2的元素(2, 3) # print(tuple1[:4]) # 不写起始位置,默认从头开始,0,1,2,3,(1,2,3,4) # print(tuple1[3:]) # 不写结束位置,默认一直截到最后,3,4,(4,5) print(tuple1.count(2)) # .count(e),获取元素e在元组中出现的次数 print(tuple1.index(2)) # .index(e),获取元素e在元组中第一次出现时的下标
false
64ec88ce1f194a7fc7d630deedd6208f10be0482
teganbroderick/Calculator2
/calculator.py
1,929
4.25
4
"""A prefix-notation calculator.""" from arithmetic import * def greet_player(): """greets player""" print("Hi Player! Welcome to the calculator.") def turn_str_into_int(l): """takes list and turns string numbers into integers""" operator_list = ["+", "-", "*", "/", "**", "squares", "cubes", "pows", "%"] new_list = [] for item in l: if item in operator_list: new_list.append(item) if item.isdigit(): new_list.append(int(item)) else: new_list.append(item) return new_list def play_calculator(a): """calls calculation functions based on user input""" a = turn_str_into_int(a.split(" ")) if a[0] == "+": print(add(a[1], a[2])) elif a[0] == "-": print(subtract(a[1], a[2])) elif a[0] == "*": print(multiply(a[1], a[2])) elif a[0] == "/": print(divide(a[1], a[2])) elif a[0] == "**" and a[2] == 2 or a[0] == "squares": print(square(a[1])) elif a[0] == "**" and a[2] == 3 or a[0] == "cubes": print(cube(a[1])) elif a[0] == "**" and not a[2] == 2 and not a[2] == 3 or a[0] == "pows": print(power(a[1], a[2])) elif a[0] == "%": print(mod(a[1], a[2])) else: print("Sorry cannot compute! Try again.") def continue_game(b_input): """takes user input to return true or false for continuing game""" if b_input.upper() == "NO": print("Goodbye!") return False else: return True def calculate(): """main calculator function""" greet_player() while True: play_calculator(a = input("What is your calculation? Please enter the operator first, followed by the numbers. Leave spaces between your entries. > ")) repeat_calc = continue_game(b_input = input("Would you like to play again?")) if repeat_calc == False: break calculate()
true
9156f4bdcf549e4820910cacc8b25ddf53068652
vennie1988/python_ref_code
/lambda.py
680
4.34375
4
""" lambdas: lambda expressions (sometimes is called lambda forms) are used to create anonymous functions. The expression lambda arguments: expression yields a function object. The unnamed object behaves like a function object defined with the following. """ lambda_expr ::= "lambda" [parameter_list]: expression lambda_expr_nocond ::= "lambda" [parameter_list]: expression_nocond def <lambda>(arguments): return expression """ origin function """ def f(x): return x+2 f(3) """ which can be replace by """ g = lambda x: x+2 g(3) (lambda x: x+2)(3) """ real world lambda functions """ process_function = collapse and (lambda s: " ".join(s.splite())) or (lambda s: s)
true
475bded227f8ec6730ecececc165173b0e98bdf0
HKang42/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
2,158
4.28125
4
""" reverse the contents of the list using recursion, *not a loop.* For example, ``` 1->2->3->None ``` would become... ``` 3->2->1->None ``` # CORRECITON: Loops are okay. Recursion is optional. """ class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False current = self.head while current: if current.get_value() == value: return True current = current.get_next() return False # use recursion (optional) to reverse a singly-linked list # refer to "problem_visualization.jpg" for a visualization of the problem def reverse_list(self, node, prev): # check to see if list is empty if self.head == None: return # if the next node is None, we have reached the end of the list (base case) # assign head to this node and set its pointer to the previous node (reverse pointer direction) elif node.next_node == None: self.head = node node.set_next(prev) return self # If we are not at the base case else: # Get the next node. This will become the "current" node next = node.next_node # Reverse the direction of the current node's pointer node.next_node = prev # Recursively call reverse_list # Input the "next" node as the current node and the current node as the previous # This will let us reverse the pointer between them and move us closer to the tail (base case) self.reverse_list(next, node)
true
b6d2aea38715a7ae5bf511a1bef05c1b45df0e4c
Ksheekey/RBootcamp
/cw/03-Python/2/Activities/02-Stu_KidInCandyStore-LoopsRecap/Unsolved/kid_in_candy_store.py
672
4.34375
4
# The list of candies to print to the screen candy_list = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Swedish Fish", "Skittles", "Hershey Bar", "Starbursts", "M&Ms"] # The amount of candy the user will be allowed to choose allowance = 5 # The list used to store all of the candies selected inside of candy_cart = [] # Print out options i = 0 for candy in candy_list: print('[' + str(i) + ']' + " " + candy) i=i+1 need_more="yes" while need_more == "yes" and len(candy_cart) < 5: selected_item = int(input("Choose the Number : ")) candy_cart.append(candy_list[selected_item]) need_more=input("Do you need more? ") print (candy_cart)
true
29cf7ea6745659950bcee0725ee5a8a6556c37ce
Ksheekey/RBootcamp
/cw/03-Python/1/Activities/04-Stu_DownToInput/Unsolved/DownToInput.py
1,016
4.125
4
# Take input of you and your neighbor me = input("What is your name? ") neighbor = input("What is your neighbors name? ") # Take how long each of you have been coding me_coding = int(input("How many years have you been coding? ")) neighbor_coding = int(input("How long has your neighbor been coding? ")) # Add total years total_coding = me_coding + neighbor_coding # Print results print(f"{me} has been coding for {me_coding} years, {neighbor} has been coding for {neighbor_coding} years, together we have been coding for {total_coding} years!") #your_first_name = input("what is your first name? ") #neighbor_first_name = input("whatis your neighbors first name? ") #months_ive_coded = input("How many months have you been coding? ") #months_neighbor_coded = input("How many months has your neighbor been coding? ") #total_months_coding=int(months_ive_coded) + int(months_neighbor_coded) #print(f"{your_first_name} and {neighbor_first_name} have been coding for {total_months_coding} years ")
true
248837d55a72ce380e091e8995212ebd1d3d5570
Alapont/PythonConBetsy
/main.py
645
4.125
4
#!/c/Users/pablo/AppData/Local/Programs/Python/Python38/python import math print("Hola Pablo") # función para ver funciones # nombre: persona a la que saludo # años: años de la persona que saludo def my_function(nombre, años): print("Holiii " + nombre + ", tienes ") print(años) if (años > 1): # then print("años 💩") else: print("año 💩") # El cuadrado de una hipotenusa de un triangulo rectángulo es igual a la suma de los dos catetos al cuadrado # h=√(c²+c²) def pitagoras(cateto1, cateto2): return math.sqrt(cateto1*cateto1+cateto2**2) my_function("Quevedo", 1) x = float(3.2)
false
3a41cfe8aba9d9aa2daea650cc8a9f44121e3f1f
dupjpr/Hacker_Rank_challenge
/Agenda_while.py
1,586
4.125
4
print("Small Calculator") print(""" Menu Options 1. Sum. 2. Weight Converter. 3. Guess Game. 4. Quit. """) command="" while command != 4: command=int(input("Opcin:")) if command == 1: print("__"*20) print("You are in the space to sum two numbers") a=int(input("First number: ")) b=int(input("Second number: ")) total=a+b print(f"The result is {total}.") print("__" * 20) elif command == 2: print("__"*20) print("You can convert your weight") weight = int(input("Your Weight: ")) tip = input("Write if this is in (l)bs or (K)g:") if tip == "l": a=weight*0.45 print(f"The weight is {a} Kg.") elif tip == "k": a=weight/0.45 print(f"The weight is {a} lbs") else: print("Try again and write l or k") print("__" * 20) elif command == 3: print("__" * 20) print("GUESS GAME") print("You have to guess a number between 1 and 10") secret_number = 5 counter = 0 limit_counter = 3 while counter < limit_counter: guess = int(input("Type your guess:")) counter = counter + 1 if guess == secret_number: print("You Won!!") print("__" * 20) break else: print("You lost") print("__" * 20) elif command == 4: print("__" * 20) print("Good by") break else: print("It's not an option, try again")
true
d4f70cd8f154b59e562344c4525f2ae83884cce5
ensarerturk/globalAiHubPythonHomework
/homework_1.py
1,348
4.25
4
#create an list info=[] #5 values received from the user and added to the list name = input("Please enter your name : ") info.append(name) lastname = input("Please enter your lastname : ") info.append(lastname) #control was done. If the expected value is not entered, it has been requested to be re-entered. try: age = int(input("please enter your age : ")) info.append(age) except ValueError: age = int(input("Please enter your age in integer type : ")) info.append(age) job = input("Please enter your job : ") info.append(job) try: salary = float(input("Please enter your salary :")) info.append(salary) except ValueError: salary = float(input("Please enter your salary in float type. :")) info.append(salary) #Printing to the screen with the "f-string" method print(f"Name : {name} \nLast Name : {lastname} \nAge : {age} \nJob : {job} \nSalary : {salary}") #Value types are print to the screen with the ".format" method. print("Name type : {} \nLastname type : {} \nAge type : {} \nJob type : {} \nSalary type : {}".format(type(info[0]), type(info[1]), type(info[2]), type(info[3]), type(info[4])))
true
051ab9274fa7a781326199086077b05fecba8a88
cdebruyn/PackageName
/PackageName/sorting.py
1,251
4.5625
5
def bubble_sort(items): '''Return array of items, sorted in ascending order. Argument: items (array): an array of numbers. Returns: array: items sorted in ascending order. Examples: >>> bubble_sort([5,4,3,2,1]) [1,2,3,4,5] >>> bubble_sort([1,3,2]) [1,2,3] >>> bubble_sort([1,5,3,9,7,4]) [1,3,4,5,7,9] ''' return sorted(items) def merge_sort(items): '''Return array of items, sorted in ascending order. Argument: items (array): an array of numbers. Returns: array: items sorted in ascending order. Examples: >>> bubble_sort([5,4,3,2,1]) [1,2,3,4,5] >>> bubble_sort([1,3,2]) [1,2,3] >>> bubble_sort([1,5,3,9,7,4]) [1,3,4,5,7,9] ''' return sorted(items) def quick_sort(items): '''Return array of items, sorted in ascending order. Argument: items (array): an array of numbers. Returns: array: items sorted in ascending order. Examples: >>> bubble_sort([5,4,3,2,1]) [1,2,3,4,5] >>> bubble_sort([1,3,2]) [1,2,3] >>> bubble_sort([1,5,3,9,7,4]) [1,3,4,5,7,9] ''' return sorted(items)
true
8ee588750f32ad7ddad6a68f9c64252b94489913
ChRiStIaN3421/programacion
/unidad_3.1/ejercicio24.py
1,447
4.125
4
flag1 = True while flag1: primer_color=input("ingrese el 1° color (rojo o azul): ") if not primer_color.isalpha(): # verificamos q se haya escrito un string print("ingrese un string") elif primer_color=="rojo": while flag1: segundo_color=input(f"ingrese el 2° color (azul o verde) para mezclar el {primer_color}: ") if not segundo_color.isalpha(): # verificamos q se haya escrito un string print("ingrese un string") elif segundo_color=="azul": print(f"el color formado entre {primer_color} y {segundo_color} es Magenta") flag1 = False elif segundo_color=="verde": print(f"el color formado entre {primer_color} y {segundo_color} es Amarillo") flag1 = False else: print("Ingrese por favor azul o verde") elif primer_color=="azul": while flag1: segundo_color=input(f"ingrese el 2° color (verde o rojo) para mezclar el {primer_color}: ") if not segundo_color.isalpha(): # verificamos q se haya escrito un string print("ingrese un string") elif segundo_color=="verde": print(f"el color formado entre {primer_color} y {segundo_color} es Cian") flag1 = False elif segundo_color=="rojo": print(f"el color formado entre {primer_color} y {segundo_color} es Magenta") flag1 = False else: print("Ingrese por favor rojo o verde") else: print("Ingrese por favor azul o rojo")
false
027032a9ec3d0051dcf62620aa102d540d7d1b15
ChRiStIaN3421/programacion
/unidad_3.1/ejercicio27.py
210
4.21875
4
while True: palabra=input("ingrese una palabra:") if palabra == "salir": print(palabra) break elif palabra == "hola" or "chau": continue else: print(palabra)
false
9c06c1861d4e166d45e81c23111cfd09e8faa314
wfields1/MIS3545
/Assignments/assignment_1/palindrome.py
646
4.25
4
def isPalindrome(s): """ Write a recursive function isPalindrome(string) that returns True if string is a palindrome, that is, a word that is the same when reversed. Examples of palindromes are “deed”, “rotor”, or “aibohphobia”. Hint: A word is a palindrome if the first and last letters match and the remainder is also a palindrome. """ if(len(s) < 2): return True if(s[0] != s[-1]): return False else: return isPalindrome(s[1:-1]) inputStr = input("Enter a string: ") if isPalindrome(inputStr): print("That's a palindrome.") else: print("That isn't a palindrome.")
true
b07940d23f4b7feec4b29662d117dece7090d68a
kristjanleifur4/forritun-2020
/timaverk7.py
2,675
4.125
4
# The function definition goes here def output_string(input_str): for i in input_str: return input_str[::2] input_str = input("Enter a string: ") # You call the function here print("Every other character:",output_string(input_str)) # Your function definition goes here def digit_count(input_str): digit_count = 0 for ch in input_str: if ch.isdigit(): digit_count += 1 return digit_count input_str = input("Enter a string: ") # Call the function here digit_count = digit_count(input_str) print("No. of digits:", digit_count) # max_of_three function definition goes here def find_max(first, second, third): maximum = 0 if first > second and first > second: maximum = first elif second > first and second > third: maximum = second else: maximum = third return maximum first = int(input("Enter first number: ")) second = int(input("Enter second number: ")) third = int(input("Enter third number: ")) # Call the function here maximum = find_max(first, second, third) print("Maximum:", maximum) # is_prime function definition goes here def is_prime(x): if x >= 2: for i in range(2,x): if not ( x % i ): return False return True max_num = int(input("Input an integer greater than 1: ")) # Call the function here repeatadly from 2 to max_num and print out the appropriate message for i in range(2, max_num + 1): if is_prime(i): print(i,"is a prime") else: print(i, "is not a prime") # palindrome function definition goes here def palindrome(in_str): in_str = in_str.replace(".","").replace("'","").replace(" ","").replace(",","").replace("!","").lower() if in_str == in_str[::-1]: return True return False input_str = input("Enter a string: ") # call the function and print out the appropriate message if palindrome(input_str): print('"{}" is a palindrome.'.format(input_str)) else: print('"{}" is not a palindrome.'.format(input_str)) #Your function definition goes here def valid_date(date_str): if len(date_str) == 8: for ch in date_str: if ch == "/": return False if ch.isalpha(): return False date_str.split(".") day = int(date_str[:2]) month = int(date_str[3:5]) year = int(date_str[-2:]) if day > 0 and day <= 31 and month >= 1 and month <= 12 and year >= 0 and year <= 99: return True return False date_str = input("Enter a date: ") if valid_date(date_str): print("Date is valid") else: print("Date is invalid")
true
2eacfb81be308feccf1097b2bda36a780eb61dd2
mandalpawan/Data-Stucture
/Stack/Stack.py
782
4.125
4
''' Stack In Data Stucture ''' class Stack: def __init__(self): self.item = [] "PUSH method is use for insert element in TOP of the STACK" def push(self,item): self.item.append(item) "POP method is use to remove element from top of the stack" def pop(self): return self.item.pop() "Print the Stack elemnt" def get_stack(self): return self.item "Check for Stack is empty or not" def is_empty(self): return self.item == [] "Check top element of the Stack" def peek(self): if not self.is_empty(): return self.item[-1] else: return "Stack is Empty" "Check for length of the stack" def length(self): return len(self.item)
true
e009e166a5260accd340fe69ad86e01f74fa589e
mandalpawan/Data-Stucture
/Stack/binary.py
392
4.15625
4
"Use Stack and Convert Decimal Number To Binary Number" from Stack import Stack def binary_Convertor(number): s = Stack() while number > 0: remainder = number %2 s.push(remainder) number = number //2 binary_number = "" while not s.is_empty(): binary_number += str(s.pop()) return binary_number print(binary_Convertor(242))
true
80cb7a60563bcd2b1a9f0a9554b237c7b6ebd978
GoogolDKhan/Student-Library
/main.py
2,592
4.15625
4
class Library: # Constructor def __init__(self, list_of_books): self.books = list_of_books # Method to display the books available in the library def display_available_books(self): print("Books available in this library are: ") for index, book in enumerate(self.books): print(f"{index+1}. {book}") # Method to borrow a book from the library def borrow_book(self, book_name): if book_name in self.books: print( f"You have been issued {book_name}. Please keep it safe and return it within 30 days" ) self.books.remove(book_name) return True print( "Sorry. This book is either not available or has already been issued to someone else." ) return False # Method to return a book from the student to library def return_book(self, book_name): self.books.append(book_name) print( "Thanks for returning this book! Hope you enjoyed reading this book. Have a great day ahead!" ) class Student: # Method to request a book from the library def request_book(self): self.book = input("Enter the name of the book you want to borrow: ") return self.book # Method to return the borrowed book back to the library def return_book(self): self.book = input("Enter the name of the book you want to return: ") return self.book if __name__ == "__main__": # Book available in thw Central Library central_library = Library( [ "Material Science", "Mechanics of Solids", "Fluid Mechanics", "Dynamics of Machines", "Manufacturing Process", "Heat Transfer", ] ) student = Student() while True: welcome_message = """ =====Welcome to Central Library===== Please choose an option: 1. List all the books 2. Request a book 3. Add or Return a book 4. Exit the library """ print(welcome_message) choice = int(input("Enter a choice: ")) if choice == 1: central_library.display_available_books() elif choice == 2: central_library.borrow_book(student.request_book()) elif choice == 3: central_library.return_book(student.return_book()) elif choice == 4: print("Thanks for choosing Central Library. Have a great day ahead!") break else: print("Invalid Choice!")
true
87fee067b223e967327ac784b0234073b5d8e04c
monumk/How-to-add-elements-in-list.
/appe.py
848
4.15625
4
'''how to add elements in list''' '''append method add only 1 element at a time at the end of the list''' l1=[10,20,30,40] l1.append(50) print(l1) #output [10,20,30,40,50] l1.append(60) print(l1) #output [10,20,30,40,50,60] '''insert method of the list add one element on the specific position index wise''' l2=[50,60,70,80] l2.insert(1,100) print(l2) #output [50, 100, 60, 70, 80] list1=['monu','durga','arun','sunny'] list1.insert(2,'Rahul') print(list1) #output ['monu', 'durga', 'Rahul', 'arun', 'sunny'] '''extend method of the list add a sequence in list at a time''' list2=[1,2,3,4,5] list2.extend([10,20,30,40]) print(list2) #output [1, 2, 3, 4, 5, 10, 20, 30, 40] list3=[30,40,50] list3.extend(range(20,26)) print(list3) #output [30, 40, 50, 20, 21, 22, 23, 24, 25]
false
17c0758cf196d5916becaaffad5383fea3827536
MohitMehta257/Show-me-the-Data-Structures
/problem_2.py
879
4.375
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ output=[] l=suffix if path: l=suffix+'/'+path for each in os.listdir(l): l1=l+'/'+each if os.path.isfile(l1) and l1.endswith(".c"): output.append(l1) elif os.pathisdir(l1): output=find_files(l,each,l) return output print(find_files('.', 'testdir')) print(find_files('.', '')) print(find_files('.', 'testdir/subdir3'))
true
76fc2fc987ac8afe42719e3d9563dc02f11d81e7
VasBu/lrn_python3
/src/Variables.py
2,526
4.1875
4
def basics(): print("\n****** Create and Delete Variables ******") x = 42 # assigning integer variable print("x = ", x) print("id(x) = ", id(x)) # get reference (identifier) of the variable y = x # assign variable to another print("y = x") print("y = ", y) print("id(x), id(y) = (%s, %s)" % (id(x), id(y))) # they are referencing to a same memory location y = 66 # assign a new value for one of the values print("y = ", y) print("id(x), id(y) = (%s, %s)" % (id(x), id(y))) # the Python creates new memory location for the changed variable try: del y # delete variable print("y =", y) except Exception as e: print("[Error]", e) def advanced(): print("\n****** Advanced Working with Variables ******") x = 2 y = "Vasil Buraliev" z = .5 print('Detect type of a variable with `type` keyword\n x = %s(%s)\n y = %s(%s)\n z = %s(%s)' % (x, type(x), y, type(y), z, type(z))) a = b = c = 1 print("Multiple assignment. a = b = c = %s" % (a)) a,b,c = 1,2,"Vasil" print("Another way of assignment variables a,b,c = %s,%s,%s" % (a, b, c)) def global_local_variables_helper(): global s print(s) s = "I love Paris!" print(s) def global_local_variables(): print("\n****** Global and Local Variables ******") global_local_variables_helper() print(s) def non_local_variables(): print("\n****** NonLocal Variables ******") s = "I love Paris!" def nested_func(): nonlocal s s = "I Love Valencia!" print("before calling nested_func() s = " + s) print("calling nested_func() now:") nested_func() print("After calling nested_func() s = " + s) def nested_global_variables(): print("\n****** Nested Global Variables ******") def nested_func(): global s s = "I Love Valencia!" print("before calling nested_func() s = " + s) print("calling nested_func() now:") nested_func() print("After calling nested_func() s = " + s) # Global variables s = "I love Skopje!" def main(): # basics() # advanced() # global_local_variables() # non_local_variables() nested_global_variables() print("s in main: " + s) if __name__ == '__main__': main()
true
86f1796d0be666e3fd5a97530d548cd5bfd2c988
ashirbad1212/Python-Task-1-by-Ashirbad
/main.py
413
4.25
4
#Accept two integer numbers from a user and return their product and if the product is greater than 1000, then return their sum def product_sum(num1, num2): product = num1 *num2 if(product <= 1000): return product else: return num1 +num2 num1 = int(input("Please enter first number ")) num2 = int(input("Now enter second number ")) result = product_sum(num1, num2) print("The result is", result)
true
727d9728527d23e8a3dce0f49fadeef06c5a8b3e
AntonioCenteno/Miscelanea_002_Python
/Ejercicios progra.usm.cl/Parte 1/4- Patrones Comunes/productos-especiales_4.py
931
4.15625
4
from math import * #Productos especiales: Numero de Stirling del Segundo tipo #Pedimos los numeros n = int(raw_input("Ingrese n: ")) k = int(raw_input("Ingrese k: ")) #Iremos calculando el Numero de Stirling por partes. stirling = 0 #Primero, el factorial factorial_k = 1 for i in range(1,k+1): factorial_k *= i #Ahora, la sumatoria suma = 0 for i in range(k+1): #Calculamos los tres factoriales del coeficiente binomial fact_k = 1 for j in range(1,k+1): fact_k *= j fact_i = 1 for j in range(1,i+1): fact_i *= j fact_k_i = 1 for j in range(1, k-i+1): fact_k_i *= j #Ahora, calculamos el coeficiente binomial coef_binomial = fact_k / ( fact_k_i * fact_i ) #Y el elemento de la suma suma += (-1)**i * coef_binomial * (k - i)**n #Ahora nos queda dividir la suma por el factorial de k. stirling = suma / factorial_k print stirling
false
849fd5ed0c0a94f43c7b30a5bac23ee2105e5d73
raghukhanal/Python3
/Conditions.py
313
4.15625
4
age = 22 if age < 21: print("No beer for you") elif age == 21: print("Yes, right on!") else: print("You definetely can!") name = "Lucy" if name is "Raghu": print("Hey there Raghu") elif name is "Lucy": print("Hey hey, LUCEYYYYY") else: print("Hey there! please sign up for the site")
true
43e62b2fadbfe103f8bbc74c6084691e5a89b542
JennaDalgety/coding-dojo
/algorithms/chapter_0/birthday.py
691
4.15625
4
#If 2 given numbers represent your birth month and day in either order, log "How did you know?", else log "Just another day....", #Example: given yourBirthday(4,19) or yourBirthday(19,4) # def birthday(num1, num2): # full_birthday = [4, 19] # for i in full_birthday: # if (i[0], i[1]) == (num1, num2) or (i[1], i[0]) == (num2, num1): # print('How did you know?') # else: # print('Just another day....') # birthday(19, 4) def birthday(guess1, guess2): month = 'February' day = 1 if ((guess1, guess2) == (month, day)) or ((guess1, guess2) == (day, month)): print('How did you know?') else: print('Just another day...') birthday(1, 'February')
false
5b87abe1523ed4403a73e19aa65520ab731d6e4d
israeljgarcia/OOP-Data-Structures
/encapsulation/_gpa.py
2,445
4.375
4
class GPA: """ The GPA class stores a student's GPA within the range of 0.0 and 4.0. member variables: gpa methods: __init__(), get_gpa(), set_gpa(value(float)) """ def __init__(self): """ Initializes the gpa variable to 0. return: none """ self._gpa = 0.0 def _get_gpa(self): """ return: gpa """ return self._gpa def _set_gpa(self, value): """ Assigns the gpa member variable according to the input. return: none """ # The gpa can never be more than 4.0 or less than 0.0 if value > 4.0: self._gpa = 4.0 elif value < 0.0: self._gpa = 0.0 # Sets gpa to the passed in value self._gpa = value def _get_letter(self): """ Calculates the letter grade based on the gpa return: string """ if self._get_gpa() < 1: return 'F' elif self._get_gpa() < 2: return 'D' elif self._get_gpa() < 3: return 'C' elif self._get_gpa() < 4: return 'B' elif self._get_gpa() == 4: return 'A' def _set_letter(self, value): """ Returns a letter grade based on the passed in value. return: string """ if value == 'F': self._set_gpa(0.0) elif value == 'D': self._set_gpa(1.0) elif value == 'C': self._set_gpa(2.0) elif value == 'B': self._set_gpa(3.0) elif value == 'A': self._set_gpa(4.0) @property def letter(self): return self._get_letter() @letter.setter def letter(self, value): self._set_letter(value) gpa = property(_get_gpa, _set_gpa) def main(): student = GPA() print("Initial values:") print("GPA: {:.2f}".format(student.gpa)) print("Letter: {}".format(student.letter)) value = float(input("Enter a new GPA: ")) student.gpa = value print("After setting value:") print("GPA: {:.2f}".format(student.gpa)) print("Letter: {}".format(student.letter)) letter = input("Enter a new letter: ") student.letter = letter print("After setting letter:") print("GPA: {:.2f}".format(student.gpa)) print("Letter: {}".format(student.letter)) if __name__ == "__main__": main()
true
82a50c3979827e141f5f78904ca55cd355900534
parasjitaliya/DataStructurePrograms
/stack.py
1,672
4.125
4
class Node: # create a node def __init__(self, data = None): # initialize the first part of node is data self.data = data # initialize the second part of node is point address of next node self.next = None class Stack: # head is default Null def __init__(self): self.top = None # initialize the variable # count the element of stake self.count = 0 # Checks if stack is empty def is_empty(self): if self.top is None: return True else: return False # method to add data to the stack # adds to start of the stack def push(self, value): # stake head is none if self.top is None: self.top = Node(value) self.count += 1 else: #satke head is not none pusedNode = Node(value) pusedNode.next = self.top self.top = pusedNode self.count += 1 # method to remove head from the stack def pop(self): # check the stack is not empty if self.is_empty(): print("Stack is empty!!") else: if self.top.next is None: self.top = None self.count -= 1 else: self.top = self.top.next self.count -= 1 # return the head node data def peek(self): # check the stake is not empty if self.is_empty(): return "Stack is empty" else: return self.top.data #found the size of the stack def size(self): #return the count number return self.count
true
8de9a315962e4c95ff00a876073dc450e520b43f
parasjitaliya/DataStructurePrograms
/queue.py
1,571
4.15625
4
class Node: # create a node def __init__(self, data = None): # initialize the first part of node is data self.data = data # initialize the second part of node is point address of next node self.next = None class Queue: # declaring the front,rare,count variables and initialize def __init__(self): self.front = None self.rare = None self.count = 0 # Checks if stack is empty def is_empty(self): # check the first node is none if self.rare is None: return True else: return False # creating a function for enqueue def enqueue(self, data): # creating Node node = Node(data) node.data = data node.next = None # if the given element is 1st element, front element = rare element if self.rare == None: self.front = self.rare = node # else given data is assigned next to the rare element self.rare.next = node self.rare = node self.count += 1 # Creating a function for dqueue def dequeue(self): # check the queue is empty or not if Queue.is_empty(self): return "Queue is empty" else: #check for next of front if self.front.next == None: self.front == None else: self.front = self.front.next self.count -= 1 #found the size of the stack def size(self): #return the count number return self.count
true
1585c7c0468c3e8d710ebc3ec4c9e6b3ad9989bd
NSangita/Machine-Learning
/numpy-tutorial/ex01.py
381
4.1875
4
# Exercise 01: Extract elements from an array # Declare and initialize an array as done below # arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # Then, extract all odd numbers from arr to achieve the desired output. # Desired output: # #> [1 3 5 7 9] import numpy as np arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) arr = np.delete(arr, [0, 2, 4, 6, 8]) print(arr)
true
ac40c43ff5057cf0b8a8c4eb67d1e68ba4b4f9cf
Ncalo19/general_python_practice
/Python_tutorial/14_classes_slash_objects.py
1,418
4.34375
4
# class is an object blueprint # create an object blueprint class class1: name = 'Nick' # object: item inside a class age = 23 print(class1) # print an object print(class1.name) print(class1.age) # use a period when extracting info about a class or performing an action on a script or array # assign values to object properties class class1: def __init__(self, name, age): # self is a reference to the current instance of the class self.name = name # self is used to access variables that belong to the class self.age = age p1 = class1('Nicolas', 23) # p1 is the object p2 = class1('Jonathan', 21) print(p1.name) print(p2.age) # __init__ is a class method # method: similar to a function, but it is a member of an object or class # methods are always called with an object (ie. p1.) # functions are conversely called by their name # the first parameter of a method is always (self, # assign a function to an object (an object method) class class1: def __init__(self, name, age): self.name = name self.age = age def function1(self): print('my name is ' + self.name) # cannot use integers p1 = class1('Nicolas', 23) p2 = class1('Jonathan', 21) p1.function1() p2.function1() # change a number or string within an object p1.name = 'Nick' p1.age = 52 print(p1.name) print(p1.age) # delete a property from an object del p1.age # delete an object del p1
true
e689b9ebb684f88f2764418b6ea033216b88f2a4
jainsimran/python-exercises
/strings.py
802
4.28125
4
#Strings are Arrays str = "happy" #loop for x in str: print(x) # to check length print(len(str)) # to check if a certain phrase or character is present in a string, if "app" in str: print("app is present in " + str) if "tap" not in str: print("tap is not present in " + str) #Slicing Strings print(str[-4:-2]) # it will not include -2 postion. #replace string print(str.replace('h', 'D')) # combine string and number text = "I will become {} old on {} March 2021!" print(text.format(25, 13)) text2 = "I like to order {1} number of items, my budget is ${0} and I want to till {2}-{3}-{4}" # use index number to arrange it in order you wish print(text2.format(500, 10, 10, 10, 2021)) #using "" inside string print("I like to visit \"Mexico\", But love staying in \"Canada\". ")
true
30b54f8a93a3ccf721d40444cca9a1e1f6bae9e5
aync19/InteractivePythonCoursera
/circle.py
1,013
4.1875
4
#Use buttons to increase and decrease the size of the circle #Change color with input field import simplegui # Define globals - Constants are capitalized in Python HEIGHT = 400 WIDTH = 400 RADIUS_INCREMENT = 5 ball_radius = 20 color = "Orange" # Draw handler def draw(canvas): global ball_radius canvas.draw_circle([200,200],ball_radius, 2, color) # Event handlers for buttons def increase_radius(): global ball_radius ball_radius+=RADIUS_INCREMENT def decrease_radius(): global ball_radius if(ball_radius>RADIUS_INCREMENT): ball_radius-=RADIUS_INCREMENT def circ_color(col): global color color = col # Create frame and assign callbacks to event handlers frame = simplegui.create_frame("Ball control", WIDTH, HEIGHT) frame.set_draw_handler(draw) frame.add_button("Increase radius", increase_radius, 100) frame.add_button("Decrease radius", decrease_radius, 100) frame.add_input("Circle color", circ_color, 100) # Start the frame animation frame.start()
true
5e986e6230bae6882a92744b52f6b8102a3e9cde
deepali1232/divya-coding-classes
/basic_programs/program11.py
573
4.28125
4
#dictionary(key-value-pair) d1={'apple':50,'mango':100,'guava':200,'banana':300} print(d1) print(type(d1)) #extracting keys print(d1.keys()) #extracting values print(d1.values()) #add new element in dict d1['bag']=400 print(d1) #change existing element or modify d1['mango']=30 print(d1) #update one dict value with another or append stationary={'pen': 2,'rubber': 4,"bottle": 8} books={'math':100,'english':400} stationary.update(books) print(stationary) #pop an element stationary.pop('rubber') print(stationary)
true
b5d5ad2fd8f2eb6425d2684eb49b47ca4ed02d66
deepali1232/divya-coding-classes
/basic_programs/basic32.py
815
4.125
4
#Python program to check if the given number is Happy Number #Number = 32 #3^2+ 2^2 = 13 #1^2 + 3^2 = 10 #1^2 + 0^2 = 1 #isHappyNumber() will determine whether a number is happy or not def isHappyNumber(num): rem = sum = 0; #Calculates the sum of squares of digits while(num > 0): rem = num%10; sum = sum + (rem*rem); num = num//10; return sum; num = 82; result = num; while(result != 1 and result != 4): result = isHappyNumber(result); #Happy number always ends with 1 if(result == 1): print(str(num) + " is a happy number"); #Unhappy number ends in a cycle of repeating numbers which contain 4 elif(result == 4): print(str(num) + " is not a happy number");
true
f969ad05d1ea8646a031ef1788c2d75075e1f627
J-asy/Algorithms-and-Data-Structures
/boyer_moore/z_algo.py
2,197
4.15625
4
def z_algorithm(string): """ Returns a z_array, such that for all i, z_array[i] contains the length of the longest substring starting at position i of the string that matches its prefix :time complexity: O(n) :space complexity: O(n), where n is the length of the string """ z_array = [0] * len(string) z_array[0] = len(string) left = right = -1 index = 1 while index < len(string): # when index is outside the current Z-box # explicit comparisons starting from first character if index > right: left, right, counter = character_comparison(string, index, left, right, 0) z_array[index] = counter # when index is in the current Z-box else: remaining = right - index + 1 reference_index = index - left if z_array[reference_index] < remaining: z_array[index] = z_array[reference_index] elif z_array[reference_index] > remaining: z_array[index] = remaining else: # explicit comparisons starting from the right + 1 number_known_same_char = right - index + 1 left, right, counter = character_comparison(string, right + 1, left, right, number_known_same_char) z_array[index] = counter index += 1 return z_array def character_comparison(string, pointer, left, right, number_known_same_char): """ Does explicit character comparison starting from the first character of the string and pointer, and redraws the Z-box (indicated by left & right) if necessary :time complexity: O(n); :space complexity: O(n), where n is the length of the string """ counter = number_known_same_char start = pointer while pointer < len(string) and string[counter] == string[pointer]: counter += 1 pointer += 1 # redraws the Z-box if its length is greater than 0 if counter > 0: left = start - number_known_same_char if pointer - 1 > right: right = pointer - 1 return left, right, counter
true
4559c4687e3ac3c5ec8ad6c257a5fbbbb21a257d
GitBulk/datacamp
/marketing analytics with python/01 analyzing marketing campaigns with pandas/11_grouping_and_counting_by_multiple_columns.py
1,189
4.1875
4
''' INTRODUCTION: Grouping and counting by multiple columns Stakeholders have begun competing to see whose channel had the best retention rate from the campaign. You must first determine how many subscribers came from the campaign and how many of those subscribers have stayed on the service. It's important to identify how each marketing channel is performing because this will affect company strategy going forward. If one channel is outperforming others, it might signal the channel merits further investment. You will build on what we have learned about .groupby() in previous exercises, this time grouping by multiple columns. INTRUCTION: Use .groupby() to calculate subscribers by subscribing_channel and date_subscribed ''' channel_age = marketing.groupby(['marketing_channel', 'age_group'])['user_id'].count() # Unstack channel_age and transform it into a DataFrame channel_age_df = pd.DataFrame(channel_age.unstack(level=1)) # Plot channel_age channel_age_df.plot(kind='bar') plt.title('Marketing channels by age group') plt.xlabel('Age Group') plt.ylabel('Users') # Add a legend to the plot plt.legend(loc='upper right', labels=channel_age_df.columns.values) plt.show()
true
08e5788255b2234ea69ddcc5b38aec34e27706ef
exfrioss/python_projects_for_beginners
/0_beginners_path/03_email_slicer.py
1,002
4.40625
4
""" Email slicer: An email slicer is a very useful program for separating the username and domain name of an email address. To create an email slicer with Python, our task is to write a program that can retrive the username and the domain name of the email. For example: 'frioss@domain.com'. So we need to divide the email into two strings using '@' as the seperator. Let's see how to separate the email and domain name with Pyhton. """ def email_slicer_slicing(email): username = email[:email.index('@')] domain_name = email[email.index('@')+1:] format_message = (f"Your user name is: '{username}' and your domain is '{domain_name}'") print(format_message) def email_slicer_split(email): data = email.split('@') username = data[0] domain_name = data[1] format_message = (f"Your user name is: '{username}' and your domain is '{domain_name}'") print(format_message) email = input("Enter your Email: ").strip() email_slicer_slicing(email) email_slicer_split(email)
true
a9f563b4837e8cc91791bc8bc0b03a3cbea4d5c0
johnwatterlond/playground
/matrix_printer.py
2,290
4.6875
5
""" Module for printing a matrix. Matrix can be of any size and can contain numbers or words of any length. Matrix should be a list of rows where each row is a list. Examples: --------- Example 1: In : matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]] print_matrix(matrix) Out : 2 4 6 8 10 12 14 16 18 Example 2: In : matrix = list(zip(*[iter(range(21))]*7)) print_matrix(matrix) Out : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Example 3: In : matrix = [ ['cat', 'meow'], ['dog', 'bark'], ['airplane', 'vroom'] ] print_matrix(matrix) Out : cat meow dog bark airplane vroom """ def get_row_format(num_cols, padding): """ Return a string row_format for use in row_format.format(*row), where row is a row in a matrix. num_cols: number of columns in the matrix. padding: how many characters each element in the row should take up. """ spacer = '<{}'.format(padding) form = '{}{}{}{}'.format('{', ':', spacer, '}') return ' '.join(form for x in range(num_cols)) def get_formatted_rows(matrix, num_cols, padding): """ Return the rows of matrix as a list of formatted rows as strings. num_cols: number of columns in the matrix. padding: how many characters each element in the row should take up. """ row_format = get_row_format(num_cols, padding) return [row_format.format(*row) for row in matrix] def get_matrix_string(matrix, num_cols, padding): """ Return matrix as a string ready to be printed. num_cols: number of columns in the matrix. padding: how many characters each element in the row should take up. """ rows = get_formatted_rows(matrix, num_cols, padding) return '\n'.join(list(rows)) def len_longest_in_row(row): """ Return the length of the longest element in row. """ return max([len('{}'.format(x)) for x in row]) def get_len_longest(matrix): """ Return length of the longest element in matrix. """ return max([len_longest_in_row(row) for row in matrix]) def print_matrix(matrix): """ Print matrix. """ num_cols = len(matrix[0]) padding = get_len_longest(matrix) print(get_matrix_string(matrix, num_cols, padding))
true