blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d9a33659707e519046e7a2de0db3990974a022d6
moyales/Python-Crash-Course
/3_lists/3-1_names.py
227
4.15625
4
#A list of names of friends names = ["Lucas", "Raquel", "Richie", "Il Duce", "Matt"] #Print each name individually. All list elements start at "0". print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4])
true
c7341c1597bc4bfc0113c9775eb5c6723eed62af
moyales/Python-Crash-Course
/3_lists/3-8_seeing_the_world.py
978
4.46875
4
#Exercise 3.8: Seeing the World locations = ['New York' , 'London', 'Vancouver', 'Amsterdam', 'Tokyo'] print("Here is the original list:") print(locations) print("\nHere is the list sorted by alphabetical order:") print(sorted(locations)) print("\nThe original list is still in the same order:") print(locations) print("\nHere is the list in reverse alphabetical order:") print(sorted(locations, reverse=True)) print("\nAgain, the list is still in the same order as it was before:") print(locations) print("\nNow, we are going to reverse the order of the list using the reverse method:") locations.reverse() print(locations) print("\nUsing the reverse method again will restore the list back to its original form:") locations.reverse() print(locations) print("\nThe sort method will permanently sort this list in alphabetical order:") locations.sort() print(locations) print("\nPut the list in reverse alphabetical order:") locations.sort(reverse=True) print(locations)
true
401e56f804af670e46bb2fa62941a876f031d184
edwwumpus241/python_all_collections_
/19Tugas19.py
2,081
4.1875
4
print("Hello welcome to this money changer program") print("The list below are the banknotes we have currently") print("Note: enter the ID to convert the banknote") print("ID : 1 .Dollar to Rupiah") print("ID : 2 .Euro to Rupiah") print("ID : 3 .Ringgit to Rupiah") print("ID : 4 .Yen to Rupiah") print("ID : 5 .Won to Rupiah") print("ID : 6 .Poundsterling to Rupiah") print("ID : 7 .Rupee to Rupiah") print("ID : 8 .Ruble to Rupiah") print("Credit to Google(helps me to find the currency rate") id_detecting = int(input("Enter one ID that has been shown in your screen : ")) amount_detecting = int(input("Enter the amount of the money to convert : ")) id_1 = 14000; id_2 = 17000; id_3 = 3000; id_4 = 132.23; id_5 = 1267; id_6 = 20000; id_7 = 194.21; id_8 = 195.70; if id_detecting == 1: converting = id_1 * amount_detecting; print(amount_detecting ,"Dollar in Rupiah are ",converting ," Rupiah") if id_detecting == 2: converting_1 = id_2 * amount_detecting; print(amount_detecting ,"Euro in Rupiah are ",converting_1 ," Rupiah") if id_detecting == 3: converting_2 = id_3 * amount_detecting; print(amount_detecting ,"Ringgit in Rupiah are ",converting_2 ," Rupiah") if id_detecting == 4: converting_3 = id_4 * amount_detecting; print(amount_detecting ,"Yen in RUpiah are ",converting_3 ," Rupiah") if id_detecting == 5: converting_4 = id_5 * amount_detecting; print(amount_detecting ,"Won in Rupiah are ",converting_4 ,"Rupiah") if id_detecting == 6: converting_5 = id_6 * amount_detecting; print(amount_detecting ,"Poundsterling in Rupiah are ",converting_5 ," Rupiah") if id_detecting == 7: converting_6 = id_7 * amount_detecting; print(amount_detecting ,"Rupee in Rupiah are ",converting_6 ," Rupiah") if id_detecting == 8: converting_7 = id_8 * amount_detecting; print(amount_detecting ,"Ruble in Rupiah are ",converting_7 ," Rupiah") if id_detecting <1: print("Chap, read the list again") if id_detecting >8: print("Buckaroo, read the list again")
false
9be09e1799866e98e7c2c8c88518e2df0cce260e
leonjaime1983/PYTHON_GUI
/TKINTER/2. TKINTER BASICS/02_botones_entry.py
2,431
4.125
4
#Santiago Garcia Arango, 16 Enero 2020 #MANEJO SENCILLO DE BOTONES Y "ENTRY" EN TKINTER #------------------------------------------------------------------------ #Es fundamental tener widgets interactivos para el programa, como los botoes y entry fields. #Ambos se deben crear primero y luego posicionar por alguno de los dos sistemas (grid/pack) #------------------------------------------------------------------------ #EJEMPLO: #Se crea aplicacion sencilla con dos botones, que ambos hacen algo #Se importan librerias de trabajo import tkinter as tk from tkinter import ttk #Se crea ventana principal, nombrada por nosotros "root" root = tk.Tk() #Se crea label encargada de indicar que el usuario ingrese el nombre texto_1 = ttk.Label( root, text = "Ingrese su nombre: " ) texto_1.grid(row =0, column =0 ) #Se crea label para luego interactuar con ella al tocar boton texto_2 = ttk.Label( root, text = " " ) #Nota: columnspan o rowspan permiten hacer widgets de "grosor" de N columas o filas texto_2.grid(row =1, column =0,columnspan = 3 ) #Se crea Entry Field (para ingresar info por el usuario) #FUNDAMENTAL: crear "tk.StringVar()" para manejo de Entry fields nombre_usuario = tk.StringVar() entrada = ttk.Entry( root,width = 20, textvariable = nombre_usuario ) entrada.grid( row = 0, column =1 ) #OJO: truco interesante: hacer que el usuario ya tenga el "mouse" listo para escribir: entrada.focus() #Se crean dos botones, uno para imprimir algo en terminal y otro para salirse #WARNING: "command" permite hacer funcion al tocar boton, pero NO se pone entre parentesis... #... de lo contrario NO funcionaria al tocarla, sino al inicializar... #NOTA: Se debe crear funcion del boton, antes de crearlo def funcion_tocame(): #Se cambia texto de label, con ayuda de "condigure()" #Ver forma de obtener info de Entry asociado al nombre... #...es a traves de la variable "nombre_usuario", llamando a "get()" texto_2.configure( text = "Gracias por tocarme {}".format(nombre_usuario.get()) ) b_1 = ttk.Button( root, text = "TOCAME" , command = funcion_tocame) b_1.grid(row =0, column = 2, padx = (10,50)) #Mirar padx como "padding en x externo" #Tambien existe ipadx comom "internal padding en x" b_2 = ttk.Button(root, text = "SALIR", command = quit) b_2.grid(row = 0, column = 3) #Se ejecuta finalmente toda la ventana de tkinter con el mainloop() root.mainloop()
false
f7a1cf9dd1c14e7e43271738204743388f2f6ef8
Simratt/N-Body_Simulation
/particle.py
1,116
4.15625
4
import pygame class Particle: ''' This is a representation of a particle in space === Attributes === - _x: the x position of the particle - _y: the y position of the particle - coords: the coordinates of the particle on the screen - size: the radius of the particle - color: the color of the particle - thickness: the thickness of the particle, this is for the pygame window === Representaion Invariants === #TODO _x: int _y: int coords: tuple(int, int) size: [int, float] color: tuple(int,int,int) thickness: int ''' def __init__(self, x: int ,y: int, size: int) -> None: ''' the constructor for the particle class''' self._x = x self._y = y self.coords = (self._x, self._y) self.size = size self.color = (255,255,255) self.thickness = 1 def display(self, screen: pygame.display) -> None: ''' this function draws the particle onto a paygame window''' pygame.draw.circle(screen, self.color, self.coords, self.size, self.thickness)
true
5d3f3163698f004ccbc41c1c0371b6386d941ff7
gunal89/python-Interview_workout
/logic1-workout-1.py
2,407
4.15625
4
from __future__ import print_function #Largest Number: numlist = [10,20,1,900,-20,2,1058,300,1000,901] largest1=largest2=largest3 = int() for lnum in numlist: if lnum > largest3: if lnum > largest1: largest1,largest2= lnum,largest1 elif lnum > largest2: largest2, largest3 = lnum, largest2 else: largest3 = lnum print ("1st largest num",largest1) print ("2nd largest num",largest2) print ("3rd largest num",largest3) #Smallest Number: smallest1 = numlist[0] smallest2 = int() for snum in numlist: if snum < smallest2: if snum < smallest1: smallest1,smallest2 = snum,smallest1 else: smallest2 = snum print ("1st Smallest num",smallest1) print ("2nd Smallest num",smallest2) #Fibonnaci Number: count =0 n1 = 0 n2 =1 while (count < 10 ): print(n1,end=',') nr = n1 + n2 n1=n2 n2=nr count +=1 #Sorting without default fun() sortlist =list() while numlist: first_val = numlist[0] for item in numlist: if item < first_val: first_val = item sortlist.append(first_val) numlist.remove(first_val) print ('\n',sortlist) print("--Sorting----") #sort --> Sort is doing sorting with same List or Dict itself. It modifies original Data. #sorted - Sorted is doing sorting the list and dict.It return another list.Not modify the original object sortlist1 = [2,9,45,3,1] print ("--",(sortlist1.sort())) #returns NONE print (sortlist1) #sorted s1=[5,7,9,1,2,3] s2 = sorted(s1) print (s2) print (s1) #switch case in python def switch(choice): switcher={ 'Ayushi':'Monday', 'Megha':'Tuesday' } print(switcher.get(choice)) switch('Megha') #Count the Number of Each Vowels: vowels = 'aeiou' # change this value for a different result ip_str = 'Hello, have you tried our turorial section yet?' ip_str = ip_str.lower() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0) # count the vowels for char in ip_str: if char in count: #counts have vowels letters count[char] += 1 print(count) keys = {'a', 'e', 'i', 'o', 'u' } v = 'aeio,' vowel = dict.fromkeys(['gunal','sures'],1) print(vowel) #Change uppecase using ORD(): s='mari' for char in s: s_val = (ord(char)-32) print (chr(s_val),end="")
false
aa72938796a2257ce6f931fefcec5c166b58d6bb
refanr/2020
/11/3.py
535
4.1875
4
def get_emails(): email = '' email_list = [] while email != 'q': email = input('Email address: ') if email != 'q': email_list.append(email) return email_list def get_names_and_domains(listi): tuple_list = [] for i in listi: tup = tuple(i.split('@')) tuple_list.append(tup) return tuple_list # Main program starts here - DO NOT change it email_list = get_emails() print(email_list) names_and_domains = get_names_and_domains(email_list) print(names_and_domains)
false
3bc9857d792c155ccee7739a7563e33c23882e81
GerganaTancheva123/ML_Python
/labs/python_basics/tuples_my_data.py
328
4.4375
4
### create tuple with 3 elements: my_data = (7, "August", 1993,"Bulgaria", "Gergana") # retrieve tuple elements: birth_day = my_data[0] birth_month = my_data[1] birth_year = my_data[2] contry = my_data[3] name = my_data[4] print("{} is born on {} {} in {}, and is from {}".format(name,birth_day,birth_month,birth_year,contry))
false
55fe4a7e33269193a7eee2d7f0c3906f4da2d02c
GerganaTancheva123/ML_Python
/labs/python_basics/guess_the_number.py
745
4.15625
4
import random number = random.randrange(1,20) print(number) # def generateMachineNumber(): # """generate number between 1 to 200 and ask the user's name""" # user_name = input('Hello! What is your name? ') # # number = random.randrange(200) # print('Well {}, I am thinking of a number between 1 and 200.'.format (user_name)) # # print(number) # generateMachineNumber() # def userInput(): # """ ask the user to enter a number """ # num = int( input('Please, enter a number: ') ) # # while user enters a number out of interval [1,10]: # # input('Please, enter number in [1,2]') # while num<1 or num>200: # num = int( input('Please, enter a number in [1,10]: ') ) # print(num) # def compareNumbers(): # pass # userInput();
true
7af895097e5a072438c012c70b151152f927a277
jenniquan/Python-Homework
/Accelerometer.py
363
4.28125
4
# The accelerometer monitors acceleration in the x, y and z axes # by reporting each value in m/s/s. # Write a function that, given the accleration of each axes, # returns the resultant (square root of the sum of squares ) of all 3 values. import math def resultant (x, y, z): return math.sqrt ((math.pow (x, 2)) + (math.pow (y, 2)) + (math.pow (z, 2)))
true
a0804901d29f45c662e2dfd08db3fe2c3d2e952f
deepshig/leetcode-solutions
/easy/queue_using_stack/queue_using_stack.py
1,653
4.34375
4
class Stack(object): def __init__(self): self.elements = [] return def push(self, x): self.elements.append(x) return def pop(self): if self.empty(): return 0 return self.elements.pop() def peek(self): if self.empty(): return 0 return self.elements[len(self.elements)-1] def empty(self): return len(self.elements) == 0 class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.stack = Stack() return def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ temp = Stack() while not self.stack.empty(): element = self.stack.pop() temp.push(element) self.stack.push(x) while not temp.empty(): element = temp.pop() self.stack.push(element) return def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ return self.stack.pop() def peek(self): """ Get the front element. :rtype: int """ return self.stack.peek() def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return self.stack.empty() # Your MyQueue object will be instantiated and called as such: obj = MyQueue() obj.push(1) obj.push(2) a = obj.pop() b = obj.peek() c = obj.empty() print("a = ", a, ", b = ", b, ", c = ", c)
false
f79792a887f6275f1ab45bc2c17947e2de961653
Andy1998/coingame
/library.py
603
4.15625
4
#! /usr/bin/env python def side_input(sentence): a = raw_input(sentence) if a != "head" and a != "tail": print "I cannot understand because the program is stupid. Please just enter 'head' or 'tail'" a = side_input(sentence) else: return a def int_input(sentence): number = raw_input(sentence) try: number = int(number) return number except: print "Not an int, try again." number = int_input(sentence) def float_input(sentence): number = raw_input(sentence) try: number = float(number) return number except: print "Not a float, try again." number = float_input(sentence)
true
1fca320ec161ac227e28939f580f6fb72f258c97
shashank451180/Python
/calculator_marksheet_while.py
2,586
4.53125
5
#user input for option option=int(input('choose your option \npress 1 for calculator \npress 2 for student marksheet\npress 3 to quit\n')) #this loop will execute if user want to continue with calculator while option==1: print("calculator\n") d="yes" while d=="yes" or d=="Yes": a=float(input("enter 1st number = ")) b=float(input("enter 2nd number = ")) print("\nselect operation you want to perform \n\nfor addition press + \nfor subtraction press -\nfor multiplication press *\nfor division press /\n") choice=input("Enter Choice ") if choice=="+": print("Addition : ", a, "+", b, "=", a+b) elif choice=="-" : print("Subtraction : ", a, "-", b, "=", a-b) elif choice=="*" : print("Multiplication is : ", a, "*", b, "=", a*b) elif choice=="/" : print("Division is : ", a, "/", b, "=", a/b) else: print("wrong Choice") d=input("\ndo you want to continue??\ntype Yes if you want to continue\ntype No to exit\n") if d=="no" or d=="No": print("Thank you") option=int(input('choose your option \npress 1 for calculator \npress 2 for student marksheet\n')) else: print("wrong input") #this loop will execute if user want to continue with student marksheet while option==2: print("Student marksheet") choice="Yes" while choice=="yes" or choice=="Yes": marks=float(input("enter your marks =")) if marks>=80 and marks<=100: print("Your Grade Is O") elif marks>=65 and marks<=79: print("Your Grade Is A") elif marks>=50 and marks<=64: print("Your Grade Is B") elif marks>=40 and marks<=49: print("Your Grade Is C") elif marks>=30 and marks<=39: print("Your Grade Is D") elif marks>=0 and marks<=29: print("You are FAIL") else: print("Wrong input") choice=input("\ndo you want to continue??\ntype Yes if you want to continue\ntype No to exit\n") if choice=="no" or choice=="No": print("Thank you") option=int(input('choose your option \npress 1 for calculator \npress 2 for student marksheet\n')) else: print("wrong input") #this loop will execute if user want to quit if option==3: print("thank you") #if by mistaken user gave wrong input else: print("wrong input")
false
3e240cbed48fbf7d6aee42d0992aa12b4213d49b
ryan-31/Login-System
/loginSys.py
1,937
4.15625
4
choice = input("Welcome! Enter 1 to login or 2 to make a new account.") choice = int(choice) while choice != 1 and choice != 2: choice = input("Enter 1 to login or 2 to make a new account.") choice = int(choice) def login(): userAttempt = input("Enter your username:") passAttempt = input("Enter your password:") with open('usernamefile.txt') as f: if userAttempt in f.read(): unameEntry = 1 else: unameEntry = 0 with open('passfile.txt') as f: if passAttempt in f.read(): pEntry = 1 else: pEntry = 0 if unameEntry == 1 and pEntry == 1: print("Successful Login") elif unameEntry == 1 and pEntry == 0: print("Username Corect, Incorrect Password") elif unameEntry == 0 and pEntry == 1: print("Incorrect Username") else: print("Unsuccessful Login") suggPass = " " import string import random def suggestPass(): specialChar = ['!', '@', '#', '$', '%','^','&','*', '(', ')','-','_', '+','=','|','|','?','>','<','/','.',','] suggPass = random.choice(specialChar) for i in range(0, 5): suggPass = suggPass + str(random.randint(0,9)) suggPass = suggPass + random.choice(string.ascii_letters) suggPass = suggPass + random.choice(specialChar) print("Suggested Password: "+ suggPass) def createNew(): newUser = input("Enter a username:") newUser = str(newUser) suggestPass() newPass = input("Enter a secure password that is up to 16 characters long: ") newPass = str(newPass) while len(newPass) > 16: newPass = input("Enter a secure password that is UP TO 16 CHARACTERS LONG:") with open('usernamefile.txt', mode = 'w') as f: f.write(newUser+"\n") with open('passfile.txt', mode = 'w') as f: f.write(newPass+"\n") print("You have successfully created a new account with the username: "+newUser) if (choice == 1): print("Login:") login() elif (choice == 2): print("Create a New Account:") createNew()
true
0c1c032356cd3988e810a3741a1dc7c276fffa34
aldotele/lotto_lottery
/lotto/lotto_bet.py
1,548
4.25
4
class Bet: """ represents the type of bet @attr name is the name of the bet as a lowercase string @attr min_numbers is the minimum amount of numbers needed for that bet, and is equal to the bet code """ bet_strings = {1: 'ambata', 2: 'ambo', 3: 'terno', 4: 'quaterna', 5: 'cinquina'} bet_codes = {'ambata': 1, 'ambo': 2, 'terno': 3, 'quaterna': 4, 'cinquina': 5} def __init__(self, bet_code): if Bet.is_bet_valid(bet_code): bet_code = int(bet_code) self.name = Bet.bet_strings[bet_code] self.min_numbers = bet_code else: raise ValueError('bet code must be an integer between 1 and 5') @staticmethod def is_bet_valid(bet_code): """ validates the bet code which has to be between 1 and 5 :param bet_code: integer :return: boolean """ try: bet_code = int(bet_code) if bet_code in Bet.bet_strings: return True else: return False except: return False @staticmethod def show_allowed_bets(amount=5): """ it shows the allowed bets based on the placed amount of numbers @param amount is by default 5, which means the method will show all existing bets """ for key in Bet.bet_strings: if amount >= key: print('{} : {}'.format(key, Bet.bet_strings[key])) @staticmethod def get_bets(): return list(Bet.bet_strings.values())
true
8e9abbcc21d8ab9da21389c79cb54fe3d75985e0
Sahu-Ayush/Python-Programs
/Conditionals and Loops/Sum of even & odd.py
1,090
4.21875
4
# Sum of even & odd ''' Write a program to input an integer N and print the sum of all its even digits and sum of all its odd digits separately. Digits mean numbers, not the places! That is, if the given integer is "13245", even digits are 2 & 4 and odd digits are 1, 3 & 5. Input format : Integer N Output format : Sum_of_Even_Digits Sum_of_Odd_Digits (Print first even sum and then odd sum separated by space) Constraints 0 <= N <= 10^8 Sample Input 1: 1234 Sample Output 1: 6 4 Sample Input 2: 552245 Sample Output 2: 8 15 Explanation for Input 2: For the given input, the even digits are 2, 2 and 4 and if we take the sum of these digits it will come out to be 8(2 + 2 + 4) and similarly, if we look at the odd digits, they are, 5, 5 and 5 which makes a sum of 15(5 + 5 + 5). Hence the answer would be, 8(evenSum) <single space> 15(oddSum) ''' # Code n = int(input()) sum_of_even = 0 sum_of_odd = 0 while n > 0: rem = n % 10 if rem % 2 == 0: sum_of_even += rem else: sum_of_odd += rem n //= 10 print(sum_of_even, "\t", sum_of_odd)
true
c70838068a4326ef20677d178830e250365e5087
Sahu-Ayush/Python-Programs
/Patterns/Number Pattern Opposite Direction.py
693
4.125
4
# Number Pattern ''' Print the following pattern for n number of rows. For eg. N = 5 1 1 12 21 123 321 1234 4321 1234554321 Sample Input 1 : 4 Sample Output 1 : 1 1 12 21 123 321 12344321 ''' # Code n = int(input()) d = n - 1 i = 1 while i <= n: # Increasing number (right triangle) j = 1 while j <= i: print(j, end='') j += 1 # Space (in Inverted triangle order) space = 1 while space <= n - i + d: # print("@", end='') print(" ", end='') space += 1 # Increasing number (Mirror Image) p = i while p >= 1: print(p, end='') p -= 1 # print() i += 1 d -= 1
true
898dfeefb8ffbfbe7b24631a14b718dced459648
kpowers/GIS501_lab3_good
/GIS_501_lab_3_turtles.py
1,277
4.8125
5
##GIS 501 - Lab 3 problem 4 Create a turtle ##You are going to write a script that asks the user to input a number and then draws a shape with that number of sides! import turtle #allows us to use the turtles library wn = turtle.Screen() #creates a graphics window turtle.speed #gives turtle max speed wn.bgcolor('lightblue') #background color to light blue alex = turtle.Turtle() #create a turtle named alex alex.color('darkgreen') # alex.forward(150) #tell alex to move forward by 150 units # alex.left(90) #turn by 90 degrees # alex.forward(75) #complete the second side of a rectangle print ("This program draws shapes based on the number you enter in a uniform pattern.") num_sides = int(input("Enter the number of sides for an equilateral polygon the turtle will draw: ")) angle = int(360/num_sides) #divide the inside angle by number of sides input by user to determine angle that the turtle turns. for num_sides in range (num_sides): alex.forward(50) #length of each line segment alex.left(angle) turtle.mainloop() #keeps turtle draw window from freezing
true
2cb3a118536b9d86416f2ba05358e28d129632a7
ricardo-tapia/CYPJoseMT
/libro/problemas_resueltos/capitulo3/problema3_8.py
252
4.125
4
num = int(input("Dame un número: ")) if num > 0: while num != 1: if num % 2 == 0: num = num / 2 else: num = (num * 3) + 1 print (num) else: print ("El número tiene que ser un entero positivo")
false
7391a5b3dae2a45d3f9d45c0bb3839d8483fda0c
MarkC077/learning-python
/smallpro.py
770
4.1875
4
print("Whats your couples name?") name1 = input("What is your name? ") name2 = input("What your partner name? ") def couplesname(str1, str2): return name1[ : : 2] + name2[ : : 2] result = couplesname(name1, name2) print(f"Your couples names is {result}") # we dont know why this code is here, but if you remove it, everything breaks, so here it will stay reverse = input("Do you want to reverse the outcome? [y / n] ") def reversename(str2, str1): if reverse == "Y" or reverse == "y": return name2[ : : 2] + name1[ : : 2] elif reverse == "N" or reverse =="n": print("Thank you for playing") else: print("Sorry that is the wrong input!") result2 = reversename(name2, name1) print(f"Your reverse name is {result2}")
true
af44ad8fef0d57ad4a833b0faa7d412c60a62f50
shane-vdl/CS50x2020
/pset6/mario/less/mario.py
647
4.28125
4
# Program that prints half of Mario's pyramid # Author: Gloria Videloup # CS50x2020 from cs50 import get_int while True: # Prompt the user for the pyramid's height height = get_int("height:") width = height # Needs to be a positive integer between 1 and 8 # If it's smaller or equal to 0, reprompt. if height <= 0: height = get_int("height:") # If it's true, generate the pyramid elif height < 9: for i in range(height): num_hashes = i + 1 num_spaces = width - num_hashes print(" " * num_spaces, end="") print("#" * num_hashes) break
true
ffb71598572818dac82b5bed92d9db50d626ad14
tanushsavadi/Code-in-Place-Stanford-2021
/Lectures/Lecture 10: Lists/listparameter.py
1,642
4.71875
5
""" File: listparameter.py --------------------- This program contains examples of using lists as parameters, especially in different type of for loops. """ def add_five_buggy(alist): """ Attempts to add 5 to all the elements in the list. BUGGY CODE! Does not actually add 5 to the list elements if values are primitive type (like int or float), since value would just be a local copy of such variables. """ for value in alist: value += 5 def add_five_working(alist): """ Successfully adds 5 to all the elements in the list. Changes made to the list persist after this function ends since we are changing actual values in the list. """ for i in range(len(alist)): alist[i] += 5 def create_new_list(alist): """ Shows an example of what happens when you create a new list that has the same name as a parameter in a function. After you create the new list, you are no longer referring to the parameter "alist" that was passed in """ # This "alist" is referring to the parameter "alist" alist.append(9) # Creating a new "alist". This is not the same as the parameter # passed in. After this line references to "alist" are no longer # referring to the parameter "alist" that was passed in. alist = [1, 2, 3] def main(): values = [5, 6, 7, 8] print('values =', values) add_five_buggy(values) print('values =', values) add_five_working(values) print('values =', values) values = [5, 6, 7, 8] create_new_list(values) print('values =', values) if __name__ == '__main__': main()
true
5d6e7654c703f92699b58e600b8cdd9996448939
ianujvarshney/Python-Programs
/Intermediate Level Programs/Factorial_No_of_Zeroes.py
407
4.125
4
def fac(num): if num==0 or num==1: return 1 else: return num*fac(num-1) def fact(num): i=5 count=0 if num//i!=0: count+=int(num//i) # count += int(num / i) i=i*5 return count if __name__ == '__main__': a=int(input(" Please Enter a no. : ")) print(f" Factorial is : {fac(a)}") print(f" No. of Zeroes in the factorial : {fact(a)}")
true
10027c0e80fc1732cc8f8fa3d8259497c2112e64
ianujvarshney/Python-Programs
/Basic Level Programs/Clear_a_list.py
551
4.21875
4
########################################## Ways to Clear a list ##################################### ################### 1st Way: a=[4,5,1,2,6,8,9,6] print(f"Before Clear: {a}") a.clear() print(f"After Clear: {a}") ################# 2nd Way: a=[4,5,1,2,6,8,9,6] print(f"Before Clear: {a}") a=[] print(f"After Clear: {a}") ################ 3rd Way: a=[4,5,1,2,6,8,9,6] print(f"Before Clear: {a}") a*=0 print(f"After Clear: {a}") ################# 4th Way: a=[4,5,1,2,6,8,9,6] print(f"Before Clear: {a}") del a[:] print(f"After Clear: {a}")
false
515282c3bac0d93fd9e15c56b625bad958d9197f
ianujvarshney/Python-Programs
/Intermediate Level Programs/Jumbling_the_names.py
851
4.125
4
import random import time def jumble_word(first_name, last_name, num): print("\n\nNames after Jumbling : ") for i in range(0, num): jumbled_name= first_name[i].capitalize() +" " +last_name[random.randint(0, num - 1)].capitalize() time.sleep(0.5) print(jumbled_name) if __name__ == '__main__': num = int(input("How many names you want to input : ")) nameList = [] first_name = [] last_name = [] for i in range(1, num + 1): name = input(f"Enter {i} name:") # name=name.upper() if name.isnumeric(): raise Exception("Here Numbers are not Allowed !!") nameList.append(name) for i in nameList: split_name = i.split(" ") first_name.append(split_name[0]) last_name.append(split_name[1]) jumble_word(first_name, last_name, num)
true
099e33cd6b47d06c02f63d1b0e7347a95f276556
sleamyz/Python-2020-2022-
/Other Problems/Greater values in array.py
1,566
4.15625
4
#Date: March 14, 2021 #Purpose: quick question I heard about #Given a single array, determine the distance (in indices) #between the value at each index and the closest greater value AHEAD. #Note: return output for each index of the input array in the format of another array #Note: if there is greater no value ahead of the current, then the output for that index is 'impossible'. def GreaterValues(arr): #use stack, always keep smallest value in front (will be automatically done) #if a value is larger than smallest value, compare then repeat if necesarry ans = arr stack = [] for index, value in enumerate(arr): #initialize the stack when its first index if index == 0: stack.append((value,index)) #if less or equal to most recent if value <= stack[-1][0] and index != 0 : stack.append((value,index)) #if bigger than most recent/smallest elif value > stack[-1][0]: while value > stack[-1][0] and len(stack) > 0: ans[stack[-1][1]] = (index - stack[-1][1], 'possible') stack.pop() try: #if it is bigger than every value in the stack, then go onto next round stack[-1][0] except IndexError: break stack.append((value,index)) for index, element in enumerate(ans): if type(element) != tuple: ans[index] = 'impossible' return ans
true
fc0aef2e5088ec8934d1367bfc98f883749b66e0
claridiva2000/Intro-Python-I
/src/14_cal.py
1,983
4.5
4
""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import datetime from datetime import date import re # print(calendar.weekheader(3)) # print() # print(calendar.firstweekday()) # print(calendar.month(2019, 11)) # print(date.today()) arguments = sys.argv arg_len = len(arguments) mm_input = input("enter a month: ") yr_input = input("enter a year: ") if mm_input != '' or mm_input != int or yr_input != '' or yr_input != int: print('must enter a number') mm_input = input("enter a month: ") yr_input = input("enter a year: ") elif mm_input != '' and yr_input == '': print(calendar.month(2019, int(mm_input))) elif mm_input != '' and yr_input != '': print(calendar.month(int(yr_input), int(mm_input))) else: print(calendar.month(datetime.now().year, datetime.now().month)) print("please enter a number") # planner = Calendar(mm_input, yr_input) # print(planner) # print(f'{mm_input}/{yr_input}') # mm_input + yr_input == '': # empty = date.today() # # m=int(float(empty[0])) # # y=int(empty[1]) # # print(type(m)) # # print(type(11)) # # print(y) # print(int(empty))
true
99933a71cf8084334fa7384709b6b4d1770b15d0
praveenkumarsrivas/python-practice
/py.checkio.org/electronic-station/brackets.py
1,716
4.40625
4
""" You are given an expression with numbers, brackets and operators. For this task only the brackets matter. Brackets come in three flavors: "{}" "()" or "[]". Brackets are used to determine scope or to restrict some expression. If a bracket is open, then it must be closed with a closing bracket of the same type. The scope of a bracket must not intersected by another bracket. In this task you should make a decision, whether to correct an expression or not based on the brackets. Do not worry about operators and operands. Input: An expression with different of types brackets as a string (unicode). Output: A verdict on the correctness of the expression in boolean (True or False). """ def checkio(expression): stack = [] dict_b = {"{": "}", "[": "]", "(": ")"} for letter in expression: if letter in dict_b.keys(): stack.append(letter) if letter in dict_b.values(): if not (stack and dict_b[stack.pop()] == letter): return False return not stack # def checkio(exp): # s = '' # for i in exp: # if i in '(){}[]': # s += i # if s[-2:] in ('()', '{}', '[]'): # s = s[:-2] # return not s # These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio("((5+3)*2+1)") == True, "Simple" assert checkio("{[(3+1)+2]+}") == True, "Different types" assert checkio("(3+{1-1)}") == False, ") is alone inside {}" assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" assert checkio("2+3") == True, "No brackets, no problem"
true
f9b39244c822d148e9219f7f6fa4da12250f7a0b
dinara-abilekova/python-practice
/merge_sort.py
747
4.15625
4
""" Implementation of Merge Sort """ def merge_sort(arr): if len(arr) <= 1: return(arr) middle = len(arr) // 2 left = merge_sort(arr[:middle]) right = merge_sort(arr[middle:]) return(merge(left, right)) def merge(left, right): result = [] while len(left) > 0 and len(right) > 0: if left[0] <= right[0]: result.append(left[0]) left = left[1:] else: result.append(right[0]) right = right[1:] if len(left) > 0: result += left if len(right) > 0: result += right return(result) arr_size = int(input("Write array's size: ")) import random arr = [random.choice([i for i in range(-1000, 1000)]) for j in range(arr_size)] print("\nArray:") print(arr) print("Sorted array:") sorted_arr = merge_sort(arr) print(sorted_arr)
true
6354b96d076be743d602246234817f0512c4e203
anuragmarale/pythonprojects
/tipbill.py
383
4.15625
4
print("Welcome to Tip Calculator") total_bill= float(input("What is your total bill: ")) total_member=input("How many people are there: ") tip=int(input("How much % would you tip 10, 12 or 15: ")) tip_bill= float(tip/100*total_bill+total_bill) split_bill=tip_bill/int(total_member) final_bill=round(split_bill, 2) print((f"Your total bill per person is {final_bill}"))
true
1be21b663fe8080eab2bce5155a1e90a6dfbeb02
SeekingAura/computationalComplexityCourse
/tarea 2/quick_sort_function.py
609
4.1875
4
def swap(array, a, b): array[a], array[b] = array[b], array[a] def quickSort(array, left, right): # set ref for integer values if left >= right: return pivot = int((left + right) / 2) l = left r = right while True: # Determine l and r for swaping while array[l] < array[pivot]: l += 1 while array[r] > array[pivot]: r -= 1 if l == r: break # swap(array, l, r) array[l], array[r] = array[r], array[l] if l == pivot: pivot = r l += 1 elif r == pivot: pivot = l r -= 1 else: l += 1 r -= 1 quickSort(array, left, pivot-1) quickSort(array, pivot + 1, right)
true
6d31cf491edb012dbc5d11db5b1e7208d3eb54b7
umbrelluck/battleShips
/myPaint/rectangle.py
963
4.1875
4
class Rectangle: def __init__(self, corner, size, border='*', inside=' '): """ Initialize new rectangle. :param corner: corner coordinates. :param size: size of rectangle :param border: symbol that is used to display rectangle border. :param inside: symbol that is used to display rectangle border. """ self._corner = corner self._size = size self.border = border self.inside = inside def view(self, coordinate): """ Display view of rectangle by coordinate. :param coordinate: coordinate of cell. :return: view of rectangle by coordinate. """ if coordinate[0] == self._corner[0] or coordinate[1] == self._corner[1] or \ coordinate[0] == self._corner[0] + self._size[0] - 1 or coordinate[1] == self._corner[1] + self._size[1] - 1: return self.border else: return self.inside
true
653b1716b5de13554a439be0b2cd7b8ab028c4ec
Jrufino/Estrutura-sequencial
/ex11.py
374
4.25
4
numInt1=int(input('Digite um numero inteiro: ')) numInt2=int(input('Digite mais um numero inteiro: ')) numReal=float(input('Digite um numero real: ')) total1=((numInt1*2)*(numInt2/2)) total2=((numInt1*3)+numReal) total3=(numReal**3) print('Primeiro resultado: {}'.format(total1)) print('Segundo resultado: {}'.format(total2)) print('Terceiro resultado: {}'.format(total3))
false
39509b556bbbf10e034b1a3f81e9b812f91220e4
MatteoPalmieri/word_learning
/modules/insert_words.py
1,639
4.3125
4
from .database_functions import * def insert_words(cursor_easy, cursor_hard, connection_easy, connection_hard): """ this functions asks the user what words to insert in the db :param cursor_easy: the cursor of the database words.db :type cursor_easy: object :param cursor_hard: the cursor of the database hard.db :type cursor_hard: object :param connection_easy: the connection of the database words.db :type connection_easy: object :param connection_hard: the connection of the database hard.db :type connection_hard: object :return: """ topic = input("topic > ") language1 = input("language1 > ") language2 = input("language2 > ") while topic != 'X': new_word([topic,language1,language2], cursor_easy, cursor_hard, connection_easy, connection_hard) print(f"({language1},{language2}) inserted in {topic}\n") topic = input("topic > ") language1 = input("language1 > ") language2 = input("language2 > ") def list_words(table, cursor): """ this function lists the words present in a table :param table: the table :type table: str :param cursor: the cursor of the database :type cursor: object :return: """ list = cursor.execute(f'''select * from {table}''') for i in list: print(i) def list_tables(cursor): """ this functions lists all the tables in a database :param cursor: the cursor of the database :type cursor: object :return: """ tables = cursor.execute("""select name from sqlite_master where type='table'""") for i in tables: print(i[0])
true
da1e1347dceababb8b5934e2a6e4d87f5f33119b
NateDreier/Learn_Python
/challenges/fizzbuzz.py
1,111
4.125
4
#!/usr/bin/python3.6 ''' FizzBuzz, print numbers zero through thirty. If the number is divisible by 3 print 'Fizz' if the number is divisible by 5 print 'Buzz', if it is divisible by both, print 'FizzBuzz'. ''' import time start_time = time.time() num = 0 for num in range(31): if num == 0: print(num) # elif num % 3 == 0 and num % 5 == 0: # print('Fizzbuzz') if num % 3 == 0: print('Fizz') if num % 5 == 0: print('Buzz') else: print(num) print('%s seconds ' % (time.time() - start_time)) ''' import time start_time = time.time() def fizzbuzz(start, end): def int_to_fizzbuzz(i): entry = '' if i % 3 == 0 and i % 5 == 0: entry += "fizzbuzz" if i % 3 == 0: entry += "fizz" if i % 5 == 0: entry += "buzz" if i % 3 != 0 and i % 5 != 0: entry += str(i) return entry return [int_to_fizzbuzz(i) for i in range(start, end+1)] #print('%s seconds ' % (time.time() - start_time())) if __name__ == "__main__": start = int(input("starting #: ")) end = int(input("ending #: ")) for i in fizzbuzz(start, end): print(i) print('%s seconds ' % (time.time() - start_time)) '''
false
3a1e5f02a72892fa9e2ba6e11e5c68569f2e3858
yendigo/Pirple
/homework#4.py
1,115
4.15625
4
myUniqueList = [] myLeftovers = [] # the lists are empty print("Please input three numbers or words: ") # title # the user will enter 3 inputs # i limit this to 3 inputs to be not that complicated because my way of coding are long input1 = input("Input1: ") if input1 != myUniqueList: print(True) myUniqueList.append(input1) else: print(False) # adding the 1st input into the list input2 = input("Input2: ") if input2 != input1: print(True) myUniqueList.append(input2) else: print(False) myLeftovers.append(input2) # testing if the 2nd input and the 1st input are not the same # if True, add the value to the list # if False, add the value to the other list input3 = input("Input3: ") if input3 != input2 and input3 != input1: print(True) myUniqueList.append(input3) else: print(False) myLeftovers.append(input3) # testing if the 3rd input, 2nd input and the 1st input are not the same # if True, add the value to the list # if False, add the value to the other list print(myUniqueList) print(myLeftovers)
true
52aba82a70971fd881eeb2ca100320f3ae1019d1
NUsav77/Python-Exercises
/Crash Course/Chapter 7 - User Input and While Loops/7.10_dream_vacation.py
556
4.3125
4
"""Write a program that polls users about their dream vacation. Write a prompt similar to 'if you could visit one place in the world, where would you go?' Include a block of code that prints the results of the poll. """ place = str places = [] active = True while active: if place == 'quit': [print(place.title()) for place in places] active = False place = input('If you could visit one place in the world, where would you go?\n' '(type "quit" to end): ') if place != 'quit': places.append(place)
true
b2cd39c3aff9fd79f578060fa12bd4bf2c216332
NUsav77/Python-Exercises
/Crash Course/Chapter 7 - User Input and While Loops/7.8_deli.py
658
4.40625
4
"""Make a list called sandwich_orders and fill it with the names of various sandwiches. Then make an empty list called finished_sandwiches. Loop through the list of sandwich orders and print a message for each order, such as 'I made your tuna sandwich'. After all the sandwiches have been made, print a message listing each sandwich that was made. """ sandwich_orders = [ 'pb&j', 'tuna', 'ham and cheese', 'turkey breast', ] finished_sandwiches = [] while sandwich_orders: making = sandwich_orders.pop() print(f'\nYour {making} sandwich is being made.') finished_sandwiches.append(making) print('\nYour sandwiches are ready!')
true
8d4ce2a99549a83cced845c502ed2571cfd8271f
NUsav77/Python-Exercises
/Crash Course/Chapter 6 - Dictionaries/6.1_person.py
463
4.25
4
"""Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, las_name, age, and city. Print each piece of information stored in your dictionary. """ pa_xiong = { 'first_name': 'pa', 'last_name': 'xiong', 'dob': '3/30/1986', 'city': 'st. paul', } [print(f"{key}: {value}".title().strip('_')) for key, value in pa_xiong.items()]
true
f9aa6fb23755a8906feef0988d93258a5be33c07
NUsav77/Python-Exercises
/Crash Course/Chapter 8 - Functions/8.5_cities.py
589
4.625
5
"""Write a function called describe_city() that accepts the name of a city and its country. The function should print a simple sentence, such as "San Diego is in United State". Give the parameter for the country a default value. Call your function for three different cities, at least one of which is not in the default country. """ def describe_city(city, country='united states of america'): print(f"{city.title()} is located in {country.title()}.") san_diego = describe_city('san diego') manila = describe_city('manila', 'philippines') paris = describe_city('paris', 'france')
true
5612f45ee60526277bf6ce4c6a1c4c85e25d35c2
NUsav77/Python-Exercises
/Zip/enumerate.py
414
4.28125
4
# Quiz: Enumerate # Use enumerate to modify the cast list so that each element contains the name # followed by the character's corresponding height. For example, the first element # of cast should change from "Barney Stinson" to "Barney Stinson 72". cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"] heights = [72, 68, 72, 66, 76] for i, char in enumerate(cast): cast[i] = char + ' ' + str(heights[i]) print(cast)
true
5c12c57bf261a685209739da5bdcd9a328cd18cf
Yakobo-UG/Python-by-example-challenges
/challenge 33.py
509
4.4375
4
#Ask the user to enter two numbers. Use whole number division to divide the first number by the second and also work out the remainder and display the answer in a user-friendly way (e.g. if they enter 7 and 2 display “7 divided by 2 is 3 with 1 remaining”). first = float(input("Enter first numbers: ")) second = float(input("Enter second numbers: ")) whole = first//second remainder = first%second print("if ", first, "is divided by ", second, "the answer is ", whole, "and a remainder of ", remainder )
true
d6c0016a585ceef2ffea7a9e31cc6334d4b64757
Yakobo-UG/Python-by-example-challenges
/challenge 36.py
244
4.3125
4
#Alter program 035 so that it will ask the user to enter their name and a number and then display their name that number of times. Name = str(input("Enter your name: ")) num = int(input("Enter a number: ")) for i in range(num): print(Name)
true
e88723853e6f176b7b6f62c472c00c323252aabe
Yakobo-UG/Python-by-example-challenges
/challenge 101.py
834
4.3125
4
#Using program 100, ask the user for a name and a region. Display the relevant data. Ask the user for the name and region of data they want to change and allow them to make the alteration to the sales figure. Display the sales for all regions for the name they choose. ''' N S E W John 23 65 87 56 Tom 87 22 77 99 Peter 73 00 83 27 Fiona 11 73 27 89 ''' Dic2D = {"N": {"John": 23, "Tom": 87 , "Peter": 73 , "Fiona": 11 }, "S": { "John":65, "Tom":22, "Peter":00, "Fiona":73}, "E": { "John": 87, "Tom": 77, "Peter":83, "Fiona":27}, "W": { "John": 56, "Tom": 99, "Peter":27, "Fiona":89}} askName = input("Enter name: ") askRegion = input("Enter region: ") print(Dic2D[askRegion][askName]) NewValue = int(input("Enter new value: ")) Dic2D[askRegion][askName] = NewValue print(Dic2D[askRegion])
true
18c9e50369ffbc4748b12e60f2e8ae9cd255b502
Yakobo-UG/Python-by-example-challenges
/challenge 119.py
1,625
4.5
4
''' Define a subprogram that will ask the user to pick a low and a high number, and then generate a random number between those two values and store it in a variable called “comp_num”. Define another subprogram that will give the instruction “I am thinking of a number...” and then ask the user to guess the number they are thinking of. Define a third subprogram that will check to see if the comp_num is the same as the user’s guess. If it is, it should display the message “Correct, you win”, otherwise it should keep looping, telling the user if they are too low or too high and asking them to guess again until they guess correctly. ''' import random def Low_high(): up = int(input("Enter a low number: ")) down = int(input("Enter a high number: ")) comp_num = random.randint(up,down) return comp_num def guess_num(): guess = int(input("I am thinking of a number, what is the number: ")) return guess def check(comp_num, guess): try_agian = True while try_agian == True: if comp_num == guess: print("Correct, you win") try_agian == False elif comp_num > guess: print("Too high try again") try_agian = True guess = int(input("I am thinking of a number, what is the number: ")) elif comp_num < guess: print("Too low try agian") try_agian = True guess = int(input("I am thinking of a number, what is the number: ")) def main(): comp_num = Low_high() guess = guess_num() check(comp_num,guess) main()
true
96cde4257c0dae2406542b23112dabfb0c47b78b
Yakobo-UG/Python-by-example-challenges
/Additional challenges/challenge 42.py
302
4.3125
4
#Create a function that takes a number (from 1 - 60) and returns a corresponding string of hyphens. num = int(input("Enter number between 1 - 60: " )) def num_to_dashes(num): if num in range(1,60): return (num * "-") else: return "Enter between 1 - 60" print(num_to_dashes(num))
true
7abec8051a9828a41cbc391b885a82e8f90a6d3a
Yakobo-UG/Python-by-example-challenges
/challenge 109/challenge 109.py
1,323
4.5625
5
#Display the following menu to the user: ''' 1) Create new file 2) Display the file 3) Add a new file to the file, make a selction of 1,2 or 3: Ask the user to enter 1, 2 or 3. If they select anything other than 1, 2 or 3 it should display a suitable error message. If they select 1, ask the user to enter a school subject and save it to a new file called “Subject.txt”. It should overwrite any existing file with a new file. If they select 2, display the contents of the “Subject.txt” file. If they select 3, ask the user to enter a new subject and save it to the file and then display the entire contents of the file. Run the program several times to test the options. ''' print("1). Create new file: \n2). Display file: \n3). Add new file to the file: ") select = int(input("Enter number between 1,2,3: ")) if select == 1: ask1 = str(input("Enter a school subject: ")) file1 = open("Subject.txt", "w") file1.write(ask1) file1.close() elif select == 2: file1 = open("Subject.txt", "r") print(file1.read()) elif select == 3: ask2 = str(input("Enter new subject: ")) file1 = open("Subject.txt", "a") file1.write(ask2) file1.close() #Displaying file file1 = open("Subject.txt", "r") print(file1.read()) else: print("Error not within the range")
true
23a6c83295d682a41151cca256aa014f0ed79a0b
Yakobo-UG/Python-by-example-challenges
/challenge 19.py
411
4.21875
4
#Ask the user to enter 1, 2 or 3. If they enter a 1, display the message “Thank you”, if they enter a 2, display “Well done”, if they enter a 3, display “Correct”. If they enter anything else, display “Error message” Num = int(input("Enter number: ")) if Num == 1: print("Thank you") elif Num == 2: print("Well done") elif Num == 3: print("Correct") else: print("Error message")
true
032ee6a9122c35bd6e37f10226f2e8178d541761
Yakobo-UG/Python-by-example-challenges
/challenge 21.py
317
4.40625
4
#Ask the user to enter their first name and then ask them to enter their surname. Join them together with a space between and display the name and the length of whole name. First_name = str(input("Enter your first name: ")) Second_name = str(input("Enter your Second name: ")) print(First_name + " " + Second_name)
true
73348fae2dd23a76b93a23bd3212f3938bbb3ecd
Yakobo-UG/Python-by-example-challenges
/challenge 87.py
344
4.40625
4
#Ask the user to type in a word and then display it backwards on separate lines. For instance, if they type in “Hello” it should display as shown below #o #l #l #e #H word = str(input("Enter word: ")) length = len(word) num = 1 for i in word: position = length - num letter = word[position] print(letter) num = num + 1
true
831abfef897ee0fae6f3a4913d41663e42d5fec1
Yakobo-UG/Python-by-example-challenges
/challenge 110 fail/challenge 110.py
820
4.15625
4
#Using the Names.txt file you created earlier, display the list of names in Python. Ask the user to type in one of the names and then save all the names except the one they entered into a new file called Names2.txt. #creating the file NewFile = open("Name.txt", "w") NewFile.write("jamse \n") NewFile.write("Timmy \n") NewFile.write("zick \n") NewFile.close #reading the file in terrminal NewFile = open("Name.txt", "r") print(NewFile.read()) NewFile.close() #typing one of the names NewFile = open("Name.txt", "r") OneOftheNames = str(input("Type in one of the names: ")) for i in NewFile: if i != OneOftheNames: NewFile = open("Name2.txt", "a") NewFile.write(i) NewFile.close() NewFile.close() #reading the file NewFile = open("Name2.txt", "r") print(NewFile.read()) #failed to do it
true
7b36112d1282d16a621fb345227084598c4287d2
Yakobo-UG/Python-by-example-challenges
/challenge 51.py
1,220
4.125
4
#Using the song “10 green bottles”, display the lines “There are [num] green bottles hanging on the wall, [num] green bottles hanging on the wall, and if 1 green bottle should accidentally fall”. Then ask the question “how many green bottles will be hanging on the wall?” If the user answers correctly, display the message “There will be [num] green bottles hanging on the wall”. If they answer incorrectly, display the message “No, try again” until they get it right. When the number of green bottles gets down to 0, display the message “There are no more green bottles hanging on the wall” bottles = 10 print("There are", bottles," green bottles hanging on the wall,", bottles, " green bottles hanging on the wall, and if 1 green bottle should accidentally fall") while bottles == 10: bottles = bottles -1 ask = int(input("how many green bottles will be hanging on the wall?: ")) if ask == bottles: print("There will be", bottles, " green bottles hanging on the wall") else: while ask != bottles: print("No, try again") ask = int(input("how many green bottles will be hanging on the wall?: ")) #failed to solve this one
true
4d780fb6dbaebbcc66d4c78b7054daea78f017d4
Yakobo-UG/Python-by-example-challenges
/Additional challenges/challenge 45.py
537
4.3125
4
''' Make a function that encrypts a given input with these steps: Input: "apple" Step 1: Reverse the input: "elppa" Step 2: Replace all vowels using the following chart: a => 0 e => 1 o => 2 u => 3 Step 3: Add "aca" to the end of the word: "1lpp0aca" Output: "1lpp0aca" ''' def encrypt(word): backword = str(word[::-1]) a = backword.replace("a", "0") b = a.replace("e", "1") c = b.replace("o", "2") d = c.replace("u", "3") e = d.replace("i", "4") return e + "aca" print(encrypt(input("Enter word: ")))
true
43391d164842abd2b12af0cdb38e82fa1a119362
Yakobo-UG/Python-by-example-challenges
/challenge 124.py
676
4.3125
4
#Write a program that can be used instead of rolling a six-sided die in a board game.When the user clicks a button it should display a random whole number between 1 to 6 (inclusive). import random from tkinter import * def onclick(): change = random.randint(1,6) enrty["text"] = change #frame window = Tk() window.title("dice game") window.geometry("500x500") #button when pressed button = Button(text="Click to get number", command= onclick ) button.place(x=155, y=200, width=150, height=70) #where the number will be displayed enrty = Message(text=" ") enrty.place(x = 170, y= 100, width= 120, height= 90) enrty["bg"] = "yellow" enrty["fg"] = "blue" mainloop()
true
3c53fc7954c21a482586ccc69c883a83dc3377c2
Yakobo-UG/Python-by-example-challenges
/Additional challenges/challenge 41.py
299
4.1875
4
#Given two strings, first_name and last_name, return a single string in the format "last, first". FirstName = str(input("ENter your name: ")) SecondName = str(input("Enter your second name: ")) def One(FirstName, SecondName): return FirstName + " " + SecondName print(One(FirstName, SecondName))
true
4ef14a93571a08526b04696a9cf90a3a72e15017
Yakobo-UG/Python-by-example-challenges
/Additional challenges/challenge 27.py
202
4.375
4
#Write a program that works out whether if a given number is an odd or even number. num = int(input("Enter number: ")) if num%2 == 0: print("The number is even") else: print("The number is odd")
true
a7e64079945a247ba70db5238faaed3bdaad5787
Yakobo-UG/Python-by-example-challenges
/challenge 46.py
316
4.40625
4
#Ask the user to enter a number. Keep asking until they enter a value over 5 and then display the message “The last number you entered was a [number]” and stop the program num = int(input("Enter number: ")) while num < 5: num = int(input("Enter number: ")) print ("The last number you enter was ", num)
true
84336647742c3b1cc43ce861988b3c8463f27330
by3nrique/2019-2020-PNE-Practices
/Session-03/dna_count.py
610
4.21875
4
dna_sequence = input("Introduce the sequence: ") # The user enters the sequence directly def count(dna_seq): A = 0 G = 0 T = 0 C = 0 for base in dna_seq: if base == "A": A += 1 # When there is an "A" we add 1 to the counter A elif base == "G": G += 1 elif base == "T": T += 1 elif base == "C": C += 1 return A, C, T, G print("Total length is: ", len(dna_sequence)) print("A: ", count(dna_sequence)[0], "C: ", count(dna_sequence)[1], "T:", count(dna_sequence)[2], "G: ", count(dna_sequence)[3])
true
2f0ea0e2ce381ab2dd55f2971e78bc377fddea7a
sochief/Python-Practice
/str_methods.py
324
4.125
4
name = 'Turkey' #String object if name.startswith('Tur'): print('\n\nString starts with Tur') if 'e' in name: print('\n\nString has a letter e') if name.find('key') != -1: print('\n\nString has the string "key"\n\n') razdelitel = ' ' myList = ['Brazil','China','Russia','India'] print(razdelitel.join(myList))
false
a3657dd77bfbd7eae48df54dd7cc58ab6793e37b
Nguyen-Quynh-Nga/SS1
/HW2/problem6.py
840
4.25
4
# Function cal_frequency take a string as input and return character that appear most def cal_frequency(string): # Creat a dictionary that its keys are character of string and value is the times it appears frequency_dict = dict.fromkeys(string,0) char_appear_most = '' count_frequency = 0 for ch in string: frequency_dict[ch] += 1 for key in frequency_dict: if frequency_dict[key] >= count_frequency: count_frequency = frequency_dict[key] char_appear_most = key print(frequency_dict) return char_appear_most def main(): string = input("Enter a string: ") # Call cal_frequency function to get character appear most frequently char_appear_most = cal_frequency(string) print("The character that appear most frequently is ", char_appear_most) main()
true
23c04d082342e71d6a453c2310b81d85ddc9b638
Nguyen-Quynh-Nga/SS1
/HW2/problem2.py
468
4.28125
4
def main(): date = str(input("Enter date in form mm/dd/yy: ")) print_date(date) def print_date(date): new_date = date.split("/") months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] string_date = "" string_date += months[int(new_date[0])-1]+' ' string_date += new_date[1] string_date += ', ' string_date += new_date[2] print(string_date) main()
false
8a6527f61e7c773ac17313dd3228457370b30b7a
ShivamBhosale/100DaysOfCode
/Day03/Insertionsort.py
773
4.15625
4
"""Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. -Source Geek fo Geeks""" def insertionSort(arr): for i in range(1,len(arr)): key = arr[i] j= i-1 while j>=0 and key < arr [j]: arr[j+1] = arr[j] j-= 1 arr[j+1] = key return arr n= int(input("Enter the number of elements in the array: ")) b = list(map(int,input("Enter the numbers : ").strip().split()))[:n] print("The unsorted array is",b) c=insertionSort(b) print("The sorted array is",c) #Time Complexity O(n^2)
true
da5920b825452553723d25c2292b53b60f5e9511
GuruPrasath7/Python-Linked-List
/insert_linked_list.py
1,125
4.25
4
class Node: def __init__(self, data): """ The structure of a node of a linked list """ self.data = data self.next = None class LinkedList: def __init__(self, head): """ The current pointer only should be moved, not head. """ self.head = None self.current = None def insert(self, data, linked_list): node = Node(data) linked_list.current.next = node def print_linkedList(self, head): temp = head while temp: print(temp.data) temp = temp.next linked_list = LinkedList() print("Enter the number of elements to be inserted in the linked list: ") size = int(input()) print("Enter the elements to be inserted in the linked list: ") i = 0 while i < size: element = int(input()) if not linked_list.head: node = Node(element) linked_list.head = node linked_list.current = node else: node = Node(element) linked_list.current.next = node linked_list.current = node i+=1 print("The inserted linked list is: ") linked_list.print_linkedList(linked_list.head)
true
22a69053394f360c59f6e7d5930f0ee8557b90c7
Prakash190797/Pect-A
/day2/A7.py
1,506
4.5
4
#--------------Files Operations----------------- #We are able to store data for later use in files #you can create or use an already created file with open #if you use w(write) for mode the the file is overwritten. #if you use a(append) you add to the end of the file #text is stored using unicode where numbers represent all #possible characters #we start the code with 'with' which guarantees the file #will be closed if the program crashes import os with open("mydata5.txt", mode = 'w', encoding= 'utf-8') as myFile: #you can write to the file with 'write' #it doesn't add a newline myFile.write("Some random text\n More random text\n and some more") with open("mydata5.txt", encoding= "utf-8") as myFile: # We can read data in a few ways # 1. read() reads everything into 1 string # 2. readline() reads everything including the first newline # 3. readlines() returns a list of every line which includes # each newline print(myFile.read()) # Find out if the file is closed print(myFile.closed) #gives the name of the file print(myFile.name) #gives the mode of the file print(myFile.mode) os.rename("mydata5.txt", "mydata6.txt") #delete a file #os.remove("mydata3.dat") #create directory os.mkdir("mydir2") #change directories os.chdir("mydir2") #display current directory print("current Directory:", os.getcwd()) #remove a direcotry but 1st move back 1 directory os.chdir("..") os.rmdir("mydir2") #Note: every time you have to change the file name
true
24cd74c4ba29c5277c6ddb25d276ac0da40c4935
Prakash190797/Pect-A
/S19.py
1,737
4.125
4
#Intro to functions def add_numbers(num1, num2): return num1 + num2 print("5 + 4 =", add_numbers(5,4)) #function local variables # Variables created in a function can't be accessed outside # of it def assign_name(): name = "Doug" assign_name() # You can't change a global variable even if it is passed # into a function def change_name(name): name = "Mark" name = "Tom" change_name(name) print(name) # If you want to change the value pass it back def change_name_2(): return "Mark" name = change_name_2() print(name) # You can also use the global statement to change it gbl_name = "Sally" def change_name_3(): global gbl_name gbl_name = "Sammy" change_name_3() print(gbl_name) #Returning None def get_sum(num1, num2): sum = num1 + num2 print(get_sum(5,4)) #problem: Solve for X # Make a function that receives an algebraic equation like # x + 4 = 9 and solve for x def solve_eq(equation): x,add,num1,equal,num2 = equation.split() num1, num2 = int(num1), int(num2) return "x=" + str(num2 - num1) print(solve_eq("X + 4 = 9")) #Return multiple values def mult_divide(num1, num2): return (num1 * num2),(num1 / num2) mult,divide = mult_divide(5,4) print("5 * 4 = ", mult) print("5 / 4 = ", divide) #Return a list of primes def isprime(num): for i in range(2, num): if(num%i == 0 ): return False return True def getPrimes(max_number): list_of_primes = [] for num1 in range(2, max_number): if isprime(num1): list_of_primes.append(num1) return list_of_primes max_num_to_check = int(input("Search for Primes Up to:")) list_of_primes = getPrimes(max_num_to_check) for prime in list_of_primes: print(prime)
true
b2746bde514e52dc37d1e356d8cd74da85f16c72
Parth-Ps/python
/csv_parsing/practise.py
1,292
4.1875
4
import csv # NORMAL METHOD # with open('names.csv', "r") as f: # csv_reader = csv.reader(f) # # next(csv_reader) # start from 1 index # with open('practise_new.csv', 'w') as new_file: # csv_writer = csv.writer(new_file, delimiter='\t') # for line in csv_reader: # csv_writer.writerow(line) # # for line in csv_reader: # # print(line[2]) # DICT READER METHOD # with open('names.csv', 'r') as csv_file: # csv_reader = csv.DictReader(csv_file) # for line in csv_reader: # print(line['email']) # DICT METHOD FOR WRITING CSV FILE # using Dict method we can select particular column and parse to another csv file. with open('names.csv', 'r') as csv_file: csv_reader = csv.DictReader(csv_file) with open('dict_new_names.csv', 'w') as new_file: # fieldnames must be same as written in original csv file fieldnames = ['me', 'last_name'] # Do not mension the column which we dont want csv_writer = csv.DictWriter( new_file, fieldnames=fieldnames, delimiter='\t') # It also copy the header from original csv file. csv_writer.writeheader() for line in csv_reader: del line['email'] # delete email column csv_writer.writerow(line)
true
49bf56b49972625be0bccf066f16750bc970d0dc
arminv/Interview-Practice-Python
/maxchar.py
861
4.25
4
def maxChar(str): """ Given a string, return the character that is most commonly used in the string. >>> maxChar('abcdefghijklmnaaaaa') 'a' >>> maxChar('ab1c1d1e1f1g1') '1' """ charMap = {} max = 0 maxChar = '' for char in str: """The key difference is here. In Python we need to explicitly access dictionary keys using the built-in function .keys() and check if there is one corresponding to the character: """ if char in charMap.keys(): charMap[char] += 1 else: # If there is no corresponding key, we initialize # it to 1: charMap[char] = 1 for char in charMap: if charMap[char] > max: max = charMap[char] maxChar = char return maxChar # --------------------------------- # TESTS: # This runs tests based on the docstring of the function: if __name__ == '__main__': import doctest doctest.testmod()
true
645387dd18cdceee1044d5ff6cb02d177fa8e6cf
arminv/Interview-Practice-Python
/steps.py
1,072
4.40625
4
def steps(n, row = 0, stair = ''): """ Write a function that accepts a positive number N. The function should console log a step shape with N levels using the # character. Make sure the step has HYPHENS on the right hand side! >>> steps(2) #- ## >>> steps(3) #-- ##- ### >>> steps(4) #--- ##-- ###- #### """ # NOTE: I added hyphens instead of spaces to the right side # of stair. It is easier to see what is going on (also better for testing!) # SOLUTION 1: if n == row: return if n == len(stair): print(stair) return steps(n, row + 1) if len(stair) <= row: add = '#' else: # Original solution adds ' ', we add '-' instead for clarity: add = '-' steps(n, row, stair + add) # SOLUTION 2: # for row in range(0, n): # stair = "" # for column in range(0, n): # if column <= row: # stair += '#' # else: # stair += '-' # print stair # --------------------------------- # TESTS: # This runs tests based on the docstring of the function: if __name__ == '__main__': import doctest doctest.testmod()
true
a48398ab1eb98c0f4f3f7a8f8765aa1cde1ff132
GurutheKing/js_sample
/vscode_8.py
509
4.25
4
course ="The values are \"good\"" print(course) letter =''' Hello guru, thanks for coming ''' print(letter) print(course[0:2]) print(len(course)) #print(firstname.upper()) firstname="gururajan" lastname="Srinivasan" output =f'{firstname} [{lastname}] is a coder' output2 =firstname + " [" + lastname + "] is a coder" print(output) print(output2) print(firstname.capitalize()) print(lastname.upper()) print(lastname.lower()) print(firstname.find('guru')) course3= "Python for beginners" print(len(course3))
false
32ec22069c3682bc6ed96135d5ec32615a999e8c
sandeepyadav10011995/Data-Structures
/Pattern-Two Pointers/3. TripletToSumZero.py
2,369
4.1875
4
""" In problems where we deal with sorted arrays (or LinkedLists) and need to find a set of elements that fulfill certain constraints, the Two Pointers approach becomes quite useful. The set of elements could be a pair, a triplet or even a sub-array. Problem Statement : Given an array of unsorted numbers find all the unique triplets in it that add up to zero. Algo : Since the array is not sorted and instead of a pair we need to find triplets with a target sum of zero. Another difference is that we need to find all the unique triplets. To handle this, we have to skip any duplicate number. Since we will be sorting the array, so all the duplicate numbers will be next to each other and easier to skip. Example 1: Input: [-3, 0, 1, 2, -1, 1, -2] Output: [-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1] Explanation: There are four unique triplets whose sum is equal to zero. """ from typing import List class TripletToSumZero: @staticmethod def search_triplets(nums: List[int]) -> List[List[int]]: # Sort the array nums.sort() triplets = [] for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: # To skip the duplicates continue TripletToSumZero.search_pairs(nums, -nums[i], i+1, triplets) return triplets @staticmethod def search_pairs(nums, target_sum, left, triplets): right = len(nums) - 1 while left < right: cur_sum = nums[left] + nums[right] if cur_sum == target_sum: triplets.append([-target_sum, nums[left], nums[right]]) left += 1 right -= 1 while left < right and nums[left] == nums[left-1]: left += 1 # Skip same element to avoid duplicate triplets while left < right and nums[right] == nums[right+1]: right -= 1 # Skip same element to avoid duplicate triplets elif target_sum > cur_sum: left += 1 # We need a pair with a bigger sum else: right -= 1 # We need a pair with a smaller sum def main(): ttsz = TripletToSumZero() print(ttsz.search_triplets([-3, 0, 1, 2, -1, -1, 1, -2])) main() """ Time Complexity: O(N*LogN) - Sorting + N*N ==> O(N^2) Space Complexity: O(N) """
true
6782e77ce8c88a89fa7e37987478da53b5ee2c16
sandeepyadav10011995/Data-Structures
/Pattern-Two Pointers/Template.py
2,916
4.3125
4
""" In problems where we deal with sorted arrays (or LinkedLists) and need to find a set of elements that fulfill certain constraints, the Two Pointers approach becomes quite useful. The set of elements could be a pair, a triplet or even a sub-array. For example -: Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target. --> Two Sum Bruteforce Approach -: N^2 --> NlogN (If we use Binary Search since the array is sorted) Optimized Approach -: Given that the input array is sorted, an efficient way would be to start with one pointer in the beginning and another pointer at the end. At every step, we will see if the numbers pointed by the two pointers add up to the target sum. If they do not, we will do one of two things: a. If the sum of the two numbers pointed by the two pointers is greater than the target sum, this means that we need a pair with a smaller sum. So, to try more pairs, we can decrement the end-pointer. b. If the sum of the two numbers pointed by the two pointers is smaller than the target sum, this means that we need a pair with a larger sum. So, to try more pairs, we can increment the start-pointer. Example 1: Input: [1, 2, 3, 4, 6], target=6 Output: [1, 3] Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6 Example 2: Input: [2, 5, 9, 11], target=11 Output: [0, 2] Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11 """ from typing import List class TwoSum: @staticmethod def find_two_sum(nums: List[int], target_sum: int) -> list: left = 0 right = len(nums)-1 while left < right: current_sum = nums[left] + nums[right] if current_sum == target_sum: return [left, right] elif current_sum < target_sum: left += 1 # we need a pair with a bigger sum else: right -= 1 # we need a pair with a smaller sum return [-1, -1] """ Time Complexity: O(N) Space Complexity: O(1) """ """ Follow Up: What if the array is not sorted ? Approach: Using Hash Map """ class TwoSum2: @staticmethod def find_two_sum(nums: List[int], target: int) -> List[int]: nums_to_index = {} for i, num in enumerate(nums): if target-num in nums_to_index: return [nums_to_index[target-num], i] nums_to_index[num] = i """ Time Complexity: O(N) Space Complexity: O(N) """ def main(): ts = TwoSum() print(ts.find_two_sum([1, 2, 3, 4, 6], 6)) print(ts.find_two_sum([2, 5, 9, 11], 11)) main()
true
8b5b1e60a9bcf9098c1fd82d6907e73bb82f7290
sandeepyadav10011995/Data-Structures
/30 Days Challenge/Valid Sequence.py
1,662
4.21875
4
""" Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree. Example 1: Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1] Output: true Explanation: The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). Other valid sequences are: 0 -> 1 -> 1 -> 0 0 -> 0 -> 0 Example 2: Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1] Output: false Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence. Example 3: Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1] Output: false Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence. """ class Solution: def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool: def preorder(root, i=0): # Base Case if root is None: return # Leaf Case if root.left is None and root.right is None: if i > len(arr) - 1: return False if i == len(arr) - 1 and root.val == arr[i]: return True if i < len(arr)-1 and root.val != arr[i]: return False return preorder(root.left, i+1) or preorder(root.right, i+1) return preorder(root)
true
ccd5e5905f7b1d016444331c12af4e3944d0bc1f
sandeepyadav10011995/Data-Structures
/Pattern-Sliding Window/1. Max Sum Sub-Array(K Size).py
2,118
4.1875
4
""" ------------------------------------------------ SLIDING WINDOW -------------------------------------------------------- Types of Sliding Window -: 1. Fixed Length : When k, i.e. sliding window size is provided as a constraint. 2. Dynamic Variant: Caterpillar How to recognize these problems ? Things we iterate over sequentially; a. Contiguous Sequence of elements. b. Sliding arrays, linked-lists In terms of the way questions are asked ? => Min, Max, Largest, Shortest Questions Variants 1. Fixed Length: Max Sub-array of size k 2. Dynamic Variant: Smallest Sum (equal to S) => Will need to use Auxiliary DS, i.e. Arrays or Hashmap a. Largest sub-string with no more than k distinct characters. b. String Permutations Question: Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous sub-array of size ‘k’. Example: Output: ------------------------------------------------------ CODE ------------------------------------------------------------ """ from typing import List class MaxSumSubArray: @staticmethod def find_max_sum_sub_array(nums: List[int], k: int) -> int: max_sum = 0 window_sum = 0 window_start = 0 for window_end in range(len(nums)): window_sum += nums[window_end] # slide the window, we don't need to slide if we've not hit the required window size of 'k' if window_end >= k-1: max_sum = max(max_sum, window_sum) # update the max-sum window_sum -= nums[window_start] # sub the element going out window_start += 1 # slide the window ahead return max_sum def main(): msa = MaxSumSubArray() print("Maximum sum of a sub-array of size K: " + str(msa.find_max_sum_sub_array([2, 1, 5, 1, 3, 2], 3))) print("Maximum sum of a sub-array of size K: " + str(msa.find_max_sum_sub_array([2, 3, 4, 1, 5], 2))) main() """ Overall TC : O(2N) --> O(N) Overall SC: O(1) --> O(1) """
true
26a0fbfbac45db786df164df47dec1a690a935b8
joeb15/202Problems
/queues/list_queue/queue.py
897
4.34375
4
#!/usr/bin/python3 """ A queue is a first-in first-out type of data structure For this to work, you must be able to enqueue (add) items to the queue, dequeue (remove) items from the queue """ class List_Queue: """ Creates a List Queue """ def __init__(self, size): self.size = size self.num_items = 0 self.front = 0 self.end = 0 self.list = [None for i in range(self.size)] """ returns whether the queue is full or not """ def is_full(self): """ Method will add a new items to the end of the queue return True if successful return False if not enough space in queue """ def enqueue(self, item): """ Method will remove the first item from the queue and return it Raises an IndexError if no items are in the queue """ def dequeue(self):
true
762d8c198937b541e1f555fcee2664f5449aeecc
Amberttt/Python3-Test
/examples/2numberAdd.py
1,524
4.46875
4
# Python 数字求和 # Document 对象参考手册 Python3 实例 # 以下实例为通过用户输入两个数字,并计算两个数字之和: # 实例(Python 3.0+) # # -*- coding: UTF-8 -*- # # Filename : test.py # # author by : www.runoob.com # # 用户输入数字 # num1 = input('输入第一个数字:') # num2 = input('输入第二个数字:') # # 求和 # sum = float(num1) + float(num2) # # 显示计算结果 # print('数字 {0} 和 {1} 相加结果为: {2}'.format(num1, num2, sum)) # 执行以上代码输出结果为: # 输入第一个数字:1.5 # 输入第二个数字:2.5 # 数字 1.5 和 2.5 相加结果为: 4.0 # 在该实例中,我们通过用户输入两个数字来求和。使用了内置函数 input() 来获取用户的输入,input() 返回一个字符串,所以我们需要使用 float() 方法将字符串转换为数字。 # 两数字运算,求和我们使用了加号 (+)运算符,除此外,还有 减号 (-), 乘号 (*), 除号 (/), 地板除 (//) 或 取余 (%)。更多数字运算可以查看我们的Python 数字运算。 # 我们还可以将以上运算,合并为一行代码: # 实例(Python 3.0+) # # -*- coding: UTF-8 -*- # # Filename : test.py # # author by : www.runoob.com # print('两数之和为 %.1f' %(float(input('输入第一个数字:'))+float(input('输入第二个数字:')))) # 执行以上代码输出结果为: # $ python test.py # 输入第一个数字:1.5 # 输入第二个数字:2.5 # 两数之和为 4.0
false
c53d2ccd12ba6b057724890e2b243e5c1c75b403
RandyG3/TheGreatCourses
/Python/14. Bottom-Up Design, Turtle Graphics, Robotics/TallyMarks.py
816
4.15625
4
from turtle import * def drawtally(): left(90) forward(20) backward(20) right(90) shiftright() def shiftright(): penup() forward(5) pendown() def drawslash(): # Move up left(90) penup() forward(3) pendown() # Draw Slash startposition = pos() goto(startposition[0]-25, startposition[1]+14) # Return to starting position penup() goto(startposition) backward(3) right(90) pendown() # Shift over shiftright() shiftright() def drawfive(): for i in range(5): drawtally() drawslash() def drawtallies(n): while n >= 5: drawfive() n = n - 5 while n >= 1: drawtally() n = n - 1 num_to_draw = int(input("Enter a number:")) drawtallies(num_to_draw) input()
false
c047e6e1817fa78713edbdf2cfb472f54955706d
HamplusTech/data-science-_-python
/ScalarVectorClass.py
1,083
4.1875
4
from math import sqrt class Point(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self,other): if isinstance(other, Point): return Point(self.x + other.x, self.y + other.y ) else: return TypeError ("Expected Point but got %s" %type(other)) def __sub__(self,other): if isinstance(other, Point): return Point(self.x - other.x, self.y - other.y ) else: return TypeError ("Expected Point but got %s" %type(other)) def __mul__(self,other): if isinstance(other, Point): return (self.x * other.x + self.y * other.y ) elif isinstance (other, int): return Point(self.x * other , self.y * other ) else: return TypeError ("Expected Point or Int but got %s" %type(other)) def distance(self, other): return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) def __repr__(self): return f"Point({self.x}, {self.y})"
false
8ed0832f7cd22d8e619d0d64d21519162aae6a18
Authorcai/Python-Practise
/Codes/1.Grammar_Practise/d7p2.py
670
4.125
4
""" 设计一个函数产生指定长度的验证码,验证码由大小写字母和数字构成 思路: 设置一个初始字符串,包括数字和大小写字母,设定长度,用for-in循环随机得到索引位置并取得字符串元素连接至空串山 Version: 0.1 Author: Authorcai """ import random def yanZhenma(code_len=10): code = "" str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456790" length = len(str) for n in range(code_len) : m = random.randint(0,length) para = str[m] code = code + para return code num = int(input('请输入想要获取的验证码的长度')) print(yanZhenma(num))
false
8cd4f73cb3d98012543fc1e24e7da59f9c3a5431
Python-lab-cycle/kavya_python
/co1_2_leapyr.py
296
4.15625
4
print("Print leap year between two given years") print("Enter start year") startYear = int(input()) print("Enter last year") endYear=int(input()) print("List of leap years:") for year in range(startYear,endYear): if((year%4==0)and(year%100!=0)or (year%400==0)): print(year)
true
db1b93e25c28ca853408a4e6eab519894955290e
Python-lab-cycle/kavya_python
/co1_6_name.py
322
4.125
4
Astr=input("enter the string\n") char=input("enter the character\n") print("Given String:\n", Astr) print("Given Character:\n",char) res = 0 for i in range(len(Astr)): # Checking character in string if (Astr[i] == char): res = res + 1 print("Number of time character is present in string:\n",res)
true
d7b1db136418a5929a31e1a7b7c3b93a40cb3747
beng0/myworkspace35
/somepractice/202012102property.py
784
4.15625
4
# 使用property作为装饰器 class Rectangle: def __init__(self,x1,y1,x2,y2): self.x1,self.y1 = x1,y1 self.x2,self.y2 = x2,y2 @property def width(self): """rectangle height measured from top""" return self.x2 - self.x1 @width.setter def width(self,value): self.x2 = self.x1 + value @property def height(self): """rectangle height measured from top""" return self.y2 - self.y1 @height.setter def height(self,value): self.y2 = self.y1 + value def __repr__(self): return "{}({},{},{},{})".format(self.__class__.__name__,self.x1,self.y1,self.x2,self.y2) rectangle = Rectangle(10,10,20,30) print(rectangle.width,rectangle.height) rectangle.width = 100 print(rectangle)
false
cea152b884b91425653577831abd7b1d074977d4
aiden0z/snippets
/leetcode/114_flatten_binary_tree_to_linked_list.py
2,988
4.3125
4
"""Flatten Binary Tree to Linked List Given the root of a binary tree, flatten the tree into a "linked list": * The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null; * The "linked list" should be in the same order as a pre-order traversal of the binary tree. Example 1: https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg 1 1 / \ \ / \ 2 2 5 --> \ / \ \ 3 3 4 6 \ 4 \ 5 \ 6 Input: root = [1, 2, 5, 3, 4, null, 6] Output: [1, null, 2, null, 3, null, 4, null, 5, null, 6] Example 2: Input: root = [] Output: [] Example 3: Input: root = [0] Output: [0] Constraints: * The number of nodes in the tree is in the range [0, 2000] * -100 <= Node.val <= 100 Follow-up: Can you flatten the tree in-place (with O(1) extra space)? """ from typing import Optional from utils.binary_tree import TreeNode from utils.binary_tree import BinaryTreeFormatter, BinaryTreeBuilder class Solution: def flatten(self, root: Optional[TreeNode]) -> None: """ Do not return anything, modify root in-place instead. 1. 将 root 的左子树和右子树木拉平; 2. 将 root 的右子树接到左子树下方,然后将整个左子树作为右子树; """ if root is None: return self.flatten(root.left) self.flatten(root.right) # 后序遍历位置 # 1. 左右子树已经被拉平成一条链表 left = root.left right = root.right # 2. 将左子树作为右子树 root.left = None root.right = left # 3. 将原右子树接到当前右子树的末端 p = root while p.right is not None: p = p.right p.right = right if __name__ == '__main__': testcases = [ ([1, 2, 5, 3, 4, None, 6], [1, None, 2, None, 3, None, 4, None, 5, None, 6]), ([0], [0]), (None, None), ] ss = (Solution(), ) for case in testcases: root = BinaryTreeBuilder.build_from_level_ordered(case[0]) expect_root = BinaryTreeBuilder.build_from_level_ordered(case[1]) for s in ss: s.flatten(root) if root is None: assert root == expect_root else: result = [node.val for node in BinaryTreeFormatter.level_order(root)] assert result == [node.val for node in BinaryTreeFormatter.level_order(expect_root)]
true
983e11fcf9cdf34256e71bd03dbd477393b7839c
aiden0z/snippets
/leetcode/226_invert_binary_tree.py
1,835
4.15625
4
"""Invert Binary Tree Given the root of a binary tree, invert the tree, and return its root. Example 1: https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg 4 4 / \ / \ 2 7 --> 7 2 / \ / \ / \ / \ 1 3 6 9 9 6 3 1 Input: root = [4, 2, 7, 1, 3, 6, 9] Output: [4, 7, 2, 9, 6, 3, 1] Example 2: https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg 2 2 / \ --> / \ 1 3 3 1 Input: root = [2, 1, 3] Output: [2, 3, 1] Example 3: Input: root = [] Output: [] Constraints: * The number of nodes in the tree is in the range [0, 100] * -100 <= Node.val <= 100 """ from typing import Optional from utils.binary_tree import TreeNode, BinaryTreeBuilder, BinaryTreeFormatter class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None root.left, root.right = root.right, root.left if root.left: self.invertTree(root.left) if root.right: self.invertTree(root.right) return root if __name__ == '__main__': testcases = [ ([4, 2, 7, 1, 3, 6, 9], [4, 7, 2, 9, 6, 3, 1]), ([2, 1, 3], [2, 3, 1]), (None, None), ] ss = (Solution(), ) for case in testcases: root = BinaryTreeBuilder.build_from_level_ordered(case[0]) for s in ss: inverted_tree = s.invertTree(root) if inverted_tree: result = [node.val for node in BinaryTreeFormatter.level_order(inverted_tree)] else: result = inverted_tree assert result == case[1]
true
692228598f75f3091f0fc72b09c8e687de1d305b
aiden0z/snippets
/leetcode/062_unique_paths.py
1,971
4.28125
4
""" Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). +-----------+-----+-----+-----+-----+-----+ |start| | | | | | | | | | | | | | | +-----------------------------------------+ | | | | | | | | | | | | | | | | +-----------------------------------------+ | | | | | | |finish | | | | | | | | +-----+-----+-----+-----+-----+-----+-----+ ![leetcode picture](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) How many possible unique paths are there ? Example 1: Input: m = 3, n = 2 Output: 3 Explation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 Constraints: * 1 <= m, n <= 100 * It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9. """ class Solution: def uniquePaths(self, m: int, n: int) -> int: """DP solution 维护一个二维数组 dp,其中 dp[i][j] 表示到 i,j 所在位置不同的走法的个数 可以获得状态转移方程 dp[i][j] = dp[i-1][j] + dp[i][j-1] """ # 使用一维数组实现 dp = [1] * n for i in range(1, m): for j in range(1, n): dp[j] += dp[j - 1] return dp[n - 1] if __name__ == '__main__': cases = [ ((3, 2), 3), ((7, 3), 28), ] # yapf: disable for case in cases: for S in [Solution]: assert S().uniquePaths(case[0][0], case[0][1]) == case[1]
true
5a3b67e4894c9821eed90a03ed854c86825e7e9c
izikeros/scripts
/my_scripts/promptify_code.py
2,099
4.125
4
#!/usr/bin/env python3 """ A script to create a text file containing a prompt with the instruction to find potential bugs in the code below, and add the content of all *.py files with code and context. Example: python3 create_prompt_with_code.py -i "Find potential bugs in the code below:" -o "prompt_with_code.txt" This script will create a text file called `prompt_with_code.txt` containing the provided instruction and the content of all `*.py` files in the project. The file path of each Python file is added as context. You can customize the instruction and output file path using the `-i` and `-o` flags, respectively. """ import argparse import os import glob def create_prompt(instruction, output_file): """ Create a prompt with the given instruction and save it to the output_file. Args: instruction (str): The instruction for the prompt. output_file (str): The path of the output file. """ with open(output_file, "w") as f: f.write(instruction + "\n\n") def add_python_files(output_file): """ Add the content of all *.py files to the output_file with the file path as context. Args: output_file (str): The path of the output file. """ for filepath in glob.glob("**/*.py", recursive=True): with open(output_file, "a") as f: f.write(f"File path: {filepath}\n") with open(filepath, "r") as py_file: f.write(py_file.read()) f.write("\n\n") def main(): parser = argparse.ArgumentParser( description="Create a prompt and add Python code from the project." ) parser.add_argument( "-i", "--instruction", default="Find potential bugs in the code below:", help="The instruction for the prompt.", ) parser.add_argument( "-o", "--output", default="prompt_with_code.txt", help="The path of the output file.", ) args = parser.parse_args() create_prompt(args.instruction, args.output) add_python_files(args.output) if __name__ == "__main__": main()
true
18f00ca5d02d856d67f0020357372c2fe7f29419
ravenclaw1999/fintech-focus-2020
/day-1/hello.py
510
4.34375
4
print("hello, world") #string: '' or "" characters print("4" + "3") #int - a whole number print(4 + 3) #float - decimal number print(4.0 + 3.0) #play time: print("5" + str(5)) print(4.0 + 4) print("4" * 4) # variable - storage container for data name = "human" print("good day " + name + "!!!") # string formatting print(f"good day {name}!!!") #concatenation: joining strings together print("good day " + name.capitalize() + "!!!") # built in function: operate/ action => give you back a value print()
true
232eb7723c059f589f1d662cfb0e7f7d0be38aca
Eugene0469/The-Python_Workshop
/4. Extending Python, Files, Errors, ad Graphs/barPlot.py
844
4.25
4
""" The program displays student data as a bar graph """ import matplotlib.pyplot as plt # Initialize a dictionary to store the grade and the corresponding number of students with that grade studentData = {'A':20, 'B':30, 'C':10, 'D':5, 'E':8, 'F':2} # add a title, x-axis label and y-axis label plt.title('Grades Bar Plot for Biology Class') plt.xlabel('Grade') plt.ylabel('Num Students') # Plot the bar chart with our dataset and customize the color command plt.bar(list(studentData.keys()), list(studentData.values()), color=['green', 'gray', 'gray', 'gray', 'gray', 'red']) # Display the graph plt.show() # Plot the horizontal bar chart with our dataset and customize the color command plt.barh(list(studentData.keys()), list(studentData.values()), color=['green', 'gray', 'gray', 'gray', 'gray', 'red']) # Display the graph plt.show()
true
d1f785d25793f2c6ec00fa22b9e0420d5bf9c1c2
Eugene0469/The-Python_Workshop
/3. Programs, Algorithms, and Functions/binary-search.py
1,122
4.125
4
""" The Binary Search Algorithm It takes a SORTED array and finds the position of the target value. """ # Initialize an unsorted list l = [4,1,2,7,3,6,9,0] # Print out unsorted list print("Unsorted list:",l) # Use the bubble sort algorithm to sort the list isSorted = True while isSorted: isSorted = False for i in range(len(l)-1): if l[i] > l[i+1]: l[i], l[i+1] = l[i+1], l[i] isSorted = True # Print out sorted list print("Sorted list:",l) # Request user to search for the index of any item in the list searchFor = int(input("Enter number from list to search for its index: ")) # Use the binary search algorithm to search for the number sliceStart = 0 sliceEnd = len(l) - 1 isFound = False while sliceStart <= sliceEnd and not isFound: location = (sliceStart + sliceEnd) // 2 if l[location] == searchFor: isFound = True else: if l[location] < searchFor: sliceStart = location + 1 else: sliceEnd = location -1 # Print out the index of the number print("Index of {} is: {}".format(searchFor, location))
true
0c1aea99c5852f51035c9e34ce17a4c4ae30ef84
Eugene0469/The-Python_Workshop
/3. Programs, Algorithms, and Functions/fibonacci.py
1,434
4.53125
5
""" The program computes the elements of the Fibonacci sequence """ ''' @brief: Function computes elements of a fibonacci sequence @param: n: the number term in the sequence that we want to return @retVal: result: the number of position n in the fibonacci sequence ''' def fibonacciIterative(n): previous = 0 current = 1 for i in range(n-1): current_old = current previous, current = current_old , current + previous return current ''' @brief: Function computes elements of a fibonacci sequence @param: n: the number term in the sequence that we want to return @retVal: result: the number of position n in the fibonacci sequence ''' def fibonacciRecursive(n): if n == 0 or n == 1: return n else: return fibonacciRecursive(n-2) + fibonacciRecursive(n-1) # Declare a dictionary to store the fibonacci series vales and set hte first 2 terms of the Fibonacci sequence storedValues = {0:0,1:1} ''' @brief: Function computes elements of a fibonacci sequence @param: n: the number term in the sequence that we want to return @retVal: result: the number of position n in the fibonacci sequence ''' def fibonacciDynamic(n): # Check to see if the value is already stored in the dictionary if n in storedValues: return storedValues[n] else: storedValues[n] = fibonacciRecursive(n-2) + fibonacciRecursive(n-1) return storedValues[n]
true
a41534cece274f29975de64423f9a0c00ea0633b
Eugene0469/The-Python_Workshop
/3. Programs, Algorithms, and Functions/variableScope.py
2,140
4.4375
4
""" Variable Scope Global keyword tells Python to use the existing globally defined variable, where the default behaviour would be to define it locally in the function: score = 0 def myFunc(newScore): score = newScore myFunc(100) print(score) The result will be 0. score = 0 def myFunc(newScore): global score = newScore myFunc(100) print(score) The result will be 100. Nonlocal keyword is similar to the global keyword but it does not go straight to the global definition but first looks at the closest enclosing scope, i.e., it will look one level up in the code: score = 0 def myFunc(): score = 3 def inner(): nonlocal score print(score) inner() myFunc() The result will be 3 Lambda Functions are small, anonymous functions that can be define in a simple one-line syntax: lambda arguments : expression For example: def add_up(x,y): return x + y can be re-written as: add_up = lambda x,y : x + y the function is then called as follows: print(add_up(2,3) The result is 5 Lambda functions can only contain a single statement """ # Global keyword print("*"*20,"Global Keyword", "*"*20) score = 0 print("Initial value for global variable score:",score) def updateScore(newScore): score = newScore updateScore(100) print("Value of score WITHOUT using the global keyword:",score) def updateScoreGlobal(newScore): global score score = newScore updateScoreGlobal(100) print("Value of score USING the global keyword:",score) #Nonlocal keyword print("\n"+"*"*20,"Nonlocal Keyword","*"*20) x = 5 print("Value of global variable x:", x) def myFunc(): x = 3 print("Value of local variable x:",x) def inner(): nonlocal x print("Value of nonlocal variable x:",x) inner() myFunc() #Lambda Function print("\n"+"*"*20, "Lambda Functions","*"*20) # Create a lambda function first_item = lambda my_list: my_list[0] # Initialize a list pet = ['cat', 'dog', 'mouse'] # Call the function print("lambda argument: expression = ", first_item(pet))
true
9249106ad4e731a7874de7e6d8fca247c1c19cf2
Ajay-Raj-S/problem-solving
/Python/caesar-cipher.py
1,898
4.46875
4
# From: Python Programming: An Introduction to Computer Science # Written by: John Zelle # A caesar cipher is a simple substitution cipher based on the idea of # shifting each letter of the plaintext message a fixed number # (called the key) of positions in the alphabet. # For example, if the key value is 2, the word "Sourpuss" would be # Encoded as "Uqwtrwuu". The original message can be recovered # by "reencoding" it using the negative of the key. # Write a program to encode and decode Caesar ciphers, being sure # to deal with long keys in a circular fashion. The input will only be # letters and spaces. # ANSWER BELOW: from string import ascii_lowercase, ascii_uppercase def ccipher(string, key): # Shifts in a circular fashion new = "" for ch in string: if ch in ascii_lowercase: add = ascii_lowercase.index(ch) if add + key > 25: new += ascii_lowercase[add+key-24] else: new += ascii_lowercase[add+key] elif ch in ascii_uppercase: add = ascii_uppercase.index(ch) if add + key > 25: new += ascii_uppercase[add+key-24] else: new += ascii_uppercase[add+key] else: new += ch return new def ccipherAnsCirc(string, key): chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz" new = "" for ch in string: pos = chars.find(ch) # Use remainder division to take care of circular shift newpos = (pos + key) % len(chars) cipher = cipher + chars[newpos] def main(): print("This program will cipher your message.") string = input("Please enter a short text to encode: ") key = int(input("Please enter the key to shift letters: ")) print("The cipher of your text is: {0}".format(ccipher(string, key))) if __name__ == "__main__": main()
true
23950c09459e355dfd8602e251d793796da14de9
mketiku/python-tutorials
/src/codeacademy/alphabet.py
503
4.3125
4
VOWELS = ("a" , "e" , "i" , "o", "u") msg = raw_input("Enter your message: ") #var for holding user message msg.replace (" ", "") vowel_msg = "" vowel_count = 0 #new var to hold result of program con_msg = "" con_count = 0 #var to hold cons for letter in msg: if letter not in VOWELS: con_msg += letter con_count += 1 elif letter in VOWELS: vowel_msg += letter vowel_count += 1 print(str(vowel_count) "Vowels in input: " ,vowel_msg) print (str(con_count) "con in Input: " , con_msg)
false
8da095f7263addc7c5243c079cc2606ba56836c0
mketiku/python-tutorials
/src/codeacademy/2dim_tic_tac.py
559
4.25
4
# Purpose: Example: a 2D list tictactoe = [[1,2,3], [4,5,6], [7,8,9]] print (tictactoe[0]) print (tictactoe[1]) print (tictactoe[2]) print() row = 1 column = 0 print ("row " + str(row) + " column " + str(column) + " has value") print (tictactoe[row][column]) row = 2 column = 2 print ("row " + str(row) + " column " + str(column) + " has value") print (tictactoe[row][column]) print() print() tictactoe[2][2] = 0 print ("After changing the value at row 2 and column 2 to 0: ") print() print (tictactoe[0]) print (tictactoe[1]) print (tictactoe[2])
false
2487bb7dbd4608a315cffe491eaf073c31eafb58
wrishel/HETP_Scan_control
/z_examples_to_keep/python_timer/python_timer.py
1,298
4.1875
4
"""Show a self-repeating thrading.time that can be canceled externally.""" """Notes: Return value from hello has no imact on running. Thread does not autorepeat. Here a new thread is created for each iteration of hello(). Timer thread will run even while the main has the processor tied up. """ import threading, time global timer_thread global start start = time.time() # returnTF = True def elapsed(): return time.time() - start def tie_up_processor(secs): occupy_processor_time = time.time() + secs while time.time() < occupy_processor_time: ... def hello(): global timer_thread print(f"hello, world {elapsed():5.2f}") timer_thread = threading.Timer(1.0, hello) timer_thread.start() # return returnTF # print(returnTF) timer_thread = threading.Timer(1.0, hello) timer_thread.start() # after 1 sec, "hello, world" will be printed tie_up_processor(10) for x in range(10): time.sleep(.44) print(f'I woke up {elapsed():5.2f}') timer_thread.cancel() # returnTF = False # print(returnTF) timer_thread = threading.Timer(1.0, hello) timer_thread.start() # after 1 sec, "hello, world" will be printed for x in range(10): time.sleep(.44) print(f'I woke up {elapsed():5.2f}') timer_thread.cancel()
true
a7a1cc81215f79e3b9801502c45c73248a0b8655
emaillalkrishna/23May2019_list_problems1
/tests/myfile7.py
1,486
4.40625
4
# # Python program to find sum of elements in list # total = 0 # # # creating a list # list1 = [11, 5, 17, 18, 23] # # # Iterate each element in list and add them in variale total # for ele in range(0, len(list1)): # total = total + list1[ele] # # # printing total value # print("Sum of all elements in given list: ", total) # ---------------------------------------------- # # Python program to find sum of elements in list # total = 0 # ele = 0 # # # creating a list # list1 = [11, 5, 17, 18, 23] # # # Iterate each element in list and add them in variale total # while (ele < len(list1)): # total = total + list1[ele] # ele += 1 # # # printing total value # print("Sum of all elements in given list: ", total) # ---------------------------------------------- # # Python program to find sum of all elements in list using recursion # # # creating a list # list1 = [11, 5, 17, 18, 23] # # # # creating sum_list function # def sumOfList(list, size): # # # if (size == 0): # return 0 # else: # return list[size - 1] + sumOfList(list, size - 1) # # # Driver code # total = sumOfList(list1, len(list1)) # # print("Sum of all elements in given list: ", total) # ----------------------------------------------------- # Python program to find sum of elements in list # # creating a list # list1 = [11, 5, 17, 18, 23] # # # using sum() function # total = sum(list1) # # # printing total value # print("Sum of all elements in given list: ", total)
true
9467bc6b267ce2a599e8c75babaa8c6f03470f98
Sachitanand-parida/sherlock-and-squares
/gem-stones.py
672
4.40625
4
#!/usr/bin/env python """ Counts the number of elements that appear in all given rocks. https://www.hackerrank.com/challenges/gem-stones """ def count_gem_elements(rocks): """Finds the number of 'gem elements' in the given rocks.""" # Remove duplicate elements by treating the elements in each rock as a set. # Finding the intersection of these sets gives us elements in all rocks. element_sets = [set(rock) for rock in rocks] gem_elements = set.intersection(*element_sets) return len(gem_elements) if __name__ == '__main__': rock_count = int(input()) rocks = (input() for _ in range(rock_count)) print(count_gem_elements(rocks))
true
d416ddfa71335a1a03989bf0145640f3a8ebe3e8
Sachitanand-parida/sherlock-and-squares
/lonely-integer.py
638
4.1875
4
#!/usr/bin/env python """ Finds the only number in a list of numbers that isn't a pair. To do this efficiently we use the property that x ^ x = 0. XORing all numbers cancels out identical numbers and leaves us with the one we're after. https://www.hackerrank.com/challenges/lonely-integer """ from functools import reduce def find_lonely_integer(numbers): """Finds the number that has no twin.""" lonely_integer = reduce(lambda x, y: x ^ y, numbers) return lonely_integer if __name__ == '__main__': number_count = int(input()) numbers = (int(x) for x in input().split()) print(find_lonely_integer(numbers))
true
ea08be3aacea9ed4cc1ea274b6603a6375508c87
tapreaniket08/python-coding-question
/String_anagram.py
347
4.15625
4
str1=str(input("Enter frist String")) str2=str(input("Enter Second String")) str1=str1.lower() str2= str2.lower() if len(str1)==len(str2): sor_str1=sorted(str1) sor_str2=sorted(str2) if sor_str1==sor_str2: print ("String is anagram") else: print("Strng is not anagram") else: print("String is not anagram")
true
943de42f208d5038474ffe47838de36a3d4be130
xwzl/python
/python/src/com/python/learn/func/ClosureOperate.py
2,376
4.125
4
# 闭包,又称闭包函数或者闭合函数,其实和前面讲的嵌套函数类似,不同之处在于,闭包中外部函数返回的不是一个具体的值,而是一个函数。一般情 # 况下,返回的函数会赋值给一个变量,这个变量可以在后面被继续执行调用。 print(2 ** 3) # 闭包函数,其中 exponent 称为自由变量 def nth_power(exponent): def exponent_of(base): return base ** exponent return exponent_of # 返回值是 exponent_of 函数 square = nth_power(2) # 计算一个数的平方 cube = nth_power(3) # 计算一个数的立方 print(square(2)) # 计算 2 的平方 print(cube(2)) # 计算 2 的立方 # 看到这里,读者可能会问,为什么要闭包呢?上面的程序,完全可以写成下面的形式: def nth_power_rewrite(base, exponent): return base ** exponent # 上面程序确实可以实现相同的功能,不过使用闭包,可以让程序变得更简洁易读。设想一下,比如需要计算很多个数的平方,那么读者觉得写成下面哪一种形式更好呢? # 不使用闭包 res1 = nth_power_rewrite(1, 2) res2 = nth_power_rewrite(2, 2) res3 = nth_power_rewrite(3, 2) print(res1) print(res2) print(res3) # 使用闭包 # 其次,和缩减嵌套函数的优点类似,函数开头需要做一些额外工作,当需要多次调用该函数时,如果将那些额外工作的代码放在外部函数,就可以减少多次调用导致的不必要开销,提高程序的运行效率。 square = nth_power(2) res1 = square(1) res2 = square(2) res3 = square(3) print(res1) print(res2) print(res3) # 闭包类似于偏向函数 def hello_people(ketty): def inner(tiger): return tiger, ketty return inner # Python闭包的__closure__属性 # # 闭包比普通的函数多了一个 __closure__ 属性,该属性记录着自由变量的地址。当闭包被调用时,系统就会根据该地址找到对应的自由变量,完成整体的函数调用。 # # 以 nth_power() 为例,当其被调用时,可以通过 __closure__ 属性获取自由变量(也就是程序中的 exponent 参数)存储的地址 square = nth_power(2) # 查看 __closure__ 的值 print(square.__closure__) people = hello_people("people") # baby baby, babies = people("baby") print(baby, babies) print(people.__closure__)
false
d081eba65fda128c64bac3728b5888d8f5786235
wingedrasengan927/Python-tutorials
/Object Oriented Programming/1. Classes and Instances.py
1,819
4.5625
5
# Object Oriented Programming # Classes # They allow us to logically group our data and functions in a way that's # easy to reuse and also easy to build upon if need be # Method: A function that is associated with a class # A class is like a blueprint for creating instances # instance variables contain attributes that is unique to each instance # An object is an instance of the class # let's create an employee class # __init__ method is like 'to initialize' # the 'self' is the instance. It's the default argument whenever you create a method inside a class # other arguments can be accepted after self # the attributes name need not be same as the arguments name # let's create a method in the class which gives the full name # each method in the class automatically takes instance as the first argument class employee: def __init__(self, firstname="", lastname="", pay=0): self.firstname = firstname self.lastname = lastname self.pay = pay self.email = firstname + "." + lastname + "@company.com" def fullname(self): return "{} {}".format(self.firstname, self.lastname) # the instance is passed automatically as an argument emp_1 = employee(firstname="Neeraj", lastname="Krishna", pay=170000) print(emp_1.email) # the instance will be passed automatically as an argument in the method print(emp_1.fullname()) # we can also run these methods using the class itself # but when we run it from a class, we have to pass the instance as an argument # when we call method off an instance, it automatically passes the instance as an argument # but when we call the method off a class, we need to pass the instance as the argument # in the background, when we call emp_1.fullname(), it get's transformed to employee.fullname(emp_1) print(employee.fullname(emp_1))
true