blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
73222fc551ad1aeff7a88c10ea925fd0004f8b53
sanjbaby/ammu
/code/Leesa_code/if.py
390
4.1875
4
import turtle t = turtle.Pen() number = int(turtle.numinput("number of sides or circles","how many sides or circles")) shape = turtle.textinput("which shape do you want","enter 'p'for polygon or 'r' for rosette") for x in range (number): if shape == 'r': t.circle(100) t.left(360/number) t.speed(0) else: t.forward (150) t.left (360/number)
true
e7259f50a6da8cb10a3e2f7ecf75487136525eb8
jmetzz/ml-laboratory
/basic_ml/notebooks/numpy/indexing_and_slicing.py
1,221
4.40625
4
import numpy as np # Regular python list: To return the (0,1) element we must index as shown below. print("With regular array") alist = [[1, 2], [3, 4]] alist[0][1] print(alist) # With Numpy # If we want to return the right-hand column, there is no trivial way # to do so with Python lists. In NumPy, indexing follows a # more convenient syntax. # Converting the list defined above into an array print("==================================") print("With Numpy:") arr = np.array(alist) print(arr) print(arr[0, 1]) # Access and element on line 0 and column 1 print(arr[:, 1]) # Now to access the last column print(arr[1, :]) # Accessing the lines is achieved in the same way. print("------------------------") # Slicing # Creating an array arr = np.arange(5) print(arr) # Creating the index array index = np.where(arr > 2) print(index) # Creating the desired array print("------------------------") new_arr = arr[index] print(new_arr) # We can also remove specific elements based on the conditional index new_arr = np.delete(arr, index) print(new_arr) print("------------------------") # or we can use a boolean array index = arr > 2 print(index) # [False False True True True] new_arr = arr[index] print(new_arr)
true
69a5900480e5de054c5c092a4c6c4bb05162495d
MrNullPointer/Python-Basics
/PythonApplication1.py
971
4.15625
4
#iteration = 0 #while iteration < 5: # for i in "hello": # if iteration%2 == 0: # break # iteration += 1 #******Find the cube root using guesses****# #cube = int (input("Please enter a number to find the cube root!!: ")) #guess = 0.0 #increment = 0.0001 #guessNumber = 0 #proximity = 0.001 #while abs(cube - guess**3) > proximity: # guess += increment # guessNumber += 1 #print("The number guessed is :", str(guess)) #if abs(guess**3 - cube) >= proximity: # print("Failed!!", "Number of iterations are: ", str(guessNumber)) #else: print ("The cube root of", str(cube), "is close to:", str(guess)) #******Find the square root using guesses****# x = 25 epsilon = 0.01 step = 0.1 guess = 0.0 while guess <= x: if abs(guess**2 -x) < epsilon: break else: guess += step if abs(guess**2 - x) >= epsilon: print('failed') else: print('succeeded: ' + str(guess))
true
abf369255ae775fbc01891ff3da00fcd94e8184f
CathleahTelib/Assignment-no.2
/money.py
305
4.1875
4
amount_of_money_you_have = int(input("How much is your money?:")) applePrice = int(input("How much is the apple:")) you_can_buy = amount_of_money_you_have // applePrice your_change_is = amount_of_money_you_have % applePrice print(f"You can buy {you_can_buy} apples and your change is {your_change_is}")
false
906ecedd23f9a5a685fded2536a41df05f53757a
angelineemi/python
/vowel.py
268
4.125
4
str1=str(input("Enter a letter: ")) if str1=="a": print("it's a vowel") elif str1=="e": print("it's a vowel") elif str1=="i": print("it's a vowel") elif str1=="o": print("it's a vowel") elif str1=="u": print("it's a vowel") else: print("it's not a vowel")
false
0c36072fc2b094120f85090aff35930d806cc08b
RahatGaba/PIAIC
/q16.py
381
4.125
4
#16.Write a Python program to compute the distance between the points (x1, y1) and (x2, y2). x1=int(input("Enter the value of x1: ")) x2=int(input("Enter the value of x2: ")) y1=int(input("Enter the value of y1: ")) y2=int(input("Enter the value of y2: ")) ans=((x2-x1)*(x2-x1))+((y2-y1)*(y2-y1)) sqrt = ans ** 0.5 print("Distance between these two points is : "+str(sqrt))
true
e8762ee4ce94b20212bbc7a3c46f8575e39ef613
RahatGaba/PIAIC
/q2.py
246
4.28125
4
# Write a Python program to check if a number is positive, negative or zero i=int(input("Enter any number: ")) if i==0: print("You entered Zero") elif i>0: print(str(i)+" is Positive") elif i<0: print(str(i)+" is Negative")
true
44a461d27ec9406bd930606494647022a8893524
Yashika1305/PythonPrograms
/prog13.py
332
4.1875
4
temp=float(input("Enter Temperature in Celsius")) if temp<0: print("Freezing weather") elif temp>0 and temp<=10: print("Very Cold weather") elif temp>10 and temp<=20: print("Cold weather") elif temp>20 and temp<=30: print("Normal in Temp") elif temp>30 and temp<=40: print("Its Hot") else: print("Its Very Hot")
true
8ebd4fa713ae109a0a3ac7b67f242e5283e41860
mayur1101/Mangesh
/Python_Day1/Q4.py
297
4.15625
4
''' Write a program to check wheather number is even or odd using if Else statement… ''' def EvenOdd(number): if number%2==0: print(str(number)+" "+"is even") else: print(str(number)+" "+"is odd") number=int(input("Enter the number you want to check:")) EvenOdd(number)
true
2a991de645e530df3c724287edebd3a636b5a068
mayur1101/Mangesh
/Python_class/inner_class.py
748
4.65625
5
#without existing outer class object there is no chance of #existing of inner class object #So if you want to call inner class object method we need # to create outer class object and using that object we can #create inner class object. Then using that object reference # we can call inner class object methods. # Examples of inner class #e.g Braine without person is not possible # e.g engine without car is not possible class Outer: def __init__(self): print("Outer class object creation") class Inner: def __init__(self): print("inner class object creation") def m1(self): print("Inner class method") o=Outer() i=o.Inner() i.m1()
true
dc3fb1d5e12b23dab2e461a7c69a808abdb7b929
mayur1101/Mangesh
/Python_Day5/Q2.py
389
4.21875
4
''' 2. Write a Python program for sequential search (Linear search). ''' def Sequential_search(List, key): for i in range(0,len(List)): if key == List[i]: return f"{key} is found at index {i}" return -1 List=list(map(int,input("Enter list elements:").strip().split())) key=int(input("Enter the element you want to search:")) print(Sequential_search(List,key))
true
92f3d890d832e39aa1e73e322e99a68f3f45a2ea
mayur1101/Mangesh
/Python_Day6/Q3.py
680
4.25
4
''' 3. Write program to implement Insertion sort. ''' List=[5,4,10,1,6,2] for i in range(0,len(List)): temp=List[i] j=i-1 while(j>=0 and List[j]>temp): List[j+1]=List[j] j-=1 List[j+1]=temp print(List) ''' def insertion_sort(A): for i in range(1,len(A)): for j in range(i-1,-1,-1): if A[j]> A[j+1]: A[j],A[j+1] = A[j+1],A[j] else: break A=list(map(int,input("Enter List elements:").strip().split())) print(A) insertion_sort(A) print("List after sorting:",A) '''
true
186a8544bf0a3ffe9240c682d76a80b4920ded59
mayur1101/Mangesh
/Python_Day4/Q1.py
378
4.34375
4
'''1. Write a function to find max of three numbers.''' def max_numbers(a,b,c): if a>= b and a>=c: max=a elif b>=a and b>=c: max=b else: max=c return max # a=int(input("Enter a:")) # b=int(input("Enter b:")) # c=int(input("Enter c:")) a,b,c=input("Enter a,b,c values:").strip().split() print("Max of three Numbers:",max_numbers(a,b,c))
true
a6da5dbfe836943292b6d2e110921d40a96d3b7a
tejas11/pythonprojects
/firstxfibonacci.py
295
4.21875
4
print("Enter a number, and we will give you that many numbers of the fibonacci number sequence!") y = int(input("Enter a number:")) x = 2 a = 0 b = 0 if x <= 2: a = 1 b = 1 print(a) print(b) x = x + 1 while y >= x: c = a +b a = b b = c print(c) x = x + 1
true
085e49c00aaa8f35a29aaa9cc2be8029c116431f
b0ng0c4t/python-learning
/20201123.py
2,362
4.46875
4
#Assign a different name to function and call it through the new name print('EXERCISE 1') def displayStudent(name, age): print(name, age) displayStudent('Emma', 26) showStudent = displayStudent showStudent('Lucas', 15) print('\n') #Generate a Python list of all the even numbers between 4 to 30 print('EXERCISE 2') print(list(range(4,30,2))) print('\n') #Return the largest item from the given list print('EXERCISE 3') aList = [4, 6, 8, 245, 244, 22] print(max(aList)) print('\n') #Given a two list. Create a third list by picking an odd-index # element from the first list and even index elements from second. print('EXERCISE 4') listOne = [3, 6, 9, 12, 15, 18, 21] listTwo = [4, 8, 12, 16, 20, 24, 28] listThree = list() oddElements = listOne[1::2] print('Element at odd-index positions from list one') print(oddElements) EvenElements = listTwo[0::2] print('Element at even-index positions from list two') print(EvenElements) print('Printing Final third list') listThree.extend(oddElements) listThree.extend(EvenElements) print(listThree) print('\n') #Given an input list removes the element at index 4 and add # it to the 2nd position and also, at the end of the list print('EXERCISE 5') sampleList = [34,54,67,89,11,43,94] print('Original list:', sampleList) element = sampleList.pop(4) print("List After removing element at index 4 ", sampleList) sampleList.insert(2,element) print('List after adding element at index 2 ', sampleList) sampleList.append(element) print("List after adding element at last ", sampleList) print('\n') #Given a two list of equal size create a set such that it shows the element from # both lists in the pair print("EXERCISE 6") firstList = [2,3,4,5,6,7,8] print('First List:', firstList) secondList = [4,9,16,25,36,49,64] print('Second List:', secondList) result = zip(firstList, secondList) resultSet = set(result) print(resultSet) print('\n') #Given a following two sets find the intersection and remove those # elements from the first set print('EXERCISE 7') firstSet = {23,42,65,57,78,83,29,13} secondSet = {57,83,29,67,73,43,48,14} print('first set:', firstSet) print('Second set;', secondSet) intersection = firstSet.intersection(secondSet) print('Intersection is ', intersection) for item in intersection: firstSet.remove(item) print('First set after removing common element;', firstSet) print('\n')
true
0294550741fa060314eff9eb84c1748069871f5c
ChauKhanh134/khanh134
/wordshop1.2.3.5-master/wordshop3/Exercise_01-05_page_70/Exercise_02.py
330
4.125
4
""" Author: Tran Chau Khanh Date: 02/09/2021 Program: Exercise_01-05_page_70.py Problem: Write a loop that prints your name 100 times. Each output should begin on a new line. Solution: Display: Pom(1) ... ... Pom(100) """ name = "Pom" for i in range(100): print(name, "(" + str(i + 1) + ")")
true
114a1d4186a9bf2655ddf8b40b333429fd42e22f
ChauKhanh134/khanh134
/wordshop1.2.3.5-master/wordshop1/project/Project_05_page33.py
566
4.3125
4
""" Author: Tran Chau Khanh Date: 02/09/2021 Program: Project_05_page33.py Problem: Modify the program of Project 4 to compute the area of a triangle. Issue the appropriate prompts for the triangle’s base and height, and change the names of the variables appropriately. Then, use the formula .5 * base * height to compute the area. Test the program from an IDLE window. Solution: """ base = int(input("Enter with base = ")) height = int(input("Enter with height = ")) area = 5 * base * height print("This is area", area, "triangle units.")
true
56e642ce7740fbdf650810916d3e973b0ae6aff5
ChauKhanh134/khanh134
/wordshop1.2.3.5-master/wordshop5/Exercise_1-8_page_145/Exercise_3.py
443
4.1875
4
""" Author: Tran Chau Khanh Date: 05/09/2021 Program: Exercise_03.py Problem: What is a mutator method? Explain why mutator methods usually return the value None Solution: Mutator method usually returns no value of interest to the caller.” In python the Nonevalue is returned. ... This method does not have a return value. This is because “a change of state” is what is needed. However, in python it automatically returns “None. """
true
6b10393848bdf901dcbccb2f05028e3701bca73e
ChauKhanh134/khanh134
/wordshop1.2.3.5-master/wordshop2/Project_01_10_page62-63/Project_04.py
772
4.4375
4
""" Author: Tran Chau Khanh Date: 02/09/2021 Program: project_04_page_62.py Problem: Write a program that takes the radius of a sphere (a floating-point number) as input and then outputs the sphere’s diameter, circumference, surface area, and volume. Solution: Display result: Radius = 7 Diameter: 14.0 Circumference: 43.982297150257104 Surface area : 615.7521601035994 Volume : 1436.7550402417319 """ import math radius = float(input("Radius = ")) diameter = radius * 2 circumference = diameter * math.pi surfaceArea = math.pi * pow(diameter, 2) volume = 4/3 * math.pi * pow(radius, 3) print("Diameter: ", diameter) print("Circumference: ", circumference) print("Surface area : ", surfaceArea) print("Volume : ", volume)
true
c37ee06ddf68efca09d7b7697e7bca6ee3d957f8
Ylwoi/exam-basics
/oddavg/odd_avg.py
524
4.1875
4
# Create a function called `odd_average` that takes a list of numbers as parameter # and returns the average value of the odd numbers in the list # Create basic unit tests for it with at least 3 different test cases def odd_average(list_of_numbers): try: odd_counter = 0 odd_sum = 0 for number in list_of_numbers: if number % 2 != 0: odd_counter += 1 odd_sum += number return odd_sum/odd_counter except ZeroDivisionError: return 0
true
3aa076b31f57ccaa047ed1ec906725bb5dd14a27
andreshugueth/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
607
4.25
4
#!/usr/bin/python3 """Function that insert a line to a file""" def append_after(filename="", search_string="", new_string=""): """appends after a line Keyword Arguments: filename {str} -- name of the file (default: {""}) search_string {str} -- searched string (default: {""}) new_string {str} -- new string (default: {""}) """ text = "" with open(filename, encoding='utf-8') as f: for line in f: text += line if search_string in line: text += new_string with open(filename, 'w') as f: f.write(text)
true
c3dc3f963fd201fd5a9ba196f17884b1a7b5e18c
andreshugueth/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
580
4.1875
4
#!/usr/bin/python3 """add_integer""" def add_integer(a, b=98): """Represent addition Arguments: a {[int]} -- [First argument] Keyword Arguments: b {int} -- [Second argument] (default: {98}) Raises: TypeError: [a must be an integer] TypeError: [b must be an integer] Returns: [int] -- [two numbers addition] """ if type(a) not in [int, float]: raise TypeError("a must be an integer") elif type(b) not in [int, float]: raise TypeError("b must be an integer") return (int(a) + int(b))
true
16b435e8ebc4be2891db24e23d7b6a82195794bf
green-fox-academy/tszabad
/week-03/day-1/swap_elements.py
272
4.40625
4
# - Create a variable named `orders` # with the following content: `["first", "second", "third"]` # - Swap the first and the third element of `orders` orders = ["first", "second", "third"] orders[0], orders[2] = orders[2], orders[0] # orders.reverse() print(orders)
true
5370f929e0c6b30b641c9f58f27d4bcf32b8b711
green-fox-academy/tszabad
/week-04/day-2/rainbow_boxes.py
745
4.1875
4
from tkinter import * root = Tk() canvas = Canvas(root, width='300', height='300') canvas.pack() # Create a square drawing function that takes 2 parameters: # The square size, and the fill color, # and draws a square of that size and color to the center of the canvas. # Create a loop that fills the canvas with rainbow colored squares (red, orange, yellow, green, blue, indigo, violet). def rectangle(size, color="green"): x1 = 150-size/2 y1 = 150-size/2 x2 = 150+size/2 y2 = 150+size/2 rectangle = canvas.create_rectangle(x1, y1, x2, y2, fill=color, width ="2") colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"] for i in range(len(colors)): rectangle(150-(i*20),colors[i]) root.mainloop()
true
ce4c7126b554cd50e665c2ceea66b4cdcbebb0f1
green-fox-academy/tszabad
/week-02/day-02/cuboid.py
512
4.34375
4
# Write a program that stores 3 sides of a cuboid as variables (float) # The program should write the surface area and volume of the cuboid like: # # Surface Area: 600 # Volume: 1000 print("Welcome to my cuboid calculator!") print("Please enter the length:") l = float(input()) print("Please enter the second width:") w = float(input()) print("Please enter the first height:") h = float(input()) area = 2*l*w+2*l*h+2*h*w volume = l * w * h print("Surface Area: " + str(area) + "\n" + "Volume: "+ str(volume))
true
73075af5e4cbbaa8baac997d05f604f169133dcc
green-fox-academy/tszabad
/week-02/day-02/draw_diamond.py
442
4.125
4
# Write a program that reads a number from the standard input, then draws a # diamond like this: # # # * # *** # ***** # ******* # ***** # *** # * # # The diamond should have as many lines as the number was num1 = int(input("Please enter a number: ")) star = "*" space = " " for i in range(1, num1, 2): print(space * ((num1)//2-(i//2)) + star*i) for i in range(1, num1, 2): print(space * ((i//2)+1) + star*((num1)-(i)))
true
4b47f5201fe0cada1df873715fa18acab2d21e53
Daniellau331/AutomateTheBoringStuff
/Codes/mapit/mapit.py
1,021
4.21875
4
#! python3 # mapit.py - Launches a map in he browser using an address from the command line or cllipboard. # if there is no command line arguments, then the program will know to use the contents of # the clipboard. import webbrowser, sys, pyperclip if len(sys.argv)>1: # Get address from command line arguments. sys.argv stores a list of program's filename and command line arguments. # len(sys.argv)>1 means the user enters command line arguments # sys.argv[1:] chop off the first element of the array. # if you enter this into the command line # mapit 870 Valencia St, San Francisco, CA 94110 # the sys.argv variable will contain this list value: # ['mapit.py', '870', 'Valencia','St,','San','Francisco','CA','94110'] address = ' '.join(sys.argv[1:]) else: # Get address from clipboard if there is no command line arguments. address = pyperclip.paste() # launch the browser with the Google map URL, call webbrowser.open() webbrowser.open('https://www.google.com/maps/place/'+address)
true
84c5345c0cdc0d8bff694119407256d1ae016a49
melona2020/pythonproject
/main.py
723
4.15625
4
Calculation_to_units = 24*60 name_of_unit = "Minutes" def days_to_unit(num_of_days): return f"{num_of_days} days are {num_of_days * Calculation_to_units} {name_of_unit}" def validate_and_execute(): if user_input.isdigit(): user_input_number = int(user_input) if user_input_number > 0: calculated_value = days_to_unit(user_input_number) print(calculated_value) elif user_input_number == 0: print("you entered 0 please enter a positive number") else: print("User input is invalid Please try again with integer value") user_input = input("Hey User, Please enter number of days? I will calculate how many Minutes!\n") validate_and_execute()
true
25c1302382a2b8e6f8bfec62cf7503c2ab30d528
Primary-Aaron/cs340-HW3
/main-ish.py
487
4.46875
4
print("Hey there. I haven't used Python before, so bare with me.\n I declare the current year as a variable and then mod it to see if it's a leap year or not. the variable leapyear will keep track of it") leapyear = "false"; currentyear = 2021; if currentyear%400 == 0: leapyear = "true"; elif currentyear%100 == 0: leapyear = "false" elif currentyear%4 == 0: leapyear = "true"; print("the statement: this year is currently a leap year holds..."); print(leapyear);
true
22fdc9b131dcaabd4dafc8c35a75fd31ec064a3e
pythoneasyway/python-class
/class6.py
2,985
4.3125
4
#!/usr/bin/python #: Title : class6.py #: Date : #: Author : pythoneasyway@gmail.com #: Description : Class number 6 #: - loops: for and while #: - breaking loops: brake #: - lists functions: append(), remove(), sort() #: Version : 1.0 for i in range(1,10): print "John ", i # my current weight and height my_weight = 53 my_height = 127 # using for to calculate "possible" weight :) for i in range(9,35): my_weight = my_weight + 2.5 print "my weight when i am ", i, " is going to be", my_weight, "pounds" # using for to calculate "possible" height :) for i in range(9,21): my_height = my_height + 5 print "my height when i am ", i, " i am going to be", my_height/30.48, " feet tall" # create a list called ingredients, which contains the items needed for a party ingredients = ["pizza", "balloons", "cake", "people", "electronics", "chips", "goodie bags"] # printing the items for f in ingredients: print "for my party I need",f # append() add items to a list ingredients.append("confetti") ingredients.append("food") ingredients.append("books") # prints an empty line print for i in ingredients: print "my updated ingredients for the party are", i # remove() deletes the given item from the list ingredients.remove("books") print for i in ingredients: print "my last ingredients for the party are", i # sort() sort the list, in this case alphabetically ingredients.sort() print for i in ingredients: print "my sorted ingredients for the party are", i # create a list contries countries = ["USA","India" ,"Turkey", "Canada", "Belgium", "Costa Rica", "England", "Austria", "Czech Republic"] # sort the countries countries.sort() print for i in countries: print "I have been in these countries", i # adding a new country countries.append("Switzerland") # reverse () reverse the order of the items :) countries.reverse() print "My reverse list is " for i in countries: print "I have been in these countries", i ######################### # MY FIRST GUESSING GAME ######################### print print "MY FIRST GUESSING GAME" import random as r # generates a random number between 1 and 999 number = r.randint(1,1000) # generates a random number between 1 and 10 ticket = r.randint(1,11) n = 0 # A while loop statement in Python programming language repeatedly # executes a statement as long as a given condition is true. while True: # the string is transformed into integer right after is entered value = int(raw_input("enter a number between 1 and 1000=> ")) if value > number: print "number too big" elif value < number: print "number too small" else: print "number found, it was =>", number # when the number is found, we must # break the cycle in order to get out the loop!! break print "try number", n, "try again!" n = n + 1 if n < 6: print "YOU WIN A TICKET TO", countries[ticket] else: print "TO MANY TRIES, NO TICKET THIS TIME, YOU LOSEEEEE!!"
true
9b369f3fe96fc4154e61f17df0d38b16b6355de0
Louverdis/Curso-Qt-Python-Mongo
/Python/3_Clases.py
2,107
4.5
4
""" OOP: Definiendo clases en python """ class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' """ """ class Dog: def __init__(self, name): self.name = name self.tricks = [] # creates a new empty list for each dog def add_trick(self, trick): self.tricks.append(trick) """ Herencia """ class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N> """ Ejemplos de clases de uso real: Viejo estilo, usado principalmente en python 2 """ class Comando(object): """Tipo de dato usado para representar el llamado de comandos EscPos en el archivo .ticket Atributos: @nombre: STR, nombre del comando """ def __init__(self, nombre): self._nombre = nombre def __repr__(self, *args, **kwargs): return "Comando: "+self.nombre() def get_nombre(self): """Getter de nombre.""" return self._nombre def set_nombre(self, value): """Setter de nombre.""" return self._nombre = value """ Estilo Usual en python 3 """ class Texto: """Tipo de dato usado para representar la insersion de texto imprimible en el archivo .ticket Atributos: @texto: STR, texto a imprimirse @variable: STR, variable de python contenida en el modulo indicado en el archivo ticket. La variable debera ser un objeto STR o con una implementacion correcta de "__str__" o "__repr__" """ def __init__(self, texto, variable): self._texto = texto self._variable = variable def __str__(self, *args, **kwargs): return ( "Texto imprimible: "+ str(self.texto()) +"| variable: "+ str(self.variable()) ) @property def texto(self): return self._texto @texto.setter def texto(self, value): self._texto = value @property def variable(self): return self._variable @variable.setter def variable(self, value): self._variable = value """ """
false
83a28730bbb322c5c5fe8c033c71ef7697266d71
carlvin/pythonProject
/functions_exercise.py
205
4.125
4
def highest_even(my_list): highest_even=[] for value in my_list : if value % 2 == 0 : highest_even.append(value) return max(highest_even) print(highest_even([10,5,8,12,9,2]))
true
47635ca9848fea1ae769277dd1f7af57b2a66cf1
sajan4s/Python
/Functions/function_reverse_sentence.py
231
4.34375
4
# Function # Reverse the sentence def reverse_word(text): wordlist = text.split() reverse_word_list = wordlist[::-1] return ' '.join(reverse_word_list) print(reverse_word("This is a text that needs to be reversed"))
true
574bd69fb493d6d8dc0be953c754726000807e8a
anjaneyulup/Python
/BasicPrograms/CRUD_Dictionary.py
544
4.125
4
# CRUD on Dictonary #Creation of Dictonary dict = {'Name': 'Nilesh1','Name': 'Zara', 'Age': 7, 'Class': 'First','Name': 'Sachin1',} print(dict); print("Dictonary All items ", dict.items()) #Updatiopn dict['Name']="Rajat" dict['Age']=25 print("After updating",dict.items()) dict1 =dict.copy(); print("Copy of dict ", dict1) #Deleting del dict['Name']; print("After Deleting ",dict.items()) dict.clear(); # remove all entries in dict print("After clearing all value ",dict.items()) dict1 =dict.copy(); print("Copy of dict ", dict1)
false
09b5a8463a5e877e169c87142125b67aa2bb17ee
adhamkhater/Divide_Conquer_algorithm
/naive.py
1,777
4.4375
4
n= int(input("Enter the degree of the matrix: ")) while n <= 1: n= int(input("re-enter correct matrix size: ")) A=[] print("Enter the entries rowwise:") # For user input for i in range(n): # A for loop for row entries a =[] for j in range(n): # A for loop for column entries while(1): try: a.append(float(input("enter the values of the seccond matrix: "))) break except: print("enter a correct value") A.append(a) B=[] print("Enter the entries rowwise:") for i in range(n): # A for loop for row entries b =[] for j in range(n): # A for loop for column entries while(1): try: b.append(float(input("enter the values of the seccond matrix: "))) break except: print("enter a correct value") B.append(b) O= [ [0] * (len(A)) for i in range(len(A))] for i in range( len(A)): for j in range(len( B[0])): ## to be able to fill the correct entry in the new matrix O for k in range(len(B)): O[i][j] +=( A[i][k] * B[k][j]) ## swapped [k] and [j] to be able to access the columns in matrix B print('output list using the naive multiplication (brute force)', O) ############################################################################################################################################### ############################ Since it is 3 loops the Big O is N^3 because of the 3 for loops################################################### ###############################################################################################################################################
false
f1193d77391100d9514be2e460c7e360f6ca9bde
melwyn-rodrigues/Udacity-CS-101-Introduction-to-Computer-Science
/Lesson-2/quiz-practice-6-find_last.py
941
4.28125
4
# Define a procedure, find_last, that takes as input # two strings, a search string and a target string, # and returns the last position in the search string # where the target string appears, or -1 if there # are no occurrences. # # Example: find_last('aaaa', 'a') returns 3 # Make sure your procedure has a return statement. def find_last(x,y): pos= x.find(y) if pos==-1: return -1 else: while True: next_pos=x.find(y,pos+1) pos=pos+1 if next_pos==-1: return pos-1 print (find_last("aaaa", "a")) #>>> 3 print (find_last('aaaaa', 'aa')) #>>> 3 #print (find_last('aaaa', 'b')) #>>> -1 #print (find_last("111111111", "1")) #>>> 8 #print (find_last("222222222", "")) #>>> 9 #print (find_last("", "3")) #>>> -1 #print (find_last("", "")) #>>> 0
true
770da03c01609250e42afe685e56132b439eb3d4
SunnyMarkLiu/LeetCode
/201-300/232. Implement Queue using Stacks.py
1,224
4.28125
4
#!/home/sunnymarkliu/softwares/anaconda3/bin/python # _*_ coding: utf-8 _*_ """ @author: SunnyMarkLiu @time : 18-3-6 下午1:19 """ class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.stack = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: void """ self.stack.append(x) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ if self.empty(): return None pop_ret = self.stack[0] del self.stack[0] return pop_ret def peek(self): """ Get the front element. :rtype: int """ return self.stack[0] if not self.empty() else None def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return len(self.stack) == 0 # Your MyQueue object will be instantiated and called as such: obj = MyQueue() obj.push(1) obj.push(2) obj.push(3) obj.push(4) param_2 = obj.pop() print(obj.stack) param_3 = obj.peek() param_4 = obj.empty()
true
5bb7d11bf73090414d18ebd22134a547347aec5d
cristianegea/Digital-Innovation-One
/Introdução à Programação Python/Aula02.py
2,601
4.6875
5
# Aula 02 - Variáveis e Operadores Aritméticos # 1. Operadores Aritméticos a = 10 b = 5 # Operador de Soma (+) soma = a + b print(soma) # Operador de Subtração (-) subtracao = a - b print(subtracao) # Operador de Multiplicação (*) multiplicacao = a*b print(multiplicacao) # Operador de Divisão (/) divisao = a/b print(divisao) # Operador de Resto da Divisão (%) resto = a%b print(resto) # 2. Tipos de Variáveis # Variável do tipo inteiro inteiro = 4 print(type(inteiro)) # <class 'int'> # Variável do tipo float decimal = 4.5 print(type(decimal)) # <class 'float'> # Variável do tipo string texto = "variável" print(type(texto)) # <class 'str'> # 3. Conversão de Variáveis # Conversão de uma variável tipo inteiro em uma variável tipo string x1 = 45 print(type(x1)) # <class 'int'> x1 = str(x1) print(x1) print(type(x1)) # <class 'str'> # Conversão de uma variável tipo inteiro em uma variável tipo float x2 = 50 print(type(x2)) # <class 'int'> x2 = float(x2) print(x2) # x2 = 50.0 print(type(x2)) # <class 'float'> # Conversão de uma variável tipo float em uma variável tipo inteiro x3 = 55.4 print(type(x3)) # <class 'int'> x3 = int(x3) print(x3) # x2 = 55 => arrendondamento para cima print(type(x3)) # <class 'float'> # 4. Concatenação de variáveis tipo strings # Método clássico valor = 10 print(type(valor)) # <class 'int'> # obs.: não é possível concatenar variáveis de tipos diferentes. print('o valor é ' + str(valor)) # Output => o valor é 10 # Utilizando o comando ".format()" resultado1 = 100 print('o resultado é {}'.format(resultado1)) # Output => o resultado é 100 # Não é preciso converter o tipo da variável para fazer a concatenação resultado2 = 500 print('os resultados são {} e {}'.format(resultado1, resultado2)) # Output => os resultados são 100 e 500 print('os resultados são {r1} e {r2}'.format(r1 = resultado1, r2 = resultado2)) # Output => os resultados são 100 e 500 # 5. Interação com o usuário y1 = input('Entre com o primeiro valor:\n') # type(y1) = string print(type(y1)) y2 = input('Entre com o segundo valor: \n') # type(y2) = string print(type(y2)) # Obs.: "\n" => quebra de linha z1 = int(input('Entre com o primeiro valor:\n')) # type(z1) = inteiro print(type(z1)) z2 = int(input('Entre com o segundo valor: \n')) # type(z2) = inteiro print(type(z2)) z = z1 + z2 print(z)
false
4152a6994f6ef7881e87f2c139ef36b098ad6ab6
KrisAsante/Unit-4-02
/Unit 4-02.py
597
4.375
4
# Created by: Chris Asante # Created on: 28-March-2019 # Created for: ICS3U # Daily Assignment – Unit 4-02 # This is a program that rounds off decimals def calculate_decimal(number, decimal_points): answer = number * (10 ** decimal_points) answer_2 = answer + 0.5 answer_3 = int(answer_2) final_answer = answer_3 / (10 ** decimal_points) print (final_answer) user_number = float(input("Enter the decimal number: ")) user_decimal_points = int(input("Enter how many decimal points you want to round off to: ")) calculate_decimal(user_number, user_decimal_points)
true
de8fb516c4571f36b428c1988f73a91229942000
fathimathharsha/python.py
/CO1 pg 2.py
344
4.15625
4
#Display future leap years from current year to a final year entered by user. start=int(input("Enter start year :")) end=int(input("Enter final year :")) if(start<end): print("Leap years are:") for i in range(start, end): if (i % 4 == 0 and i % 100 != 0): print(i) else: print("Invalid Year")
true
585aaf9ac87d7b9a6969212906526f6ce56d9699
bravepoop/Python_Cheat_Sheets
/10 Exceptions.py
545
4.34375
4
# Exceptions # Exceptions help you respond appropriately to errors that are likely to occur. You place code that might cause an # error in the try block. Code that should run in response to # an error goes in the except block. Code that should run only # if the try block was successful goes in the else block. # Catching an exception prompt = "How many tickets do you need? " num_tickets = input(prompt) try: num_tickets = int(num_tickets) except ValueError: print("Please try again.") else: print("Your tickets are printing.")
true
e2e20d7560d3a7a37b77e2d373584f0da057b0aa
chrisrossi4542/MIT_Coursework_Git
/ps1p2.py
1,073
4.25
4
##Problem Set 1, Problem 2 ##Name: CRossi ##Program to calculate the minimum fixed monthly payments ##needed in order to pay off a credit card balance within 12 months original_Balance = float(raw_input('Enter the outstanding balance on your credit card: ')) annual_Interest_Rate = float(raw_input('Enter the annual credit card interest rate as a decimal: ')) monthly_Interest_Rate = annual_Interest_Rate/12.0 number_Of_Months = 13 minimum_Monthly_Payment = 10 remaining_Balance = original_Balance while remaining_Balance > 0: number_Of_Months = 0; remaining_Balance = original_Balance minimum_Monthly_Payment +=10 for i in range(1, 13): remaining_Balance = (remaining_Balance * (1.0 + monthly_Interest_Rate) - minimum_Monthly_Payment) number_Of_Months +=1 if remaining_Balance < 0: break print 'RESULT\n', 'Monthly payment to pay off debt in 1 year:', minimum_Monthly_Payment, '\n', 'Number of months needed:', number_Of_Months, '\n', 'Balance:', round(remaining_Balance, 2)
true
3d977517c930a72809d1c8002f8cee8403a5fbbb
charlievweiss/3dScanner
/Sample Code/receiveData.py
1,820
4.15625
4
# ****************************************************************** # * * # * * # * Example Python program that receives data from an Arduino * # * * # * * # ****************************************************************** import serial # # NOTE: While this is running, you can not re-program the Arduino. You must exit # this Phython program before downloading a sketch to the Arduino. # # # Set the name of the serial port. Determine the name as follows: # 1) From Arduino's "Tools" menu, select "Port" # 2) It will show you which Port is used to connect to the Arduino # # For Windows computers, the name is formatted like: "COM6" # For Apple computers, the name is formatted like: "/dev/tty.usbmodemfa141" # arduinoComPort = "/dev/ttyACM0" # # Set the baud rate # NOTE1: The baudRate for the sending and receiving programs must be the same! # NOTE2: Set the baudRate to 115200 for faster communication # baudRate = 9600 # # open the serial port # serialPort = serial.Serial(arduinoComPort, baudRate, timeout=1) # # main loop to read data from the Arduino, then display it # while True: # # ask for a line of data from the serial port, the ".decode()" converts the # data from an "array of bytes", to a string # lineOfData = serialPort.readline().decode() # # check if data was received # if len(lineOfData) > 0: # # data was received, convert it into 2 integers # # print the results # print(lineOfData)
true
819b6e8c00cf3e0ae1d1511a17cfd3dd1dcab7af
anandkodnani/C-
/sorting/insertion/insertion_sort.py
362
4.15625
4
def insertion_sort(arr) : for i in range(1, len(arr)) : currentValue = arr[i] position = i while position > 0 and arr[position - 1] > currentValue : arr[position] = arr[position - 1] position = position -1 arr[position] = currentValue arr = [10, 20, 15, 2, 23, 90, 67] insertion_sort(arr) print arr
false
2416590b310d3eea2c83a5c882ffed3ba400563a
endtailer007/pythonProject1
/oop.py
1,350
4.5
4
# class provides a blueprint or a template,where as object is an instance of the class # creation of object object_name=class_name() or this is called as class instantiation # Python does not require the new operator to create an object # object_name.class_membername() access class data # when we use __init__ method is a class constructor it is automatically executed when an object of a class is created.It is uded to initialize data members of the class class student(): rollno=0 name="" degree=0 aggreggate=0 def __init__(self,degree,name): #'''This method is used for initialisation of the object''' self.degree=degree self.name=name #This accepts input of student data def setstudentdetails(self): self.rollno=input("Enter student rollno: ") #self.name=input("Enter student name: ") #self.degree=input("Enter student branch: ") self.aggreggate=float(input("Enter student cgpa: ")) #This method displays the details of the student def getstudentdetails(self): print("Rollno of the student is ",self.rollno) print("Name of the student is ",self.name) print(self.name,"studies",self.degree) print("aggreggate of student is ",self.aggreggate) student1=student("BE","Sooraj") student1.setstudentdetails() student1.getstudentdetails()
true
4efa06d667375ff7918dcf9cbbdc4220db5acd2a
jaisinghchouhan/Forsks
/Day2/bricks.py
401
4.1875
4
def bricks(small,big,total): if small+big*5>=total: if total%5<=small: return True else: return False else: return False small=int(input("enter total number of one intch of brick")) large=int(input("enter the number of 5 intch of brick")) total=int(input("enter the total length of brick to be built")) print(bricks(small,large,total))
true
fbae147bf690ee876a3b30dac6c915afe621b5b0
jaisinghchouhan/Forsks
/Day2/pallindromic.py
405
4.25
4
def pallindrome(string): if string==string[::-1]: return True else: return False list1=["12", "9", "61", "5", "14"] for i in list1: if int(i)>0: a=pallindrome(str(i)) if a==True: n=True break else: n=False else: print("not integer") if n==True: print("true") else: print("false")
false
7dcecfa57ba0451d3a84aa2b17dd0699d25c74a5
raro28/grokking-algorithms
/python/quick_sort.py
703
4.1875
4
import random def pick_pivot(array): return random.randint(0, len(array) - 1) def quick_sort(array): if len(array) < 2: return array.copy() else: result = [] pivot = pick_pivot(array) #https://realpython.com/list-comprehension-python/ less = [array[i] for i in range( len(array)) if i != pivot and array[i] <= array[pivot]] greater = [array[i] for i in range( len(array)) if i != pivot and array[i] > array[pivot]] return quick_sort(less) + [array[pivot]] + quick_sort(greater) print("\nresults\n") print(quick_sort([1, 2, 3, 4, 5])) print(quick_sort([5, 4, 3, 2, 1])) print(quick_sort([5, 4, 6, 2, 1]))
true
ffb00eb55db1262eb5bdeb5fcdec2f00b1ca13ec
jasonmcboyd/sorting_algorithm_review
/bubblesort.py
499
4.28125
4
def bubblesort(array): n = len(array) - 1 while True: # Flag to determine if any values are swapped in # this pass. swapped = False # Start swapping. for i in range(0, n): if array[i] > array[i+1]: array[i], array[i+1] = array[i+1], array[i] swapped = True # After each pass index 'n + 1' will have the correct # value so we do not need to consider it again. n -= 1 # If no values were swapped we are done. # Terminate early. if swapped == False: break
true
df88afaa7dd9f3b8f2db2b3c4e9ff671683f0876
Viola8/Algorithms-in-Python
/queue.py
1,219
4.1875
4
# FIFO = first in first out LILO = last in last out class Queue: def __init__(self): self.queue = list() def addtoq(self,dataval): # Insert method to add element if dataval not in self.queue: self.queue.insert(0,dataval) return True return False def size(self): return len(self.queue) # Pop method to remove element def removefromq(self): if len(self.queue)>0: return self.queue.pop() return ("No elements in Queue!") TheQueue = Queue() # the queue objest is defined TheQueue.addtoq("a") TheQueue.addtoq("b") TheQueue.addtoq("c") print(TheQueue.size()) # 3 print(TheQueue.removefromq()) # a print(TheQueue.removefromq()) # b print(TheQueue.removefromq()) # c print(TheQueue.removefromq()) # No elements in Queue! # 2 queue = [] # Initializing a queue # Adding elements to the queue queue.append('a') queue.append('b') queue.append('c') print(queue) # ['a','b','c'] initial queue # Removing elements from the queue print("\nElements dequeued from queue") print(queue.pop(0)) # a print(queue.pop(0)) # b print(queue.pop(0)) # c print("\nQueue after removing elements") print(queue) # []
true
78d5feea8003123fa92ce297e7f6bf0f685c202d
Liberia1981/pdxfullstack
/dice.py
1,281
4.71875
5
# # Write a simple program that, when run, prompts the user for input then prints a result. # # Program should ask the user for the number of dice they want to roll as well as the number of sides per die. # # 1. Open Atom # 1. Create a new file and save it as `dice.py` # 1. Follow along with your instructor # # # 1. [Compound statements](https://docs.python.org/3/reference/compound_stmts.html) # 1. [Python Std. Library: Random Module random.randint()](https://docs.python.org/3/library/random.html#random.randint) # # # - Importing # - The Random Module # - `for` looping # - `input()` function # - programmatic logic from random import randint # roll=input("Press Y to roll the dice, press N to quit. ") # x=0 # while roll.lower()=='y': # x=int(input("Number of dice side: ")) # y=int(input("Number of rolls: ")) # print(randint(1,x)) # roll = input("Press Y to roll again, N to quit. ") # # print("Okay, we'll put the dice away.") user_dice_roll = int(input("Number of dice you want to roll: ")) die_side = int(input("Number of sides per dice: ")) counter = 0 for i in range (1, user_dice_roll+1): g=randint(1,die_side) print(g) counter = counter+g # print('Roll Number:',(i), 'Dice No.:',(g), 'Total vaule of dice rolled: ', (counter))
true
5e39a36299b9b2f488db4999687555afb8002e79
pierremont/python_challenges
/Reversed_sequence.py
337
4.125
4
''' codewars.com Get the number n (n>0) to return the reversed sequence from n to 1. Example : n=5 >> [5,4,3,2,1] ''' n = input("enter n: ") def reverse_seq(n): mylist = [] for i in range(n): if n > 0: mylist.append(n) n = n - 1 else: pass return mylist
false
37ca8ede59b6b3c2f2137c79f30520d1c65c63ce
pierremont/python_challenges
/list_filtering_list_comprehension_filtering.py
820
4.34375
4
'''List filtering In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out. Example filter_list([1,2,'a','b']) == [1,2] filter_list([1,'a','b',0,15]) == [1,0,15] filter_list([1,2,'aasf','1','123',123]) == [1,2,123] ''' def filter_list(l): return [x for x in l if isinstance(x, int)] print(filter_list([1,2,'a','b'])) '''other solutions: def filter_list(l): new_list =[] for x in l: if type(x) != str: new_list.append(x) return new_list def filter_list(l): 'return a new list with the strings filtered out' return [i for i in l if not isinstance(i, str)] def filter_list(l): 'return a new list with the strings filtered out' return [e for e in l if type(e) is int]'''
true
96c7bbf4db1be63b3ea8bc1c232b9f432bd44833
pierremont/python_challenges
/sum_of_cubes_7kyu.py
622
4.15625
4
'''Sum of Cubes (codewars, 7 kyu) Write a function that takes a positive integer n, sums all the cubed values from 1 to n (inclusive), and returns that sum. Assume that the input n will always be a positive integer. Examples: (Input --> output) 2 --> 9 (sum of the cubes of 1 and 2 is 1 + 8) 3 --> 36 (sum of the cubes of 1, 2, and 3 is 1 + 8 + 27)''' def sum_cubes(n): # result = 0 # for i in range(1,n+1): # result = result + i*i*i # return result return sum(x*x*x for x in range(1, n+1)) print(sum_cubes(3)) '''other solutions: def sum_cubes(n): return sum(i**3 for i in range(0,n+1))'''
true
73ad0887f51f13562a4453f5c9a7519ad390a4ff
prospros001/Python-basics
/practice02/03.py
1,010
4.125
4
# 문제3. # 1)다음 문자열을 모든 소문자를 대문자로 변환하고, 문자 ',', '.','\n'를 없앤 후에 중복 # 없이 각 단어를 순서대로 출력하세요. s = """We encourage everyone to contribute to Python. If you still have questions after reviewing the material in this guide, then the Python Mentors group is available to help guide new contributors through the process.""" # s = s.replace(',', '').replace('.', '').upper() # words = s.split(' ') # words_results = list(set(words)) # words_results.sort(key=str) # # for word in words_results: # print("{0}:{1}".format(word, words.count(word))) a = s.upper() b = a.replace(',', '').replace('.', '').replace('\n', '') count = b.split() count1 =[] for v in count: if v not in count1: count1.append(v) count1.sort(key=str) ans2 =[] for ans1 in count1: ans2.append(ans1) print(ans1) # print(ans2) cnt = [] for z in count: cnt.append(count.count(z)) for ans print(f'%s : %s 개' % (ans2, cnt))
true
315746633e48ba0999c399694be2f8dc2aedcb82
KaoriMorinaga/pythonAtividades
/EstruturaSequencial/atividade_2_EntradaDeValor.py
278
4.25
4
''' Larissa Kaori Morinaga 17-12-2018 Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número]. ''' numero = input("Digite um valor: ") print("O número informado foi", numero, ".") #print("O número informado foi " + str(numero) + ".")
false
0ad2e8c33b3f39e1c8a7b6e0b250ad4427927d8e
er-mm/Learning_Python
/Learn_Python/Basics/ModulesPackages/ModulesAndPackages.py
1,549
4.34375
4
# Modules and Packages # In programming, a module is a piece of software that has a specific functionality. # For example, when building a ping pong game, one module would be responsible for the game logic, and # another module would be responsible for drawing the game on the screen. Each module is a different file, which can be edited separately. # Writing modules # Modules in Python are simply Python files with a .py extension. # The name of the module will be the name of the file. A Python module can have a set of functions, classes or variables defined and implemented. import Calc # or from Calc import * # We may also use the import * command to import all objects from a specific module # Import a particular function ( from Calc import sum) import urllib #python library sum = Calc.add(1,2) sub = Calc.sub(1,2) mul = Calc.mul(1,2) div = Calc.div(1,2) sortedList = Calc.sortList([22,11,14,15,6,3]) print(sortedList) sortedList = Calc.sortList(['ab','aa','da','aca']) print(sortedList) def main(): initialize = (sum,sub,mul,div) result = "sum is = %d, sub is = %d, mul is = %d, div is = %.1f." % initialize print(result) if __name__ == '__main__': main() # Module initialization # The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. # If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a "singleton" - they are initialized only once.
true
b2afb056bf5f7539bee7f23024f252b66bb4f7ea
er-mm/Learning_Python
/Learn_Python/Basics/Dictionaries.py
1,977
4.8125
5
# Dictionaries # A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. # Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it. # For example, a database of phone numbers could be stored using a dictionary like this: phonebook = {} phonebook['Mayank'] = 1234567890 phonebook['Ayush'] = 9876543210 phonebook['Mittal'] = 1357924680 print(phonebook) # {'Mayank': 1234567890, 'Ayush': 9876543210, 'Mittal': 1357924680} # Alternatively, a dictionary can be initialized with the same values in the following notation: phonebook2 = { 'Mayank' : 1234567890, 'Ayush' : 9876543210, 'Mittal' : 1357924680 } print(phonebook2.items()) # dict_items([('Mayank', 1234567890), ('Ayush', 9876543210), ('Mittal', 1357924680)]) # Iterating over dictionaries # Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. # To iterate over key value pairs, use the following syntax: for key, value in phonebook.items(): # if using phonebook : ValueError: too many values to unpack (expected 2) print("The number of %s is %d." % (key, value)) # Removing a value # To remove a specified index, use either one of the following notations: del phonebook['Mayank'] del phonebook2['Ayush'] print(phonebook) print(phonebook2) # or: phonebook.pop('Mittal') phonebook2.pop('Mittal') print(phonebook) print(phonebook2) # Exercise # Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook. phonebook = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } # write your code here phonebook['Jake'] = 938273443 phonebook.pop('Jill') # testing code if 'Jake' in phonebook: print('Jake is listed in phonebook') if 'Jill' not in phonebook: print('Jill is not listed in phonebook')
true
66aa2d833d1f0fd103c5e7ce67217297626ca8ab
Iam-El/Random-Problems-Solved
/leetcodePractice/mediumProblems/sortCharatersByFrequenecy.py
820
4.125
4
# Given a string, sort it in decreasing order based on the frequency of characters. # "tree" # "eert" # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. def sortCharactersByFrequency(s): dict={} output=[] character1=[] for i in s: if i not in dict: dict[i]=1 else: dict[i]=dict[i]+1 print(dict) valuesSorted=sorted(dict.values()) valuesSorted.reverse() print(valuesSorted) for i in valuesSorted: print(i) for character,frequency in dict.items(): if i==frequency: if character*i not in output: output.append(character*i) print(''.join(output)) s="tree" sortCharactersByFrequency(s)
true
96be474c4167e78935da6923e751fa888a46c0ee
anuragrao04/CS-Assignments
/assignment-5.py
1,045
4.5
4
### Write a Python Program to convert decimal numbers to octal numbers using ### user- defined function Convert(), function takes two arguments decimal number ### and base. If base is missing function should convert decimal number to binary. def Convert(given_num, base = 2): octal_num = [0] num_of_octal_char = 0 while (given_num != 0): octal_num.append(given_num % base) given_num = int(given_num / base) num_of_octal_char += 1 for i in range(num_of_octal_char, 0, -1): list_of_alphabets = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] if octal_num[i] >= 10: octal_num[i] = list_of_alphabets[octal_num[i]-10] print(octal_num[i], end = "") print() given_num = int(input("Enter Decimal Number To Convert: ")) base = input("Enter Base To Convert To (Default = 2): ") if base == '': Convert(given_num) else: base = int(base) Convert(given_num, base)
true
d654db09be95565c54e8462524d796138e5fc84c
csgray/intro_lesson_2
/lesson_2-2_variables.py
2,175
4.6875
5
# Lesson 2.2: Variables # Programmers use variables to represent values in their code. # This makes code easier to read by telling others what values # mean. It also makes code easier to write by cutting down on # potentially complicated numbers that repeat in our code. # We sometimes call numbers without a variable "magic numbers" # It's best to reduce the amount of "magic numbers" in our code # https://www.udacity.com/course/viewer#!/c-nd000/l-4192698630/m-48660987 speed_of_light = 299792458.0 billionth = 1.0 / 1000000000.0 nanostick = speed_of_light * billionth * 100 print nanostick # What is a variable? # Variables make it easy to refer to expressions # What does it mean to assign a value to a variable? # States the expression or number that the variable represents # What is the difference between what the equals = means in math versus in # programming? # The = does not mean equal in programming. It is an arrow indicating that # the value to the right should be assigned to the variable on the left. # What's the difference between this: 2 + 3 = 5 and this: my_variable = 5? # 2 + 3 = 5 is an arithmetic expression and its result # my_variable = 5 assigns the vlaue 5 to my_variable # Assignment Statement: Name = Expression # Variables Quiz speed_of_light = 299792458.0 #meters per second cycles_per_second = 2700000000.0 #2.7 GHz distance_per_cycle = speed_of_light / cycles_per_second print distance_per_cycle # You can update the values of a variable as Python moves down the code cycles_per_second = 2800000000.0 #2.8 GHz distance_per_cycle = speed_of_light / cycles_per_second print distance_per_cycle # Python will keep calculating and updating the value of a variable days = 7 * 7 # 49 days = 48 # 48 days = days - 1 # 47 days = days - 1 # 46 print days # 46 # Varying Variables Quiz 1 hours = 9 # 9 hours = hours + 1 # 10 hours = hours * 2 # 20 print hours # 20 # Varying Variables Quiz 2 # minutes = minutes + 1 # No initial value assigned to minutes # seconds = minutes * 60 # NameError: name 'minutes' is not defined # Python evaluates the right side first # Spirit Age Quiz year = 365 #days age = year * 29 print age
true
cc7082e171ee6c0b37e5c542334fcc04d6060707
myf-algorithm/Leetcode
/Leetcode/101.对称二叉树.py
750
4.15625
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSymmetric(self, root): if not root: return True def traverse(l, r): if not l and not r: return True if not l or not r: return False return l.val == r.val and traverse(l.left, r.right) and traverse(l.right, r.left) return traverse(root.left, root.right) if __name__ == '__main__': S = Solution() root = TreeNode(5) node1 = TreeNode(3) node2 = TreeNode(3) root.left = node1 root.right = node2 print(S.isSymmetric(root))
true
77fe836a8cb28c972b842aa96f3875975284a127
myf-algorithm/Leetcode
/Swordoffer/58.对称的二叉树.py
1,143
4.1875
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetrical(self, pRoot): if not pRoot: return True return self.recursiveTree(pRoot.left, pRoot.right) def recursiveTree(self, left, right): if not left and not right: # 左右子节点都为空 return True if not left or not right: # 左右子节点其中一个为空 return False if left.val == right.val: # 左右子节点都存在,并且值相等,进行下一次递归 return self.recursiveTree(left.left, right.right) and self.recursiveTree(left.right, right.left) return False if __name__ == '__main__': S = Solution() root = TreeNode(0) node0 = TreeNode(2) node1 = TreeNode(3) node2 = TreeNode(4) node3 = TreeNode(2) node4 = TreeNode(4) node5 = TreeNode(2) root.left = node0 root.right = node1 node1.left = node2 node1.right = node3 node3.left = node4 node4.left = node5 print(S.isSymmetrical(root))
true
701c0f2f11ea306561da312d25d110fc814f0889
Grand251/Algorithms
/sorting.py
2,424
4.21875
4
def selection_sort(array): # i is the position we are filling for i in range(len(array)): next_smallest_index = i # Search remainder for next smallest for k in range(i, len(array)): if array[k] < array[next_smallest_index]: next_smallest_index = k # Swap out values aux = array[i] array[i] = array[next_smallest_index] array[next_smallest_index] = aux return array def insertion_sort(array): # Next to place for i in range(1, len(array)): # Place element within pre-sorted section for k in range(0, i): if array[i] < array[k]: array.insert(k, array.pop(i)) break return array def bubble_sort(array): finished_sorting = False while not finished_sorting: finished_sorting = True for i in range(len(array) - 1): if array[i] > array[i + 1]: finished_sorting = False aux = array[i] array[i] = array[i + 1] array[i + 1] = aux return array def merge_sort(array): if len(array) == 1: return array mid_point = int(len(array) / 2) section1 = merge_sort(array[0: mid_point]) section2 = merge_sort(array[mid_point: len(array)]) sorted_array = [] ptr1 = 0 ptr2 = 0 while ptr1 < len(section1) and ptr2 < len(section2) > 0: if section1[ptr1] < section2[ptr2]: sorted_array.append(section1[ptr1]) ptr1 += 1 else: sorted_array.append(section2[ptr2]) ptr2 += 1 # Add remainder for i in range(ptr1, len(section1)): sorted_array.append(section1[i]) for i in range(ptr2, len(section2)): sorted_array.append(section2[i]) return sorted_array def quick_sort(array, start=None, end=None): if start is None or end is None: start, end = 0, len(array) - 1 if end - start < 1: return array pivot = end last_smaller = start - 1 for i in range(start, end): if array[i] <= array[pivot]: last_smaller += 1 array[i], array[last_smaller] = array[last_smaller], array[i] array[last_smaller + 1], array[pivot] = array[pivot], array[last_smaller + 1] quick_sort(array, start, last_smaller) quick_sort(array, last_smaller + 2, end) return array
true
60650b58d8e379702d5dd8707de7f26734a8d934
BruceBerk/advent-code-2017
/advent5_2.py
1,229
4.15625
4
# Advent of Code 2017 5.2 # A Maze of Twisty Trampolines, All Alike # # Bruce Berkowicz # bruceberk@me.com # 12/11/17 # """ Now, the jumps are even stranger: after each jump, if the offset was three or more, instead decrease it by 1. Otherwise, increase it by 1 as before. Using this rule with the above example, the process now takes 10 steps, and the offset values after finding the exit are left as 2 3 2 3 -1. How many steps does it now take to reach the exit? Answer is 23948711 """ def count_jumps(filename): """Follow a list of jump instructions determining the number of steps needed to get out""" steps = 0 with open(filename) as jump_file: f = jump_file.read() jumps = [int(instr) for instr in f.split()] idx = 0 sz = len(jumps) while idx >= 0 and idx < sz: instr = jumps[idx] if instr >= 3: jumps[idx] = instr - 1 else: jumps[idx] = instr + 1 idx += instr steps += 1 return steps # run the test file - should be 5 steps steps = count_jumps('data/test5.txt') print('made it out in', steps, 'steps') steps = count_jumps('data/input5.txt') print('made it out in', steps, 'steps')
true
d3c28cece4405d7dff3909d7b10f5e58554e3f7e
ornela83/Proyecto_contactos
/03.herencia.py
1,378
4.15625
4
class Restaurante: #constructor def __init__(self, nombre, categoria, precio): self.nombre = nombre self.categoria = categoria self.__precio = precio def mostrar_informacion(self): print(f"Nombre: {self.nombre}, \nCategoría: {self.categoria}, Precio: {self.__precio}") #GETTERS Y SETTERS (ASI SE MODIFICA LOS ATRIBUTOS ENCAPSULADOS) #Get = obtiene un valor #Set = Agrega un valor def get_precio(self): #obtengo el valor private return self.__precio def set_precio(self, precio): #puedo a acceder al valor private y modificarlo a traves de un metodo self.__precio = precio restaurante = Restaurante("Don Pepe", "Parrilla", 50) #restaurante.__precio=80 #no se puede modificar, esta encapsulado restaurante.mostrar_informacion() restaurante.set_precio(80) precio = restaurante.get_precio() #se guarda en una variable por el meétodo retorna un valor print(precio) restaurante2 = Restaurante("Il Gato", "Pastas", 20) restaurante2.mostrar_informacion() restaurante2.set_precio(60) precio2 = restaurante2.get_precio() print(precio2) #Crear una clase hijo de Restaurante class Hotel(Restaurante): def __init__(self, nombre, categoria, precio): super().__init__(nombre, categoria, precio) hotel = Hotel("Hotel POO", "5 Estrellas", 200) hotel.mostrar_informacion()
false
20b6430fb3a8e2d6e9ec7ccb0358a14c27ee6876
tylerdonison/CSE111
/Week 01/heart_rate.py
761
4.15625
4
""" When you physically exercise to strengthen your heart, you should maintain your heart rate within a range for at least 20 minutes. To find that range, subtract your age from 220. This difference is your maximum heart rate per minute. Your heart simply will not beat faster than this maximum (220 - age). When exercising to strengthen your heart, you should keep your heart rate between 65% and 85% of your heart's maximum. """ age = int(input("Please enter your age: ")) heartrate_max = 220 - age heartrate_high = int(heartrate_max * 0.85) heartrate_low = int(heartrate_max * 0.65) print(f"When you exercise to strengthen your heart, you should") print(f"keep your heart rate between {heartrate_low} and {heartrate_high} beats per minute.")
true
105bdc696c07b04bb1d86a0abff863c0653232e7
QMIND-Team/QMIND-67s-Project
/code/Data_Functions/Data_Functions.py
1,709
4.21875
4
"""Function to detect outliers Args: df (dataframe): Dataframe that will be examined by the function Returns: """ def detect_outliers(df): outliers = [] for column in df: cut_off = df[column].std() * 2 lower = df[column].mean() - cut_off upper = df[column].mean() + cut_off row_count = 0 for x in df[column]: if x >= upper or x <= lower: # if below or above 2 stds from mean, add to outliers array outliers.append(row_count) # adds row to outliers array row_count += 1 outliers = list(set(outliers)) # removes duplicate rows return outliers """Function to remove outliers Args: Returns: dict: dict containing dataframe without outliers """ def remove_outliers(): outliers = detect_outliers(df) df = df.drop(index=outliers) return df """Function that removes columns containing NAN Args: df (dataframe): dataframe to be checked col_type (str): type of data to be examined in the dataframe Returns: dict: dict containing dataframe without the selected column """ def get_col_with_no_nan(df, col_type): if col_type == 'num': predictors = df.select_dtypes(exclude=['object']) elif col_type == 'no_num': predictors = df.select_dtypes(include=['object']) elif col_type == 'any': predictors = df else: print('Please input a correct col_type value (num, no_num, any)') return 0 col_with_no_nan = [] for col in predictors.columns: if not df[col].isnull().any(): col_with_no_nan.append(col) return col_with_no_nan
true
ae85f64f9ddca505701c740d082fb973d08723cf
harshil002/Homework-4
/Markdown_File.py
1,911
4.5
4
# coding: utf-8 # GAME: ROCK, PAPER, Scissor # # This game includes rock, paper and scissor where the rock wins over scissor, scissor wins over paper and paper wins over rock.This game is about who will win in a random manner and only one user can paprticipate at a time versus computer. # for instance, let's suppose the player entered rock and the bot enters paper, here the bot wins the game. # This game is created using if,elseif,else statements, functions and library in python.This is a user based game where the useer has to input that one keywork in the form of rock or paper or scissor. # # Challenges Faced/Proud moments: # 1.) I actually did not know how to make random generation of keywords possible. In meaning, how to make computer randomly choose among rock, paper and scissor. I had to study about random library in python over the web and then I figured out it's usage. # # 2.) Functions containing the if statements were something that played the trick on me. I was not able to particularly identify # that how to manage the statements within the functions.However, I managed it by rewriting some lines and debugging the code. # # 3.) I was able to create a text based game where no computer was involved we can just enter two inputs and based on that the program will provide that who wins rock or scissor or paper. But I learned about random generation and implemented the concept. # # 4.) From a technical standpoint I was really proud of implementing random keyword generation for computer. # # # INSRTUCTIONS to Play: # # All text are case sensitive. User just has to enter a keyword: # # Enter any keyword form the group of three. There are three keywords: # 1.) rock # 2.) paper # 3.) scissor # # When the user enter the keywork and press enter the result will be displayed. One can play multiple times by running the program again and again.
true
0b6fb8fd31a4fc0943ec2f1bd6e7d54723dea3ca
Paandi/LearnPython
/basicModule/random_generator_tutorial.py
380
4.15625
4
#random_number_generator --Range for i in range(0,20,2): print(i) --Random import random x=[1,2,3,4,5,29,30,12,9] for i in range(0,20,2): --- to pick random item from a list print(random.choice(x)) random.randint(1,3) --- to pick from a integer range random.random() --- 0 to 1 floating
true
a8b2b82556a965299572d80beb76a74eef15aad3
leonardokiyota/Python-Training
/Exercises Python Brasil/01 - Estrutura Sequencial/11.py
679
4.3125
4
# -*- coding: utf-8 -*- """ Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: - O produto do dobro do primeiro com metade do segundo . - A soma do triplo do primeiro com o terceiro. - O terceiro elevado ao cubo. """ num1 = int(input("Digite um número inteiro: ")) num2 = int(input("Digite outro número inteiro: ")) num3 = float(input("Digite um número real: ")) print("O produto do dobro do primeiro com metade do segundo é: {}". format((num1 * 2) / (num2 / 2))) print("A soma do triplo do primeiro com o terceiro é: {}" .format((num1 * 3) + num3)) print("O terceiro elevado ao cubo é: {}".format(num3 ** 3))
false
e27b89f171fdccb3dc56c60866cdd9dadd7f26bf
winyter/Python-Learning
/OOP/03.py
1,473
4.21875
4
''' 鸭子模型演示 ''' class A(): name = "aaa" age = 1 def __init__(self): self.name = "init" self.age = 0 def aa(self): print(self.name) print(self.age) class B(): name = "bbb" age = 2 print('*' * 20) #这是基础的通过定义A类的一个对象a,来调用aa()方法,此处,self代理的就是a对象,而__init__可以理解是构造函数,有构造函数的类中,没有定义相应成员的方法在使用该成员时,会去构造函数中查找使用同名的成员,而不会如之前所说的那样,去类的实例中获取这个成员 a = A() a.aa() print('*' * 20) #这是调用类A的方法,并传入对象a的形式来实现调用方法aa(),这个方式实际上和上面的方法没有区别,只是写法不同而已 A.aa(a) print('*' * 20) #这就是通过调用类A的方法,并传入类A的实例对象A来实现调用方法aa(),此处,self代理的就是类A的实例对象A,所以,本段代码的运行结果也可以看到,就是A的成员值 #但是需要注意,在使用类的实例对象时,就不可以使用定义的对象来调用类的方法,例如:a.aa(A) 的写法,程序会报错,简单的记法:调用类的成员,只能通过类来调用方法,对象比类小一级,调不动 A.aa(A) print('*' * 20) #此处展示了调用其他类的成员,这在Python中也是可行的,其结果就是类B中的成员值 A.aa(B)
false
b03fbb2a0e1e7a3e56baf15e0a32ddb11decc4d9
bwatson546/prg105
/ageclass.py
566
4.15625
4
age = int(input("How OLD is your HUMAN?")) if age <= 0: print("This is GESTATING. Please COME BACK LATER.") elif age > 0 and age <= 1: print("That is an INFANT. It cannot TELL JOKES.") elif age > 1 and age < 13: print("That is a dang CHILD. It tells TOO MANY JOKES.") elif age > 13 and age < 20: print("Why have you brought this TEEN before me? I do not WANT IT.") elif age > 10 and age < 500: print("This is a GROWN-ASS ADULT. It CAN MAKE IT ON ITS OWN.") elif age >= 5000000: print("Please remove your ELDER GOD. I am FRIGHTENED of it.")
true
0948b6613e24eb73258fac2ee5e20409388aeac8
antspr/Day_Trip_Generator
/Day_04_Day_Trip_Generator/random_trip.py
2,516
4.3125
4
import random #Make a list to store each of the available variables cities = ['New York','Miami','Los Angeles','London','Paris','Dubai','Hong Kong','Tokyo'] restaurants = ["Morton's","Nobu","McCormick's","a Speakeasy"," a Dive Bar"," a Picnic","McDonald's"," some Street Food"] vehicles = ["Car","Bus","Train","Bicycle","Walking","Taxi","Horse and Buggy","Electric Scooter"] activities = ["Concert","Play","Niteclub","Bowling","Sightseeing","Museum","Voluteering","Networking"] def randomization_tool(random_list): for element in random_list: element = (random.choice(random_list)) return element approved = True #Want to use this to complete selection trip_package_list = [randomization_tool(cities),randomization_tool(restaurants),randomization_tool(vehicles),randomization_tool(activities)] trip_package_mixed_string = (f'You will be visiting: {trip_package_list[0]}, where you will be having {trip_package_list[1]} for dinner, traveling by way of {trip_package_list[2]}, and spend the day...{trip_package_list[3]}') approved_package = [trip_package_list[0],trip_package_list[1],trip_package_list[2],trip_package_list[3]]#would like to call "return" variable from function? approval = input(f'We have put together a trip, {trip_package_mixed_string}, Would you like to go on this trip? Y/N?') if approval.upper() == 'Y': approved == True print(f'The trip where {trip_package_mixed_string} selection process is complete. Congratulations!') elif approval.upper() == 'N': approved == True new_selection = int(input("""What would you like to change? Choose "1" to change the destination, "2" for a different place to eat "3" for a different mode of travel "4" for a different activity:""")) if new_selection == 1: approved_package[0]= randomization_tool(cities) elif new_selection == 2: approved_package[1]= randomization_tool(restaurants) elif new_selection == 3: approved_package[2]= randomization_tool(vehicles) elif new_selection == 4: approved_package[3]= randomization_tool(activities) approved == False confirmed = input(f'''Your trip now has you traveling to {approved_package[0]}, eating at {approved_package[1]}, traveling by {approved_package[2]}, and hanging out {approved_package[3]} Please enter "Y" to confirm, "N" to ammend.''') if confirmed.lower() == 'y': print("Your trip has been confirmed") else: print(trip_package_mixed_string)
true
85f9e2b4e449d234f51e777056e6f090ae0b0931
ramin153/algebra-university
/3_9732491_ramin_rowshan.py
1,105
4.40625
4
def inner_product(vector1: list, vector2: list, size: int = 3): result = 0 for i in range(0, size, 1): result += vector2[i] * vector1[i] return result def vector_multiplication(matrix:list,vector:list,size:int = 3): result = [] ''' ضرب ماتریس یعنی سطر ماتریس اول در ستون ماتریس دوم چون معادله به صورت ax هست پس سطر های ماتریس a در وکتر x ضرب می شود و ضرب شدن یعنی ضرب ایتم های متناظر و جمع کردن ان های که به عبارت دیگر لینر پراداکت در حال انجام است و جواب نهایی ما یک ماتریس با 3 سطر و یک ستون می باشد ''' for i in range(0,size,1): result.append([inner_product(matrix[i],vector,size)]) return result if __name__ == "__main__": print(vector_multiplication([[1,1,1],[2,2,2],[3,3,3]],[1,2,3])) print(vector_multiplication([[1,2,3],[4,5,6],[7,8,9]],[1,1,1])) print(vector_multiplication([[1,-3,4],[5,6,-7],[3,2,12]],[-1,5,8]))
false
b26ea7b97b2742c4559f96f75a0c3a9142465c74
stevenjf/CodeNation
/cash machine.py
1,326
4.21875
4
#made by - steven f - michael Z - Anam Asif #Date 19/5/2021 #step 1 create a list of pins bank_stored_pin = [1122, 2211, 1212] balance = 1000 #step 2 create some user input for the pin user_input = int(input("enter pin")) balance_input = int(input("withdrawral amount")) #step 3 test # print(bank_stored_pin) # print(user_input) #step 4 cross referance user's pin # for pin in bank_stored_pin: # if user_input == pin: # print("correct pin") # break # elif user_input != pin: # continue #this does not work ^ # pin_check_num = bank_stored_pin.count(user_input) # print(pin_check_num) # if pin_check_num == 1: # print("correct pin") # else: # print("incorrect pin") #step 5 put this into a function # bank_stored_pin = [1122, 2211, 1212, 2121, 1321] def pin_checker(): pin_check_num = bank_stored_pin.count(user_input) if pin_check_num == 1: print("correct pin") else: print("incorrect pin") # pin_checker() #step 6 input a balance def funds_checker(): if balance >= balance_input: print("you have sufficent funds do you with to proceed") else: print("insufficent funds") funds_checker() #step 7 make it so the balance updates after withdrawal balance - balance_input
true
7c0a4e78e7eb5597c3740d6aab028a6de8a2c127
dev-sandarbh/PythonOneDayBuilds
/PythonTurtleModuleExamples/turtleIntro.py
1,035
4.3125
4
import turtle step = 5 #creating an object of turtle class demo = turtle.Turtle() # defining the color - it accepts common color names, rgb values and hex values # first arg in color func is boundary color and second arg is fill color # demo.color("red","cyan") # demo.begin_fill() # for i in range(0,49): # demo.forward(step) # demo.left(90) # demo.forward(step) # demo.left(90) # step+=1 # demo.forward(step) # demo.left(90) # step+=1 # demo.forward(step) # demo.end_fill() demo.color("red","cyan") demo.begin_fill() print(demo.pos()) # creating a basic square for i in range(0,4): demo.forward(100) demo.left(90) demo.end_fill() print(demo.pos()) # commands to move our turtle to a new loaction demo.penup() demo.pensize(5) demo.right(90) demo.pencolor("grey") demo.forward(10) demo.pendown() print(demo.pos()) # creating another square just below it demo.begin_fill() for i in range(0,4): demo.forward(100) demo.left(90) demo.end_fill() print(demo.pos()) turtle.done()
true
f4bf865c83c12a8c40f83b8c63585a996698d113
MagicBloodFly/StudyPython
/Item/代码笔记.py
915
4.125
4
# join()函数 把数组里面的数据结合并表达出来 # join()只针对字符串 # sort()函数也是针对字符串 # 例子 t, s = "one", "two" arg = [t, s] z1 = " ".join(arg) # 用空格分开 print(z1) z2 = ":".join(arg) # 用冒号分开 print(z2) # 保留小数方法 s = 3.14 s = ("%.6f" % s) # 6位小数 print(s) # sum()用法 n = sum([1, 2, 3]) # 等于6 print(n) # split(",") 用法 n = map(float, input("").split(",")) # 使用逗号隔开输入 # 例如输入 1,2 # isdigit()检测字符串是否是数字 返回True或者False tx = "sd4731" print(tx.isdigit()) tx2 = "45" print(tx2.isdigit()) # line是一个字符串变量 line = "Python is simple.I practice programming everyday." n_i = line.count("i") # count()统计在字符串里面i出现多少次 i_t = line.index("t") # index()统计在字符串里面t首次出现的下标
false
d516a194f2c60ab23eb9e56484fd955963244555
commento/DataStructuresAndAlgorithms
/problem_1.py
1,268
4.3125
4
def binary_search_recursive(number, start_index, end_index): if start_index > end_index: return -1 mid_index = (start_index + end_index)//2 operation = number // mid_index if operation == mid_index: return mid_index elif operation < mid_index: # print("iteration") return binary_search_recursive(number, start_index, mid_index - 1) else: # print("iteration") return binary_search_recursive(number, mid_index + 1, end_index) def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if type(number) is not int or number < 0: return None if number == 0 or number == 1: return number return binary_search_recursive(number, 2, number) print ("Pass" if (3 == sqrt(9)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (4 == sqrt(16)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") print ("Pass" if (10000 == sqrt(100000000)) else "Fail") print ("Pass" if (None == sqrt(-1)) else "Fail") print ("Pass" if (None == sqrt("a")) else "Fail")
true
e6f1e291f87c784768ed6ce79fb2a6b11e48a238
nsudhanva/mca-code
/Sem3/Python/oops/bank.py
1,768
4.21875
4
# Create a class as bank, initialise the instance variable balance as zero # Create a methid called as deposite that takes amount as an argument and increment balace with this amount # Create another method class as withdraw which again takes amount as a parameter # Decrement the balance with the amount if balance becomes less than zero, display withdraw is not possible # Revert back to the original balance # Create another method called as display, which displays the balance amount class Bank: 'This bank is awesome' balance = 0 def __init__(self): pass def deposit(self, amount): Bank.balance += amount message = 'Deposited ' + str(amount) + ' successfully' return message def withdraw(self, amount): if Bank.balance != 0 and Bank.balance >= amount: Bank.balance -= amount message = 'Withdrawn ' + str(amount) + ' successfully' return message else: message = 'Withdraw not possible: Balance is' + str(Bank.balance) return message def display_balance(self): return Bank.balance bank = Bank() while True: print('1. Deposit') print('2. Withdraw') print('3. Display Balance') print('4. Quit') choice = int(input('Enter option: ')) if choice == 1: amount = float(input('Enter amount to deposit: ')) print(bank.deposit(amount)) elif choice == 2: amount = float(input('Enter amount to deposit: ')) print(bank.withdraw(amount)) elif choice == 3: print(bank.display_balance()) else: break print(Bank.__dict__) print(Bank.__doc__) print(Bank.__dir__) print(Bank.__name__) print(Bank.__module__) print(Bank.__bases__) print(dir(Bank))
true
9bca75b7136c338bd3de199725890d5327ccca89
nsudhanva/mca-code
/Sem3/Python/re/practice_1.py
464
4.125
4
# Given string, find all the occurences of vowels in that string # import re # string = input('Enter some string: ') # pattern = '[aeiou]' # print(re.findall(pattern, string)) # print(re.search(pattern, string)) # print(re.match(pattern, string)) # Given a list of text inof, print all the text that start with a names = ['sudhanva', 'anjana', 'anagha', 'apoorva', 'vijay', 'shreedhar'] names_with_a = [i for i in names if i.startswith('a')] print(names_with_a)
true
99e1113fa4dc0e411a6226dead02a84550d7d23e
aishajackson/Programming_Languages_Course
/Quadratic.py
850
4.46875
4
#Quadratic Equation Program- Given the roots solve the quadratic equation #By Aisha Jackson #10/18/14 #!/usr/bin/python import math #import math function print "Hello user! This program will calculate the quadratic equation by using the quadratic formula. \n" a = int(input("Please enter an integer value for a. \n")) #Ask for a b = int(input("Please enter an integer value for b. \n")) #ask for b c = int(input("Please enter an integer value for c. \n")) #ask for c b2 = b ** 2; b22 = 4 * a * c; rad = math.sqrt(b2 - b22); negb = -1 * b; top = negb + rad; #calculate the top part of the quadratic formula ^ top2 = negb - rad; bottom = 2 * a;#calculate the bottom portion ^ quad = top / bottom; quad2 = top2/ bottom; #calculate the quadratic formula #output the roots print "The first root is "+ str(quad) print "The second root is " + str(quad2)
true
ceb4587122ca8418050cd47c7dc0674956964212
HujiAnni/CAC101-Constructing-Expressions-in-Python
/Average(Mean) of a List of Numbers.py
735
4.4375
4
# define a list of numbers and assign it to my_list my_list = [10,20,30,40] # Set a running total for elements in the list, initialized to 0 total = 0 # Set a counter for the number of elements in the list, initialized to 0 num_elements = 0 # Loop over all the elements in the list for element in my_list: # Add the value of the current element to total total = total + element # Add 1 to our counter num_elements num_elements = num_elements + 1 # Compute the average by dividing the total by num_elements average = total / num_elements my_list_average=sum(my_list)/len(my_list) print(my_list_average) my_set={40,20,30,10} my_set_average=sum(my_set)/len(my_set) print(my_set_average)
true
0b25c1ea129f70b8ab1703bb1bbab41a01ed7ab7
dafnemus/universidadPython2021
/Ejercicios/valorDentroRango.py
307
4.15625
4
# Ejercicio Valor Dentro del Rango: # Solicite un valor al usuario y determine si esta dentro del rango. valor = int(input('Ingrese un numero: ')) if valor > 0 and valor <= 5: print(f'El valor {valor} está dentro del rango(1 al 5)') else: print(f'El valor {valor} está fuera del rango(1 al 5)')
false
9378681eae10e42dec80f64779be4e2ffdd2ea41
dafnemus/universidadPython2021
/Colecciones/Tuplas/tuplas.py
544
4.15625
4
# Tuplas tupla_de_frutas = ('Naranja', 'Manzana', 'Banana') print(tupla_de_frutas) # largo de una tupla print(len(tupla_de_frutas)) # acceder a un elemento indices print(tupla_de_frutas[1]) # navegacion inversa indices print(tupla_de_frutas[-1]) # acceder a un rango de valores print(tupla_de_frutas[0:2]) # recorrer elementos for fruta in tupla_de_frutas: print(fruta, end='//') # cambiar el valor de una tupla conversiones fruta_lista = list(tupla_de_frutas) fruta_lista[1] = 'Pera' frutas = tuple(fruta_lista) print('\n', frutas)
false
18c85e7944c460cdd514d61040c62b781ba7a63b
sarahvestal/ifsc-1202
/Unit 3/03.09 Next Day.py
845
4.40625
4
#Prompt for a month (an integer from 1 to 12) and a day in the month (an integer from 1 to 31) in a common year (not a leap year). #Print the month and the day of the next day after it. #The first test corresponds to March 30 - next day is March 31 #The second test corresponds to March 31 - next day is April 1 #The third test corresponds to December 31 - next day is January 1 #Enter Month: 3 #Enter Day: 30 #Next Day: 3/31 month = int(input("Enter an integer representing the month of the year: ")) #day = int(input("Enter an integer representing the day of the month: ")) if month == 2: monthdays = 28 elif month == 4 or 6 or 9 or 11: monthdays = 30 else: monthdays = 31 #if day < monthdays: # day += 1 print int(monthdays) #if day == monthdays: # day == 1 and month += 1 #print ("Next Day: {}{}".format(month, day))
true
49a9e6205282f3f78477decac146ea07749175b6
sarahvestal/ifsc-1202
/Unit 2/02.05 Tens Digit.py
250
4.125
4
#Enter a number and print its tens digit. #Be sure to use the .format method to create your output #Enter a Number: 72 #Tens Digit: 7 number = int(input("Enter a number: ")) tendigit = int(number % 100 / 10) print ("Tens Digit: {}".format(tendigit))
true
c9f9a7a6bd98679b39b846a27516935296182405
sarahvestal/ifsc-1202
/Unit 1/content/01.00.05 Python Casting.py
932
4.1875
4
intval1 = 7 intval2 = -3 intval3 = 0 floatval1 = 2.8 floatval2 = -4.6 floatval3 = 5.0 strval1 = "6" strval2 = "-7.8" strval3 = "5a" print (int(intval1)) print (int(intval2)) print (int(intval3)) print (int(floatval1)) # Note that 2.8 becomes 2 print (int(floatval2)) # Note that -4.6 becomes -4 print (int(floatval3)) print (int(strval1)) #print (int(strval2)) # Note you will get an error here #print (int(strval3)) # Note you will get an error here print (float(intval1)) print (float(intval2)) print (float(intval3)) print (float(floatval1)) print (float(floatval2)) print (float(floatval3)) print (float(strval1)) print (float(strval2)) #print (float(strval3)) # Note you will get an error here print (str(intval1)) print (str(intval2)) print (str(intval3)) print (str(floatval1)) print (str(floatval2)) print (str(floatval3)) print (str(strval1)) print (str(strval2)) print (str(strval3)) # No error here
true
228b9a2c9ac1243c4212c38ff0527f750b4cf957
sarahvestal/ifsc-1202
/Unit 3/03.04 Digits In Ascending Order.py
401
4.25
4
#Given a three-digit integer, print "YES" if its digits are in ascending order left to right, print "NO" otherwise. #Enter a Number: 123 #YES #Enter a Number: 132 #NO number = int(input("Enter a three-digit integer: ")) onedigit = int(number % 10) tendigit = int(number % 100 / 10) hundreddigit = int(number % 1000 / 100) if hundreddigit < tendigit < onedigit: print("YES") else: print("No")
true
3e87dcf99a937ea447d8a9ef59cc38fd23b5f5a3
sarahvestal/ifsc-1202
/Unit 1/content/01.00.03 Python Variables.py
711
4.5625
5
# A variable is created the moment you first assign a value to it. x = 5 y = "John" print(x) print(y) # Variables do not need to be declared with any particular type and # can even change type after they have been set. x = 4 # x is of type integer print(x) x = "Sally" # x is now of type string print(x) # String variables can be declared either by # using single or double quotes: x = "John" print(x) # is the same as x = 'John' print(x) # Python allows you to assign values to multiple variables in one line: x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) # And you can assign the same value to multiple variables in one line: x = y = z = "Orange" print(x) print(y) print(z)
true
c9fca2f36659c1a23c148ce56cc9b02969a6286d
sarahvestal/ifsc-1202
/Unit 2/02.02 Two Digits.py
361
4.25
4
#Enter a two digit number and print out its digits separately. #Be sure to use to .format method to create your output. #Enter a Number: 17 #Ones Digit: 7 #Tens Digit: 1 number = int(input("Enter a two digit number: ")) onedigit = number % 10 print ("Ones Digit: {}".format(onedigit)) tendigit = int(number % 100 / 10) print ("Tens Digit: {}".format(tendigit))
true
1f17bd5f45a96d8215f9ae97434b5a69083868d8
gr8lady/Discrete_Math
/RSA_algoritmo.py
1,915
4.28125
4
"""" funcion de encriptacion usando RSA """ valor_de_p = int(input("introduzca el valor de p: ")) valor_de_q = int(input("introduzca el valor de q: ")) llave_publica = valor_de_p * valor_de_q print("la llave publica es: ", valor_de_p, "*", valor_de_q, "= ", llave_publica) numero_evaluar = (valor_de_p -1) *(valor_de_q -1) print("numero a evaluar es (p-1)*(q-1): ", numero_evaluar) contador = 0 while contador < numero_evaluar : numeros_contenidos =0 while numeros_contenidos < numero_evaluar: es_primo_relativo = (numeros_contenidos * contador) % numero_evaluar if es_primo_relativo == 1 : print( "mod (", contador,"*" ,numeros_contenidos,"," ,numero_evaluar, ") =",es_primo_relativo,"es numero primo relavivo de", numero_evaluar) numeros_contenidos = numeros_contenidos +1 contador = contador +1 valor_de_e = int(input("introduzca el valor de que se aun primo relativo e: ")) residuo_llave_privada = numero_evaluar % valor_de_e print("residuo de la llave privada = ", residuo_llave_privada) cociente_llave_privada = round(numero_evaluar / valor_de_e) print("cociente de la llave privada = ", cociente_llave_privada) es_primo_relativo =0 contador =0 while contador < numero_evaluar : numeros_contenidos =0 while numeros_contenidos < numero_evaluar: es_primo_relativo = (numeros_contenidos * contador) % numero_evaluar if es_primo_relativo == 1 and contador == valor_de_e: print( "mod (", contador,"*" ,numeros_contenidos,"," ,numero_evaluar, ") =",es_primo_relativo,"la llave privada es: ", numeros_contenidos) llave_privada= numeros_contenidos numeros_contenidos = numeros_contenidos +1 contador = contador +1 print("la llave privada es: ", llave_privada) print("la llave publica pq es: ", llave_publica) print("la llave publica e es: ", valor_de_e)
false
bbf7baa9d8e9fb7193f852aca03762cb4d39f3cf
sarahccleary12/CodingBat
/Warmup1_PYTHON/front3.py
447
4.28125
4
''' PROMPT Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. ''' def front3(str): if len(str) < 3: return str*3 return str[0:3]*3 ''' Unlike Java, Python allows you to return a repeated string by multiplying it. Line 11 is essentially the same as typing... --- return str + str + str '''
true
18addf92ea03beeadbbd728abf9c4d3599823719
haeke/datastructure
/clockangle.py
534
4.3125
4
""" calculate the angle between the two hands on a clock """ def clockangle(hours, mins): #get the minute hand value minutehand = 6 * mins hourhand = 0.5 * ( 60 * hours + mins) #angle is the absolute value of hourhand - minutehand angle = abs(hourhand - minutehand) #subtract the angle from 360 if the angle is larger than 180 so that it is represented on the opposite side if angle > 180: return 360 - angle else: return angle print "------------------" print clockangle(2, 30)
true
a0381754f72288ecb305fce15922c62be5329c04
haeke/datastructure
/removecharacters.py
676
4.28125
4
""" write a function to return a string with all the characters from an array using a hash table makes it easier to compare the characters against the word we want to check it against """ def removecharacters(word, characters): #create an empty hashtable to store characters hashtable = {} #populate the hash table with the word for c in word: hashtable[c] = True #loop through the steing and check if the charcter exists in the hash table, if it does we do not add it result = '' for c in characters: if c not in hashtable: result += c return result print removecharacters(["r","w","e"], "hello everybody")
true
771034b27e7766663dbf7ef9d8f4eda22428f6aa
gragragrao/training
/training2.py
2,484
4.125
4
# リスト # 練習も兼ねて例外処理を使っています。 # 問題 1 class MyException(Exception): pass def get_average(a): try: if len(a) == 0: raise MyException("list is empty.") average = sum(a) / len(a) return average except MyException as msg: return msg print(get_average([1.3, 2.2, 10.3, 4.3])) # >>> 4.525 print(get_average([])) # >>> list is empty. ''' 正解です。 例外使ってるのいいですね。 ただ、自分で if else の文で例外飛ばすなら、実質if else だけで書けるのでtryを使わない方がシンプルです。 例外を正しく使ってカッコよくかくなら、 def get_average(a): try: average = sum(a) / len(a) return average except Exception as msg: return msg がbetterです。なぜなら a = []  のとき、len(a)が0なので、 average = sum(a) / len(a) で数字を0で割るというでマジな例外が発生して、そいつをキャッチしてくれるからです。 ''' # 問題 2 def get_varianace(a): try: if len(a) == 0: raise MyException("list is empty.") sum_2 = 0 for i in a: sum_2 += (i - get_average(a)) ** 2 var = sum_2 / len(a) return var except MyException as msg: return msg print(get_variance([1.3, 2.2, 10.3, 4.3])) # >>> 12.301875000000003 print(get_variance([])) # >>> 0 ''' 正解です。 変数名にも気を遣いましょう aという変数名はパッと見なんなのかよくわからないので、 型を連想させる名前がよいです。int_listとか 一文字がよければ、リストならlとかが通例。 ''' ''' # scoutyで実際に使っている get varianceはこちら。 def get_variance(l): average = get_average(l) return get_average([(e - average)**2 for e in l]) # ちなみに上級レベルの質問ですが、 def get_variance(l): return get_average([(e - get_average(l))**2 for e in l]) # と書かないのは何故かわかりますか? (もちろん正常に動きます) ''' # 問題 3 def remove_overlap(a): a = list(set(a)) return a print(remove_overlap([1, 2, 4, 2, 4, 9, 4, 8])) # >>> [1, 2, 4, 9, 8] print(remove_overlap(["hoge", "foo", "hoge", "bar", "foo"])) # >>> ["hoge", "foo", "bar"] ''' 正解! def remove_overlap(a): return list(set(a)) の方がシンプルでいいですね '''
false
e5209804d4b8e8d87b4c6a607cfb09ab4c665726
oliviamthomas/comp110-21f-workspace
/lessons/dictionaries.py
1,172
4.53125
5
"""Demonstrations of dictionary capabilities.""" # Declaring the type of a dictionary schools: dict[str, int] # Initialize to an empty dictionary schools = dict() # Set a key-value pairing in the dictionary schools["UNC"] = 19_400 schools["Duke"] = 6_717 schools["NCSU"] = 26_150 # Print a dictionary literal representation print(schools) # Access a value by its key -- "lookup" print(f"UNC has {schools['UNC']} students") # Remove a key-value pair from a dictionary # by its key schools.pop("Duke") # Test for the existence of a key if "Duke" in schools: print("Found the key 'Duke' in schools") else: print("No key 'Duke' in schools") # Update / Reassign a key-value pair schools["UNC"] = 20_000 schools["NCSU"] += 200 print(schools) # Demonstration of dictionary literals # Empty dictionary literal schools = {} # Same as dict() print(schools) # Alternatively, initialize key-value pairs schools = {"UNC": 19_400, "Duke": 6_717, "NCSU": 26_150} print(schools) # What happens when a key does not exist? # print(schools["UNCC"]) # Example looping over the keys of a dict for key in schools: print(f"Key: {key} -> Value: {schools[key]}")
true
71d9353bbe6c3c68ee5b169ff9b60944b0992962
oliviamthomas/comp110-21f-workspace
/exercises/ex06/dictionaries.py
1,674
4.125
4
"""Practice with dictionaries.""" __author__ = "730225468" def main() -> None: """Start of the functions.""" print(invert({"Olivia": "Colton", "Emily": "Bryan"})) print(favorite_color({"Olivia": "Blue", "Colton": "Blue", "Emily": "Pink", "Bryan": "Green"})) print(count(["Olivia", "Colton", "Olivia", "Bryan"])) def invert(a: dict[str, str]) -> dict[str, str]: """Invert keys and values in a dictionary.""" result: dict[str, str] = {} for key in a: value = a[key] if value in result: raise KeyError("The two keys cannot be the same") result[value] = key return result def favorite_color(input: dict[str, str]) -> str: """Results in the color that appears most frequently.""" color_counts: dict[str, int] = {} for person in input: color = input[person] if color not in color_counts: color_counts[color] = 1 # adding new row else: color_counts[color] += 1 # adding one to the value of the row that is already there maximum: int = 0 # lowest possible number winning_color: str = "" for key in color_counts: if color_counts[key] > maximum: maximum = color_counts[key] winning_color = key return winning_color def count(x: list[str]) -> dict[str, int]: """Results in a count of how often a value appears in the list.""" result: dict[str, int] = {} item: str = "" for item in x: if item not in result: result[item] = 1 else: result[item] += 1 return result if __name__ == "__main__": main()
true
b9e42e0a23c80e0eb480725a0698ff98b4be5215
TobyCCC/MystanCodeProJects
/SC101_Projects/SC101_Assignment0/coin_flip_runs.py
1,102
4.34375
4
""" File: coin_flip_runs.py Name: ----------------------- This program should simulate coin flip(s) with the number of runs input by users. A 'run' is defined as consecutive results on either 'H' or 'T'. For example, 'HHHHHTHTT' is regarded as a 2-run result. Your program should stop immediately after your coin flip results reach the runs! """ import random as r def main(): """ TODO: This program is a coin flipping simulator. It will stop when the number or runs is reached. """ print("Let's flip a coin!") count = 0 result = "" flip_origin = "" # Store the result one round before. switch = 0 # Determine if a run includes more than two "H" or "T" num_run = int(input("Number of runs: ")) while True: if count == num_run: break flip_num = r.randint(0,1) # Random if flip_num == 0: flip = "H" else: flip = "T" result += flip if flip_origin == flip: if switch == 0: switch = 1 count += 1 else: switch = 0 flip_origin = flip print(result) ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
96c0a28097188ac21d2e072151140fbf60242c0e
Arifulhaque313/Basic-Python-Code-practice
/Dictionary.py
852
4.21875
4
new_dictionary={ "name":"sajib","age":24,"salary":6000} print (new_dictionary) print(new_dictionary.get("age")) print("My name is " +new_dictionary["name"]) new_dictionary.pop("age") print ("After remove age : "+str(new_dictionary)) #print all the keys print(new_dictionary.keys()) #print all the values print(new_dictionary.values()) new_variable=10 new1_dictionary={"name":new_variable} print(new1_dictionary) sajib={ "name":"sajib", "age":30, "salary":6000 } print("all the elements of the list is : " +str(sajib)) updateAge={"age":22} sajib.update(updateAge) print("After update all the elements of the list is : " +str(sajib)) print("Show me all the keys of the dictionary is = "+str(sajib.keys())) print("Show me all the values of the dictionary is = "+str(sajib.values()))
true