blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3f6987166d915a0a0426f5aeb3ef776c614c41d4
cmirza/FullStackDay-PdxCodeGuild
/01 - Python/lab21-peaks_and_valleys_v3.py
1,754
4.15625
4
''' Lab 21 - Peaks and Valleys Calculate accumulated 'water'. ''' # define peaks function def peaks(num): peak_list = [] # define peak list for i in range(1, len(num) - 1): if (num[i] > num[i - 1]) & (num[i] > num[i + 1]): peak_list.append(i) return peak_list # define valleys function def valleys(num): valley_list = [] # define valley list for i in range(1, len(num) - 1): if (num[i] < num[i - 1]) & (num[i] < num[i + 1]): valley_list.append(i) return valley_list # define peaks and valleys function def peaks_and_valleys(num): peak_and_valley_list = [] # define combined peak for i in range(1, len(num) - 1): if (num[i] > num[i - 1]) & (num[i] > num[i + 1]): peak_and_valley_list.append(i) for i in range(1, len(num) - 1): if (num[i] < num[i - 1]) & (num[i] < num[i + 1]): peak_and_valley_list.append(i) return sorted(peak_and_valley_list) # define ascii barchart function def ascii_barchart(num): for x in range(max(num), 0, -1): # start loop for x coord print(end=' ') # add extra space without newline for alignment for y in num: # start loop for drawing y coord if y >= x: # if value of y is greater than or equal to x, print 'X' and suppress newline with space print("X ", end=' ') else: # otherwise print ' ' print(" ", end=' ') print() # print newline print(num) # print number list # define list of numbers data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] # pass list to functions and print results ascii_barchart(data) print(peaks(data)) print(valleys(data)) print(peaks_and_valleys(data))
false
ebbdf9c0191d12ecaa58c56a2dcce2b1bef2ac40
ChanduSharma/Data-structures-in-python
/stack/stackreverse.py
982
4.15625
4
# Function to reverse the stack using push and pop operations import random class myStack: def __init__(self): self.array = [] def is_empty(self): return self.array == [] def push(self, val): self.array.append(val) def pop(self): if not self.is_empty(): return self.array.pop() def insert_at_bottom(my_stack, val): if my_stack.is_empty(): my_stack.push(val) else: temp = my_stack.pop() insert_at_bottom(my_stack, val) my_stack.push(temp) def reverse_stack(my_stack): if not my_stack.is_empty(): data = my_stack.pop() reverse_stack(my_stack) insert_at_bottom(my_stack, data) my_stack = myStack() for i in range(10): my_stack.push(random.randint(1,100)) # Not a right way but stack ADT doesnot have a method to print all elements # inside it and poping all will require creating new stack to push those. print(*my_stack.array) reverse_stack(my_stack) print(*my_stack.array)
true
52d16687f1250067220533300f7395f3a4647fb7
ChanduSharma/Data-structures-in-python
/stack/mystack.py
652
4.4375
4
#!/usr/bin/env python3 # Stack as an abstract Data Type class MyStack: def __init__(self): self._mylist = list() def push(self, val): self._mylist.append(val) def pop(self): if self._mylist: return self._mylist.pop(0) else: raise StackEmptyException('Stack is Empty.') def top(self): return self._mylist[0] def stack_size(self): return len(self._mylist) def is_empty_stack(self): return self._mylist == [] if __name__ == '__main__': my_stack = MyStack() my_stack.push(2) my_stack.push(34) my_stack.push(22) my_stack.push(21) my_stack.push(12) print(my_stack.top()) my_stack.pop() print(my_stack.top())
false
d6a77e0922d812c89f717adc624923f9a8c7c505
A-Leus/quantum_network_routing
/notebooks/new_folder/helper.py
1,200
4.375
4
""" Applies func to each element of tup and returns a new tuple. >>> a = (1, 2, 3, 4) >>> func = lambda x: x * x >>> map_tuple(func, a) (1, 4, 9, 16) """ def map_tuple(func, tup): new_tuple = () for itup in tup: new_tuple += (func(itup),) return new_tuple """ Applies func to each element of tup and returns a new tuple. >>> a = (1, 2, 3, 4) >>> func = lambda x: x * x >>> map_tuple(func, a) (1, 4, 9, 16) """ def map_tuple_gen(func, tup): return tuple(func(itup) for itup in tup) ''' Returns the mean of an iterable (e.g. list of numbers) ''' def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) ''' Add or update a key-value pair to the dictionary ''' def add_tuple_to_dictionary(dictionary: dict, tup: tuple): k, v = tup if k in dictionary: dictionary[k] += v else: dictionary[k] = v return None ''' Add or create elements of a dictionary to another dictionary ''' def add_dictionary_to_dictionary(dictionary: dict, other_dictionary: dict): for k,v in other_dictionary.items(): if k in dictionary: dictionary[k] += v else: dictionary[k] = v return None
true
c8f34fab72545a75c3b3225e607dd489fefd071f
ltbatis/2020-30-days-of-Python
/Days-2-3_Lists_Dictionaries_Tuples_Loops/lists.py
471
4.125
4
abc = "some string" print(abc+abc) list = ["some list",123,"another string"] print(list) list.append("one more") print (list) list.pop() print(list) print("Lenght of list: {}".format(len(list))) print("Length of LUCAS: {}".format(len("LUCAS"))) print("First (0 position) item of list: {}".format(list[0])) print("Second (1st position) item in list: {}".format(list[1])) abc = [1,2,3] print("ABC List: {}".format(abc)) print("Last item from ABC: {}".format(abc[-1]))
true
aab46a6b64497d77abc1cd6bdc11602fbc5d2a73
SimonCK666/pythonBasic
/python_6hours/PythonGrammer/Classes.py
643
4.21875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- numbers = [1, 2, 3] class Point: def __init__(self, x, y): self.x = x self.y = y def move(self): print("move") def draw(self): print("draw") point = Point(10, 20) print(point.x) # point1 = Point() # point1.x = 10 # point1.y = 29 # print(point1.x) # point1.draw() # point2 = Point() # point2.x = 1 # print(point2.x) print('------------------') class Person: def __init__(self, name,): self.name = name def talk(self): print(f"Hi, I am {self.name}") john = Person("John Smith") john.talk() bob = Person("Bob Smith") bob.talk()
false
04e37f74ff75c3842b091f0ce8d062f56a65ec1a
cs-richardson/table-reservation-4-3-9-kdoan21
/tableReservation.py
315
4.25
4
#Code that checks if a user has a reservation that matches a string variable #and tells them if they do or not userName = input("Hello, what is your name? ") reservationName = "Jake" if userName == "Jake": print("Hello, your table is this way.") else: print("Sorry, you don't have a reservation with us.")
true
fcf3ac62b289a8722cfaf24f0e103033d10ac0fe
zannatul25/python
/Basic/worked_hours.py
1,437
4.375
4
#Write a program which asks the user to enter an integer 'n' which would be the total numbers of hours the user worked in a week and calculates and prints the total amount of money the user made during that week. If the user enters any number less than 0 or greater than 168 (n < 0 or n > 168) then your program should print INVALID #Assume that hourly rate for the first 40 hours is $8 per hour. #Hourly rate for extra hours between 41 and 50 (41 <= n <= 50 ) is $9 per hour. #Hourly rate for extra hours greater than 50 is $10 per hour. #Here are a few examples: # if the user enters -5, then your program should print "INVALID" # if the user enters 34, then your program should print "YOU MADE 272 DOLLARS THIS WEEK" # if the user enters 45, then your program should print "YOU MADE 365 DOLLARS THIS WEEK" # if the user enters 67, then your program should print "YOU MADE 580 DOLLARS THIS WEEK" user_input = int(input("Enter hours in a week: ")) def worked_hours(n): total_pay = 0 if n < 0 or n > 168: return "INVALID" elif n <= 40: total_pay += n * 8 return "YOU MADE {0} DOLLARS THIS WEEK".format(total_pay) elif n <= 50: total_pay += 40 * 8 + (n - 40) * 9 return "YOU MADE {0} DOLLARS THIS WEEK".format(total_pay) else: total_pay += 40 * 8 + 10 * 9 + (n - 50) * 10 return "YOU MADE {0} DOLLARS THIS WEEK".format(total_pay) result = worked_hours(user_input) print(result)
true
196df1612adb2e22b55368c770c73dd41c6f702e
zannatul25/python
/Basic/while_loop_factorial.py
485
4.4375
4
#Write a program using while loop, which asks the user to type a positive integer, n, and then prints the factorial of n. A factorial is defined as the product of all the numbers from 1 to n (1 and n inclusive). For example factorial of 4 is equal to 24. (because 1*2*3*4=24) user_input = input("Enter positive number: ") number = int(user_input) def get_fact(n): fact = 1 while n > 0: fact *= n n -= 1 return fact result = get_fact(number) print(f"{number}! = {result}")
true
89713f3531caea9fa83cd01cfa4b5fa71f17c1f4
sonal06/Data-Structures-and-Algorithms
/Find the minimum number.py
759
4.1875
4
#Chapter 2 # Find teh minimum number #finding minimum number in the list #Method 1: #Linear method smallest=iList[0] len(iList) for i in range(1, len(iList)): if smallest > iList[i] : print (smallest, iList[i]) smallest = iList[i] print (smallest) #Method 2: #Compare each number to every other number on the list O(n2) user_input = input("Enter a list of numbers separated by commas") iList = user_input.split(",") minimum = iList[0] for i in range (0, len(iList)): issmallest= True for j in range(0,len(iList)): print (iList[i],iList[j]) if iList[i] > iList[j]: issmallest = False if issmallest: minimum = iList[i] print ("smallest number is:", minimum)
true
d320eee83b6c7bc909691e4859157b6ed867ba6d
ASpoonyBard3/homework
/class1.py
854
4.21875
4
# Doesn't calculate bizz = 0 # create var to iterate over in while loop while bizz < 101: # start while loop, it needs to stop after 100, not at 100, so set to 101. #def multiple of 3 if (bizz % 3) == 0: #if bizz is equal to 0, then using mods to compare bizz to 3 to determine multiple, remember it's equals (==) 0 not different (!=)to 0 print ("Buzz") bizz = bizz +1 #iterate + 1 to bizz, if statement terminates elif (bizz % 5) == 0: #elif is bizz equal to a multiple of 5? print ("Fizz") bizz = bizz + 1 #iterate + 1 to bizz, elif statement terminates else (bizz % 5) == 0 and (bizz % 3) == 0: print ("Fizzbuzz") bizz = bizz +1 #iterate + 1 to bizz, if statement terminates, loops begins #exception handling, make sure any other #else: # print (bizz) #bizz = bizz +1
true
52e6f863b6641f4266dd59bf0624112929016a70
dipamsen/Python-Class-Projects
/firstclass.py
310
4.1875
4
# Comment input_text = input("Enter some text: ") print("You inputted: \n" + input_text) char_count = 0 word_count = 1 for ch in input_text: if(ch == ' '): word_count += 1 else: char_count += 1 print("No of Characters = " + str(char_count)) print("No of Words = " + str(word_count))
true
6aea0666ce92e953c2d8c704211d03bdf3ac3917
mishakuzma/daily-programs
/96A-RepulsionForce.py
1,603
4.5625
5
class Particle: 'Class defining what a particle is by mass, x_pos and y_pos' def __init__(self, mass, x, y): self.mass = mass self.x = x self.y = y def displayInfo(self): print("Mass: {} X-Pos: {} Y-Pos: {}".format(\ str(self.mass), str(self.x), str(self.y))) """ partDefine() defines a particle based on mass, x, and y position.""" def partDefine(): while True: part_in = str(input("Please input a set of three\ numbers. The first should be mass, 2nd is x-position,\ 3rd is y-position: ")) part_process = part_in.split() particle = Particle(int(part_process[0]), \ int(part_process[1]), int(part_process[2])) print("Particle: ") particle.displayInfo() if str(input("Is this information correct? (y/n)")) == "y": break return particle """ distance(part1, part2) consumes two particles and produces a number corresponds to the distance between those two particles.""" def distance(part1, part2): return ((((part2.x - part1.x)**2) + ((part2.y - part1.y) ** 2))\ **(1/2)) """ main() consumes two inputs in row form. Each row must have three numbers. The first represents a particle's mass, second represents particle x-position, and third represents particle y-position. The repulsion is determined by a formula represented as such: repul = (mass of 1 * mass of 2) / (distance ^ 2) """ def main(): while True: particle1 = partDefine() particle2 = partDefine() print("Repulsion force is...") print(str(((particle1.mass * particle2.mass) / \ distance(particle1, particle2)))) if (input("Do you wish to continue? (y/n)")) == "n": break main()
true
83cd4975761d14bd3de36970cd9608f20c115dc7
mishakuzma/daily-programs
/hard1-238c.py
1,268
4.28125
4
import string, sys, math # tooHigh(top, bottom) consumes 2 numbers called top and bottom # in order to produce a single number which is produced by flooring # the average of top and bottom def guessAdjust(top, bottom): guess = math.floor((top + bottom) / 2) asker(guess, top, bottom) # asker(guess, top, bottom) asks if the computer's guess is correct. # If so, the program closes. If the user says too high, than top and # bottom are fed into guessAdjust(guess, bottom) to get another response # if user says too low, than top and bottom fed into guessAdjust(top, guess). def asker(guess, top, bottom): print("My guess is: " + str(guess)) opinion = raw_input("Is that correct?"); while True: if (opinion == "right"): print("Yay, I win!") sys.exit() elif (opinion == "high"): print("Hmm, let me think.") guessAdjust(guess, bottom) elif (opinion == "low"): print("Okay, let me try again.") guessAdjust(top, guess) else: print("You didn't enter a correct statement.") # start() prints instructions to the user on startup def start(): top = 100 bottom = 1 print("Welcome to guessr! Think of a number between 1 and 100") print("I'll print a number, and you tell me if it's high, low, or right!") asker(50, top, bottom) start()
true
2f31fa79d0e8cecad1eaee277fa574574eeb689b
mgrau/ion_sim
/ion_sim/plot.py
2,105
4.125
4
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation def plot(sim, i=[], dim=0): ''' Plot ion position or velocity as a function of time. Makes a matplotlib call and creates a figure. Parameters ---------- i : array, optional A list of indices of ions to plot. An empty list may be used to plot all ions. dim : int, optional The dimension of the ion state vector to plot. The default is 0, corresponding to the 'x' position. ''' if not i: plt.plot(sim.t, sim.x[dim, :, :].T) else: plt.plot(sim.t, sim.x[dim, i, :].T) plt.xlabel('Time') plt.ylabel(['x Position', 'y Position', 'z Position', 'vx Velocity', 'vy Velocity', 'vz Velocity'][dim]) plt.ticklabel_format(style='sci', axis='both', scilimits=(0, 0)) def animate(ions): # First set up the figure, the axis, and the plot element we want to animate h_axis = 0 v_axis = 1 rmax = np.max(ions.x[:, 0:2, :]) * 1.1 fig = plt.figure() ax = plt.axes(xlim=(-rmax, rmax), ylim=(-rmax, rmax)) points, = ax.plot([], [], 'b.', markersize=20) lines = [ax.plot([], [], 'k-')[0] for _ in range(ions.N)] # plt.ticklabel_format(style='sci', axis='both', scilimits=(0, 0)) def init(): points.set_data([], []) for line in lines: line.set_data([], []) return lines # animation function. This is called sequentially def draw_frame(frame_i): points.set_data(ions.x[h_axis, :, frame_i], ions.x[v_axis, :, frame_i]) for i, line in enumerate(lines): line.set_data(ions.x[h_axis, i, (frame_i - 5):frame_i], ions.x[v_axis, i, (frame_i - 5):frame_i]) return lines anim = animation.FuncAnimation(fig, draw_frame, init_func=init, frames=ions.t.size, interval=(1000 / 60), blit=True, repeat=False) plt.close(fig) return anim
true
f50ed581e053ca29ccf848b3209dc85f47c0dd8c
stewartrowley/CSE110
/Week 4/tempconv.py
414
4.40625
4
# Input the values from the user. fahrenheit = float(input("What is the temprature in Fahrenheit? ")) cel_temp = float(input("What is the tempature in Celsius ")) # Calculating the values. celsius = (fahrenheit - 32) * (5/9) fah_temp = (cel_temp * 9/5) + 32 # The output of the values. print(f"The tempature in Celsius is {celsius:.1f} degrees.") print(f"The tempature in Fahrenheit is {fah_temp:.1f} degrees.")
true
d5ca3e598d2e3969dd917de1c001d90abddca755
stewartrowley/CSE110
/Week 10/cart_demo_group.py
1,366
4.25
4
list_accounts = [] list_balance = [] account_name = "None" print("Enter the names and balances of bank accounts (type: 'quit' when done") while account_name != "quit": account_name = input("What is the name of the account? ") account_name = account_name.lower() if account_name != "quit": account_balance = float(input("what is the balance? ")) list_accounts.append(account_name) list_balance.append(account_balance) print("\nAccount Information:") for x in range(len(list_accounts)): account = list_accounts[x] balance = list_balance[x] print(f"{x}. {account} - ${balance:.2f}") total = sum(list_balance) print(f"\nTotal: ${total:.2f}") average = total / (len(list_balance)) print(f"Average: ${average:.2f}") largest_account = list_balance.index(max(list_balance)) print(f"Highest Balance: {list_accounts[largest_account]} - ${list_balance[largest_account]:.2f}") update_question = input("Would you like to update an account? ") if update_question.lower() == "yes": account_index = int(input("What is the index of the account you wish to update? ")) new_amount = float(input("What is the new amount? ")) list_balance[account_index] = new_amount print("\nAccount Information:") for x in range(len(list_accounts)): account = list_accounts[x] balance = list_balance[x] print(f"{x}. {account} - ${balance:.2f}")
true
c8c18a69f52bb11a48357845c6e15698104f4538
stewartrowley/CSE110
/Week 10/sample_ten.py
1,604
4.1875
4
print("Enter the names and balances of bank accounts (type: quit when done)") names = [] balances = [] name = None # Build the lists while name != "quit": name = input("What is the name of this account? ") if name != "quit": balance = float(input("What is the balance? ")) names.append(name) balances.append(balance) # Display all of the accounts with their balances # Compute the total at the same time. total = 0 print("\nAccount Information:") for i in range(len(names)): print(f"{i}. {names[i]} - ${balances[i]:.2f}") # total += balances[i] # average = total / len(balances) # print() # print(f"Total: ${total:.2f}") # print(f"Average: ${average:.2f}") # # Stretch Challenges: # # Find the highest balance: # highest_name = None # highest_balance = -1 # for i in range(len(names)): # name = names[i] # balance = balances[i] # if balance > highest_balance: # # We have a new highest! # highest_balance = balance # highest_name = name # print(f"Highest balance: {highest_name} - ${highest_balance:.2f}") # change_account = "yes" # while change_account == "yes": # change_account = input("\nDo you want to update an account? ") # if change_account == "yes": # index = int(input("What account index do you want to update? ")) # new_amount = float(input("What is the new amount? ")) # balances[index] = new_amount # # Now print the balances # print("\nAccount Information:") # for i in range(len(names)): # print(f"{i}. {names[i]} - ${balances[i]:.2f}")
true
a8d7a3130ef7846bea2a8e630b5e7f34248ba724
tfudge1/calc
/calculator.py
1,272
4.1875
4
numbers = [] cont = "yes" print("welcome to the calc: ") print(" _____________________") print("| _________________ |") print("| | JO 0. | |") print("| |_________________| |") print("| ___ ___ ___ ___ |") print("| | 7 | 8 | 9 | | + | |") print("| |___|___|___| |___| |") print("| | 4 | 5 | 6 | | - | |") print("| |___|___|___| |___| |") print("| | 1 | 2 | 3 | | x | |") print("| |___|___|___| |___| |") print("| | . | 0 | = | | / | |") print("| |___|___|___| |___| |") print("|_____________________|") op = input("What operation would you like to do? ") while cont == "yes": numbers.append(int(input("what is the next number? "))) cont = input("yes or no, would you like to calculate more numbers? ") if op == "add": sums = 0 for i in numbers: sums += i print(sums) if op == "multiply": mult = 1 for i in numbers: mult *= i print(mult) if op == "subtract": sub = numbers[0] for i in range(1,len(numbers)): sub -= numbers[i] print(sub) if op == "divide": div = numbers[0] for i in range(1,len(numbers)): div /= numbers[i] print(div) if op == "exponents": exp = numbers[0] for i in range(1,len(numbers)): exp **= numbers[i] print(exp) print(numbers)
false
a9e775b7ac602820516ad9254afa8b36eccece41
hanifyogatama/data-structure-and-algorithms
/week1/Python/sum-of-two-digits/aplusb.py
415
4.3125
4
#!/usr/bin/python3 """ Data Structure and Algorithms, Coursera Arslan Ali """ def sum_of_two_digits(a, b): """ sum_of_two_digits() method :param a: :param b: :return: """ return a + b # Press the green button in the gutter to run the script. if __name__ == '__main__': print("\nsum_of_two_digits") a = float(input()) b = float(input()) print(sum_of_two_digits(a, b))
false
9b6a18a5252a5211879e27734d19e8d3142eba0a
AgsKarlsson/day2-bestpractices-1
/matmult.py
1,264
4.15625
4
# Program to multiply two matrices using nested loops import random def generate_matrix(N): # NxN matrix X = [] for i in range(N): X.append([random.randint(0,100) for r in range(N)]) # Nx(N+1) matrix Y = [] for i in range(N): Y.append([random.randint(0,100) for r in range(N+1)]) return (X, Y) def empty_results(): # result is Nx(N+1) result = [] for i in range(N): result.append([0] * (N+1)) return result def insert_results(): #insert_results is by far the slowest part of the script, #this is where I would focus the optimization if possible #What I would like to do is to instead to matrix operations instead of #cycling through all of the values of the matricies. However, #I don't think I can do that without using numpy. # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] def show_results(): for r in result: print(r) N = 10 (X, Y) = generate_matrix(N) result=empty_results() insert_results() show_results()
true
c5a1cabd4390ad9cabaffa867922e03d84d8f752
Hanxiaorong/Python-exercises
/ex29-2.py
765
4.25
4
#raw_input(">") if not False: print True if not True: print False if True or False: print True if True or True: print True if False or True: print True if False or False: print False if True and False: print False if True and True: print True if False and True: print False if False and False: print False if not(True or False): print False if not(True or True): print False if not(False or True): print False if not(False or False): print True if not(True and False): print True if not(True and True): print False if not(False and True): print True if not(False and False): print True
true
9c0b86fb712ce31649e4ef418ac16ba321ffc12e
Fedoseevale/TestPullRequest
/Calculator.py
2,069
4.3125
4
from math import sqrt # Program make a simple calculator # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y #This function multiples two numbers def mult(x,y): return x*y #This function divides two numbers def div(x,y): return x/y #This function gives the squareroot of a number def squareroot(x): return sqrt(x) print("I rul the WORLD") print("Select operation.") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. SquareRoot") print("6. Power") print("\n") while True: # Take input from the user choice = input("Select choice(1/2/3/4/5/6): ") # Check if choice is one of the four options if choice in ('1', '2', '3', '4','5','6'): if choice == '1': num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print(str(num1), "+", str(num2), "=", str(add(num1, num2))) elif choice == '2': num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print(str(num1), "-", str(num2), "=", str(subtract(num1, num2))) elif choice == '3': num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print(str(num1), "*", str(num2), "=", str(mult(num1, num2))) elif choice == '4': num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print(str(num1), "/", str(num2), "=", str(div(num1, num2))) elif choice == "5": num1 = float(input("Enter the number: ")) print("SqareRoot of " + str(num1) + " is " + str(sqrt(num1))) elif choice == "6": num1 = float(input("Enter base number: ")) num2 = float(input("Enter power... UNLIMITED POWER number: ")) print(str(num1) + " power " + str(num2) + " =" + " "+str(num1 ** num2)) break else: print("Invalid Input")
true
53980dd444eab0af726ed11b6bcf6e858f9790c0
anish29292/travis_sample
/src/mypackage_two/pandas_math.py
650
4.28125
4
import pandas as pd import numpy as np def create_empty_dataframe(new_column_list, num_rows): """ Creates a new dataframe filled with zeroes from a specified list and number of rows. Args: new_col_list (object): List of column names. num_rows (int): Number of rows you want the new table to have. Returns: df: returns a pandas dataframe with specific column names and number of rows. """ col_list = new_column_list num_cols = len(new_column_list) fill_with_zeroes = np.zeros(shape=(num_rows, num_cols)) new_df = pd.DataFrame(fill_with_zeroes, columns=[col_list]) return new_df
true
0817f7828b4a89385a2e3161582c4ea2ce86eb77
saryamane/python_design_patterns
/decorator/func_inside_func_decorator.py
570
4.25
4
#!/usr/bin/python def greet(name): def get_message(): return "Hello " result = get_message()+name return result print greet("Samir") def greet2(name): return "Hello " + name def call_func(func): other_name = "Another function" return func(other_name) print call_func(greet2) # Functions can also return another functions. def compose_greet_func(): def get_message(): return "Hello there!" return get_message greet = compose_greet_func() print greet() # Inner functions can have access to the enclosing scope. # They are commonly known as closure.
true
d6b8a752e44b5a96ebce95cdbe20331bfc1e03ec
leetrent/python3
/exercises/functions/list_manipulation.py
588
4.15625
4
def list_manipulation(list, command, location, value=0): if command == "remove": if location == "end": return list.pop() if location == "beginning": return list.pop(0) if command == "add": if location == "beginning": list.insert(0, value) return list if location == "end": list.append(value) return list print(list_manipulation([1,2,3], "remove", "end")) # 3 print(list_manipulation([1,2,3], "remove", "beginning")) # 1 print(list_manipulation([1,2,3], "add", "beginning", 20)) # [20,1,2,3] print(list_manipulation([1,2,3], "add", "end", 30)) # [1,2,3,30]
false
b1906574b07513229baa4d31d5a526cde9f3e090
shanbumin/py-beginner
/011-list/demo03/main.py
428
4.34375
4
#如果想逐个取出列表中的元素,可以使用for循环的,有以下两种做法。 #方法一: items = ['Python', 'Java', 'Go', 'Kotlin'] for index in range(len(items)): print(items[index]) #方法二: #items = ['Python', 'Java', 'Go', 'Kotlin'] for item in items: print(item) print('---------------------------------------------------------------------------------------------------------------')
false
88639fe6592d04f5e0a81a1061a7e5c3db0ce379
crazcalm/Py3.4_exploration
/DataStructures/Trees/ListOfLists.py
2,896
4.28125
4
""" List of Lists Representation: ----------------------------- Need Functions: --------------- - BinaryTree() - getLeftChild() - getRightChild() - setRootVal() - getRootVal() - insertLeft(val) - insertRight(val) Overview: --------- In a tree represented by a list of lists, we will begin with Python's list data structure and write the functions defined above. Although writing the interface as a set of operations on a list is a bit different from the other abstract data types we have implemented, it is interesting to do so because it provides us with a simple recursive data structure that we can look at and examine directly. Basics: ------- In a list of lists tree, we will store the value of the root node as the first element of the list. The second element of the list will itself be a list that represents the left subtree. The third element of the list will be another list that represents the right subtree. """ def BinaryTree(r): """ Root of the Binary Tree. """ return [r, [], []] def insertLeft(root, newBranch): """ Inserts a new subtree at root[1] and, if an the root has an existing subtree in that location, that subtree is now the subtree of the new branch that you are inserting. """ t = root.pop(1) if len(t)>1: root.insert(1,[newBranch, t, []]) else: root.insert(1, [newBranch, [], []]) return root def insertRight(root, newBranch): """ Inserts a new subtree at root[2] and, if an the root has an existing subtree in that location, that subtree is now the subtree of the new branch that you are inserting. """ t = root.pop(2) if len(t)>1: root.insert(2,[newBranch, [], t]) else: root.insert(2, [newBranch, [], []]) return root def getRootVal(root): return root[0] def setRootVal(root, newVal): root[0] = newVal return root def getLeftChild(root): return root[1] def getRightChild(root): return root[2] if __name__ == "__main__": """ I just want to know that this works. """ print("List of Lists Representation Of a Binary List:") r = BinaryTree(3) print("Tree Root\n",r) print("\nInserting left subtree\n", insertLeft(r,4)) print("\nInserting left subtree\n", insertLeft(r, 5)) print("\nInserting right subtree\n", insertRight(r,6)) print("\nInserting right subtree\n", insertRight(r,7)) print("\nGetting the left Child of Root (as l):") l = getLeftChild(r) print("\nRoot's Left Child\n",l) print("\nSetting the root value for Child l,",setRootVal(l,9)) print("\nPrinting out the whole tree\n", r) print("\nInserting a left subtree in l",insertLeft(l, 11)) print("\nPrinting out the whole tree\n", r) print("\nGetting the right child of Root", getRightChild(r))
true
0f599ef0bc581a7156a07a71b92fd318b419e01f
caravan4eg/python_kata
/binary_trees.py
1,496
4.1875
4
""" https://www.hackerrank.com/challenges/30-binary-trees/problem A level-order traversal, also known as a breadth-first search, visits each level of a tree's nodes from left to right, top to bottom. You are given a pointer, , pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree. Hint: You'll find a queue helpful in completing this challenge. Sample Input 6 3 5 4 7 2 1 Sample Output 3 2 5 1 4 7 """ import sys class Node: def __init__(self, data): self.right = self.left = None self.data = data class Solution: def insert(self, root, data): if root == None: return Node(data) else: if data <= root.data: cur = self.insert(root.left, data) root.left = cur else: cur = self.insert(root.right, data) root.right = cur return root def levelOrder(self, root): # Write your code here queue = [root] if root else [] while queue: node = queue.pop() print(node.data, end=" ") if node.left: queue.insert(0, node.left) if node.right: queue.insert(0, node.right) T = int(input()) myTree = Solution() root = None for i in range(T): data = int(input()) root = myTree.insert(root, data) myTree.levelOrder(root)
true
0972c56c1e878725a4c75f119c2b1a9866dc56e8
caravan4eg/python_kata
/automate_the_boring_stuff_with_python/mad_libs.py
1,564
4.6875
5
""" Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this: The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. The program would find these occurrences and prompt the user to replace them. Enter an adjective: silly Enter a noun: chandelier Enter a verb: screamed Enter a noun: pickup truck The following text file would then be created: The silly panda walked to the chandelie """ def get_content_from(file): # Get content from file with open(file, 'r') as mad_libs_txt: content = mad_libs_txt.read() return content def change(content): # Ask new content noun = input('Введите существительное: ') adj = input('Введите прилагательное: ') verb = input('Введите глагол: ') # Change content content = content.replace('ADJECTIVE', adj) content = content.replace('VERB', verb) content = content.replace('NOUN', noun) return content def write_content_to(file, new_content): # Write new content to file with open(file, 'a') as mad_libs_txt: mad_libs_txt.write(new_content) def main(): file = '/home/alex/dev/python_kata/automate_the_boring_stuff_with_python/mad_libs.txt' content = get_content_from(file) new_content = change(content) write_content_to(file, new_content) if __name__ == "__main__": main()
true
9e2714264ed2604eb155f94d1cc241477140b016
caravan4eg/python_kata
/regex_email.py
853
4.3125
4
"""Task Consider a database table, Emails, which has the attributes First Name and Email ID. Given N rows of data simulating the Emails table, print an alphabetically-ordered list of people whose email address ends in @gmail.com. Sample Input 6 riya riya@gmail.com julia julia@julia.me julia sjulia@gmail.com julia julia@gmail.com samantha samantha@gmail.com tanya tanya@gmail.com Sample Output julia julia riya samantha tanya """ import math import os import random import re import sys if __name__ == '__main__': N = int(input()) pattern = '@gmail.com' gmail_users = [] for N_itr in range(N): firstNameEmailID = input().split() firstName = firstNameEmailID[0] emailID = firstNameEmailID[1] if re.search(pattern, emailID): gmail_users.append(firstName) print(gmail_users) for user in sorted(gmail_users): print(user)
true
a4afaa1a154a5e39fce8ec9213d500eea06cfb1d
zl19971127/study-ing-code
/05-数据类型.py
886
4.25
4
# 整型: 整数 int num = 10 # print(num1) print(type(num)) # 浮点型: 小数 float num_1 = 30.0 print(type(num_1)) # 字符串 str -- 但凡带引号的数据都是字符串数据;所有字符串数据都要有引号 str1 = 'daqiu' print(type(str1)) # 认识的即可 # 布尔型 bool: 只有两个值 True 和 False(boolean); 判断真假 a = True print(type(a)) # 列表: list, 可以一次性存储多个数据 b = [10, 20, 30] print(type(b)) # 字典dict xx 对应 xx 键key对应值value. k对应v k:v 姓名是xx 年龄是xx 手机号是xxx # 字典 1. k:v(键值对);2. 一个字典可以放多个键值对,各个键值对用逗号隔开 c = {"name": "daqiu", "age": 18} print(type(c)) # 元组 tuple; 存储不能修改的数据 d = (10, 20, 30) print(type(d)) # 集合 set 数据不允许重复 e = {10, 20, 30, 20} print(type(e)) print(e)
false
44b2aa966d019443142fa947c54b6bddec3d824c
Svetlana0603/My_python
/1.syntax/2.if_els.py
2,227
4.15625
4
# *** логические операторы НЕ (NOT), И (AND), ИЛИ (OR) *** x = True y = False # оператор НЕ # print(not x) # оператор И - возвращает True только если значения обеих # переменных равны True res = x and y # res = True and True # оператор ИЛИ - возвращает False только если значения обеих # переменных равны False res = True or True # print(res) # *** Условные операторы *** # if False: # c = "Hello!" # print(c) a = -1 # if a > 0: # print("больше 0") # elif a == 0: # print("равно 0") # else: # print("меньше 0") b = "Г" if b == "A": c = "равно A" elif b == "Б": c = "равно Б" elif b == "B": c = "равно B" else: c = "я это не знаю" # print(c) # *** условная задача "термостат" # текущая температура cur_temp = 7 # целевые температуры (установленная через ручку регулятора) tar_temp_1 = 27 tar_temp_2 = 10 # дополниетльное условие - "зависимость от присутствия людей" z = False # логика термостата if z == True and cur_temp < tar_temp_1: print("Включено нагрева до {tar_temp_1}") elif z == False and cur_temp < tar_temp_2: print(f"Включено нагрева до {tar_temp_2}") else: print("Нагревание выключено") print("Ноль в качестве знака операции" "\nзавершит работу программы") while True: s = input("Знак (+,-,*,/): ") if s == "0": break if s in ("+", "-", "*", "/"): x = float(input("x=")) y = float(input("y=")) if s == "+": print("%.2f" % (x+y)) elif s == "-": print("%.2f" % (x-y)) elif s == "*": print("%.2f" % (x*y)) elif s == "/": if y != 0: print("%.2f" % (x-y)) else: print("Деление на ноль!")
false
d4964c3ae3d0aa0994837d5bafb4efa6ea9738a1
jddelia/automate-the-boring-stuff
/tablePrinter.py
724
4.375
4
''' This program takes lists of strings and prints the contents of each list in columns. Assignment detail can be found at: https://automatetheboringstuff.com/chapter6/, Table Printer assignment. ''' tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def table_printer(list): col_width = [0] * len(list) for i in range(len(list)): col_width[i] = len(sorted(list[i], key=len, reverse=True)[0]) print(col_width) for i in range(len(list[0])): for n in range(len(list)): print(list[n][i].rjust(col_width[n]), end=" ") print() table_printer(tableData)
true
03e3b69607090d991c6c7a064fdad9f2b45fd8a6
narendra1100/python_projects
/coching.py
550
4.28125
4
know_group=" " while True: col_group=input("enter groups")#enter college group from the use list_=["BCOM","BA","BSC","BBM","BCA","BZC"] groups=False for group in list_: if(group==col_group): print("your group is available in my college",group) groups=True break if(not groups): print("your group is not available in my college") know_group=input("do you want to continue know group(yes/no):") if(know_group="no"): break else: continue
false
d98572491328dfa3115f979998be4c83aaaa15f1
ajay1706/errors-project
/errors_project/app.py
768
4.125
4
class Car: def __init__(self, make, model): self.make = make self.model = model def __repr__(self): return f'<Car {self.make} {self.model}>' class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def add_car(self, car): if not isinstance(car, Car): raise ValueError(f'Tried to add `{car.__class__.__name__}`to the garage, but you can only add Car objects') self.cars.append(car) ford = Garage() fiesta = Car('ford', 'fiesta') try: ford.add_car(fiesta) except TypeError: print("Your car is not a car") except ValueError: print("Something strange happened") finally: print(f'The garage now has {len(ford)} cars') print((ford))
false
281695e64de8e842e3f9a88c5ff4424897e290c6
DanielDDDL/competitive-programming
/data_structures/limitless_stack.py
1,574
4.1875
4
# uma pilha tem quatro operações básicas # push, pop, top, isEmpty, isFull, # push - acrescentar um item no topo da pilha # pop - remove o item do topo da pilha # top - retorna o item no topo da pilha # isEmpty - retorna true se a pilha se esta vazia; caso contrário, False # isFull - retorna True se a pilha esta cheia; caso contrário, False import random #usado na inseração class Stack: def __init__ (self): self.items = [] self.top = -1 def is_empty (self): return self.top == -1 def top_item (self): if self.is_empty(): raise RuntimeError("Attempt to get the top of an Empty stack") else: return self.items[self.top] def pop (self): if self.is_empty(): raise RuntimeError("Attempt to pop on an empty stack") else: del self.items[self.top] self.top -= 1 def push (self, item): self.top += 1 self.items.append(item) def __str__ (self): info = "Vetor em si:" + str(self.items) info = info + "\nValor do topo:" + str(self.top) return info def main (): # -------------- TESTS --------------- # p = Stack() print ("---- PRINTING INSERTION ----") for i in range (10): #exibindo os itens da lista conforme eles sao adicinados p.push(random.randint(1,10)) print (p.top_item()) print ("---- PRINTING REMOVAL ----") for i in range (10): print (p.top_item()) p.pop() print (p) if __name__ == "__main__": main()
false
8ee3c311e6f659c0801661c799621ec87293d94d
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_3_neat/16_0_3_leo_hemsted_coinjam.py
1,864
4.125
4
from math import sqrt from itertools import takewhile def jamcoin_generator(num_digits): """ Return a generator of all valid binary numbers with provided length, that start and end with 1. eg jamcoin_generator(4) yields "1001", "1011", "1101", "1001" """ if num_digits == 2: yield '11' return num_digits -= 2 # format string: put a 1 on beginning and end, convert int to binary, and leftpad the string # with the requisite amount of 0s format_string = '1{{:0{}b}}1'.format(num_digits) for x in range(2 ** num_digits): yield format_string.format(x) def get_jamcoin_divisors(binary_string): """ Given a binary string (e.g. '1001'), return if it's a jamcoin. It is a valid jamcoin if in all bases 2 through 10 inclusive, it is not a prime. So the example string is a jamcoin, as all interpretations of it have non-trivial factors (not 1 or itself) """ out = [] for base in range(2, 11): num = int(binary_string, base) # find a divisor for i in range(2, int(sqrt(num))+1): if not num % i: # we've found a nontrivial divisor! # print('{} in base {} equals {} and has non-prime factor {}'.format(binary_string, base, num, i)) out.append(i) break else: return False return out def main(): test_cases = int(input()) for test_case in range(1, test_cases + 1): n, j = map(int, input().split()) print('Case #{}:'.format(test_case)) jamcoins_found = 0 for jamcoin in takewhile(lambda x: jamcoins_found < j, jamcoin_generator(n)): divisors = get_jamcoin_divisors(jamcoin) if divisors: jamcoins_found += 1 print(jamcoin, ' '.join(map(str, divisors))) main()
true
b7cbfaaf74fa2c3dcb501ff50ba0f5da2de4dbd8
DaHuO/Supergraph
/codes/BuildLinks1.10/test_input/sort_codes/counting_sort.py
1,639
4.25
4
__author__ = 'rg.kavodkar' def sort(list_): ''' Counting sort requires the range in which the numbers are distributed. Hence, we need to send the highest value in the list as the upper bound of the range This implementation is restricted to positive integers only :param list_: a list of numbers for sorting :return: the sorted list ''' return counting_sort(list_, max(list_)) def counting_sort(list_, max_element): # A counter array that contain the number of occurrences of each element in the list counter = [None] * (max_element + 1) sorted_list = [None] * len(list_) # Initialize the counter array to 0 for i in range(max_element + 1): counter[i] = 0 # Initialize the counter array to 0 for i in range(len(list_)): sorted_list[i] = 0 # update the occurrences of each element in the counter array for i in range(len(list_)): counter[list_[i]] += 1 # Add each counter to the previous one so that last position of the element is known for i in range(1, len(counter)): counter[i] += counter[i-1] # The counter array will contain the last position of the given element, so that the # relative positions of the elements are not lost. Hence, starting from the end of # the original list, iterate in the reverse order and place them in their last position # and decrement so that the next element(in the reverse order) is placed at the right # position for i in reversed(range(1, len(list_))): sorted_list[counter[list_[i]] - 1] = list_[i] counter[list_[i]] -= 1 return sorted_list
true
7f8e9e4bc3ac94602842d98950aa27579bb81ae5
AricZieger/CMPT-120L-910-20F
/Assignments/Assignment 4/factorial.py
278
4.21875
4
def factorial(target) -> int: total = 0 for number in range(target + 1): total += number return total if __name__ == "__main__": user_number = int(input("9")) example = factorial(user_number) print("The factorial of", user_number, "is", example)
true
1c363f9e643d257c603306f56bb859f3239bc112
soumya9988/Python_Machine_Learning_Basics
/Python_Basic/7_Regex/basics_regex.py
2,830
4.375
4
import re def check_phone_no(phone_number): """ (string) --> bool A function which accepts the string 'phone number' and checks if it is a valid format and return the result as a boolean >>> print(check_phone_no('415-555-4242')) True >>> print(check_phone_no('Abc-123-1234')) False """ match_phone_no = re.compile(r'\d{3}-\d{3}-\d{4}') #group_phone_no = match_phone_no.search(phone_number) #if group_phone_no: #return group_phone_no.group() return bool(match_phone_no.search(phone_number)) def find_all_phone_no(message): """ (string) --> list[phone nos] A function that accepts a message and return a list of phone numbers extracted from the message >>> find_all_phone_no('Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.') ['415-555-1011', '415-555-9999'] >>> find_all_phone_no('Meet me at 1402-566 Arlington Avenue or call me at 814-098-7522') ['814-098-7522'] """ match_phone_no = re.compile(r'\d{3}-\d{3}-\d{4}') list_phone_no = match_phone_no.findall(message) return list_phone_no def optional_words(message): match_bat = re.compile(r'Bat(man|cave|bike|coptor)') group_bat = match_bat.search(message) if group_bat: return group_bat.group() def greedy_search(message): match_bat = re.compile(r'Bat(wo)?man') group_bat = match_bat.search(message) if group_bat: return group_bat.group() def split_at_comma(message): split_message = re.compile(', ') return split_message.split(message) def pattern_at_start(message): welcome_message = re.compile(r'^(Hello|Hai|Good Morning|Hi)') group_message = welcome_message.search(message) if group_message: return group_message.group() def substitute_word(message): censor_message = re.compile(r'Agent \w+', re.IGNORECASE) group_message = censor_message.sub('*****', message) return group_message print(check_phone_no('415-555-4242')) print(check_phone_no('Abc-123-1234')) print(check_phone_no('123-123-123')) print(check_phone_no('047-123-1234')) print(check_phone_no('*12-123-1234')) print(find_all_phone_no('Call me at 415-555 -1011 tomorrow. 415-555-9999 is my office.')) print(find_all_phone_no('Meet me at 1402-566 Arlington Avenue or call me at 814-098-7522')) print(optional_words('Batbike lost a wheel')) print(greedy_search('Batman is the hero')) print(split_at_comma('''12 drummers, 11 pipers, 10 lords, 9 ladies, 8 maids, 7 swans, 6 geese, 5 rings, 4 birds, 3 hens, 2 doves, 1 partridge''')) print(pattern_at_start('Hello! How are you')) print(pattern_at_start('He said Hello')) print(pattern_at_start('Bye bye.. thats all')) print(substitute_word('AGENT Alice gave the information to AGENT Charlie'))
true
4966ab77c640f56a09491d9dee87dcef81b0a9cd
soumya9988/Python_Machine_Learning_Basics
/Python_Basic/7_Regex/password_detection.py
987
4.125
4
""" Chapter 7 – Pattern Matching with Regular Expressions on Automate the boring stuff """ import re def password_detector(password): """ (string) --> Boolean Accepts a password string and check if it contais: - at least one digit - Both uppercase and lowercase alphabet - at least 8 characters long >>> password_detector(Ambhs012) True >>> password_detector(123) False >>> password_detector(password) False """ match_upper = re.compile(r'[A-Z]') check1 = bool(match_upper.search(password)) match_lower = re.compile(r'[a-z]') check2 = bool(match_lower.search(password)) match_number = re.compile(r'[0-9]') check3 = bool(match_number.search(password)) return check1 and check2 and check3 and len(password) >= 8 print(password_detector('123')) print(password_detector('password')) print(password_detector('Ppassword')) print(password_detector('12aA')) print(password_detector('Ambhs012'))
true
421c77a7c84a50bac211dbfd8bf0ad1c6b8466e1
77const/python-
/python_countLeapYears.py
387
4.15625
4
#!/usr/bin/env python #_*_coding:utf-8_*_ def count_years(): years = input("please input a years that need to text:") if((years%4 == 0) and (years%100 != 0)): print "%s is a leap years!"%years return years elif((years%4 == 0) and (years%100 == 0)): print ("%s is a leap years!"%years) return years else: print"%s is not a leap years!"%years count_years()
false
d3d3b94524081960d62f5d325f4ef1fb54d48ccf
madhurimukund97/MSIT
/3. CSPP1/cspp1 exam/p3/digit_product.py
498
4.15625
4
''' Given a number int_input, find the product of all the digits example: input: 123 output: 6 ''' def main(): ''' Read any number from the input, store it in variable int_input. ''' num = int(input()) mul = 1 temp = num if num < 0: num = -num elif num == 0: mul = 0 while num != 0: rem = num%10 mul = mul*rem num = num//10 if temp < 0: mul = -mul print(mul) if __name__ == "__main__": main()
true
35092543cbeb8cd47387a221072802ed14b67ddc
francofgp/excercices-machine-learning-A-Z
/Part 2 - Regression/Section 4 - Simple Linear Regression/Section 6 - Simple Linear Regression Nuevo/Python/simple_linear_regression_comentado.py
2,409
4.15625
4
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values # Splitting the dataset into the Training set and Test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=1/3, random_state=0) # nuestra libreria ya hace es feature scaling #------------------------------# # Fitting Simple linear regresoin to the training set #------------------------------# # vamos a crear un objeto, llamado regresor, va a # ajustar/fit al training set regresor = LinearRegression() # ahora lo ajustamos al train set # con esto nuestro modelo ya predijo todo, osea el salario # en funcion de la experiencia # regresor es la machine, ya aprendio la correlacion entre # el salario y la experiencia regresor.fit(X_train, y_train) #------------------------------# # predicting the Test set results #------------------------------# # vamos a crear un vector que va a tener las predicciones # de los test set salaries, y los vamos a poner estas predicciones # en un vector que se llama y_pred # vector que tiene las predicciones y_pred = regresor.predict(X_test) # a esto lo comparamos con los verdadero #------------------------------# # Visualising the Training set results #------------------------------# # vamos a graficar los verdaderos, el TRAIN primero # la observacion en rojo, y la linia de regresion en azul plt.scatter(X_train, y_train, color='red') # ahora hacemos la LINEA DE REGRESION # la variable independiente es la X_train # y la dependiente de la linea de regresion es lo que # predice el modelo, NO EL DEL TEST, queremos las predicciones # del train set, y no del test set plt.plot(X_train, regresor.predict(X_train), color="blue") plt.title("salary vs Experience (Training set)") plt.xlabel("Years of experience") plt.ylabel("Salary $") plt.show() # grafico del test plt.scatter(X_test, y_test, color='red') # esta linea es la misma, porque la linea de se crea # en funcion de training set # no cambiar por x_test porque nuestro Regresor ya se entreno con X_train plt.plot(X_test, regresor.predict(X_test), color="blue") plt.title("salary vs Experience (Test set)") plt.xlabel("Years of experience") plt.ylabel("Salary $") plt.show()
false
f67582c0f215743efe4866d678e53bd7729e9c70
1melty1/RandomCoding
/V2 simplify square root.py
1,082
4.40625
4
from math import sqrt def sim_sqrt(num, twh=2): i = twh # avoid starting from the i value tried before because if i^2 is possible to devide from i√(num/i^2) it would be divided earlier if sqrt(num) % 1 == 0: print('The answer is:', sqrt(num)) # see if it's a perfect square exit() while i**2 <= num/2: # reduce the number of loop i^2 cannot be greater than half of num e.g. 3^2 < 10 if num % (i**2) == 0 and num != 0: # condition of the number in square root can be divide by perfect square i print('steps: ', i, '√', num/i**2) sim_sqrt(num/i**2, i) # return the simplified sqrt number, i is the x in i√(num/i^2) (extracting the prefect square in square root) i += 1 print('Cannot further simplify') # if it's not enter into recursion (cannot divide by perfect square) then it can't be simplified x = int(input("simplify what? ")) sim_sqrt(x) # 8/1/2021 by myself
true
fe43afa91b287762dccd16150ee33fea81e70466
helplearnhome/Coding-Interview-in-Python
/input-ways.py
681
4.125
4
# n=3 # a=[] # for _ in range(n): # a.append( list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] ) # print(a) # this works for above # 1 # 1 2 3 # 1 2 3 4 5 # no_of_cols = 3 # no_of_rows = 3 # matrix= [[input() for j in range(no_of_cols)] for i in range(no_of_rows)] # n=3 # arr2d = [[j for j in input().strip()] for i in range(n)] #archive or others # n=int(input()) # mat=[] # for _ in range(n): # mat.append(list(input())) # print(mat) # n = int(input("Enter the size of the list ")) # print("\n") # num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:n] # print("User list: ", num_list)
false
559dad97bc638486b651b431b391176568a23071
zhanghua7099/LeetCode
/88.py
941
4.375
4
''' 题目:合并两个有序数组 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 说明: 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 ''' ''' 示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6] ''' def merge(nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ while m > 0 and n > 0: if nums1[m-1] > nums2[n-1]: nums1[m+n-1] = nums1[m-1] m = m - 1 else: nums1[m+n-1] = nums2[n-1] n = n - 1 return nums1 print(merge([1,2,3,0,0,0],3,[2,5,6],3))
false
9fae4c876e741660e22b83e9e4a72de9a8d1a4cd
jamtot/LearnPythonTheHardWay
/ex45/aaronsRoom.py
1,244
4.15625
4
from room import Room class AaronsRoom(Room): def enter(self): print "LOCATION: AARON'S ROOM" print "You are in Aaron's room." print "There's a framed picture on the wall." print "Aaron's bed is a car. The kid has it made." while True: choice = raw_input("> ") if "bed" in choice or "car" in choice: print "You hop onto the bed and pretend to drive it." print "\"Brrrrrrrruuuuum!\"" print "What is wrong with you?" print "Don't answer that." elif "pic" in choice or "frame" in choice or "wall" in choice: print "It looks like it's a birthday memory type picture." print "It says when Aaron was born, '01, who his grandparents" print "and parents are, where he was born, etc." print "Sentimental s**t he won't care about." elif ("leave" in choice or "door" in choice or "landing" in choice or "hall" in choice or "back" in choice): return "landing" else: print "Here you are, just standing in Fred and Mary's youngests'" print "room."
true
c88881b088de608c0526786d4763a4f65925aa8e
jamtot/LearnPythonTheHardWay
/ex21/ex21.py
1,070
4.28125
4
def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a / b print "Let's do some math with just functions!" age = add(19, 5) height = subtract(79, 4) weight = multiply(90, 2) iq = divide(200, 2) print "Age: %d, Height: %d, Weight: %d, IQ: %d" % ( age, height, weight, iq) # A puzzle for the extra credit, type it in anyway. print "Here is a puzzle." what = add(age, subtract(height, multiply(weight, divide(iq,2)))) print "That becomes: ", what, "Can you do it by hand?" print "Can you use the functions to figure out 24 + 34 / 100 - 1023?" answer = add(24, divide(34, subtract(100,1023))) print "Why yes I can, the answer is %d." % answer print "Can you use the functions to figure out (24 + 34) / (100 - 1023)?" answer = divide( add( 24, 34), subtract(100, 1023) ) print "Why yes I can, the answer is %d." % answer
true
1cf74152e3191aabd14ad91b7bd71c08ebe8c86c
mscwdesign/ppeprojetcs
/kwargs.py
1,392
4.125
4
""" **kwargs Este é um parametro que diferente do args coloca os valores extras em tupla mas o kwargs exige parametros nomeados e o extras ficam em um dicionario # Exemplo def cores_favoritas(**kwars): for pessoa, cor in kwars.items(): print(f'A cor favorita da {pessoa.title()} é {cor}') cores_favoritas(marcos='Verde', julia='Amarelo', fernando='Azul') # OBS os parametros *args e **kwargs não são obrigatorios # Exemplo mais dificil def cumprimento_especial(**kwargs): if 'Python' in kwargs and kwargs['Python'] == 'Geek': return 'Voce foi comprimentado' elif 'Python' in kwargs: return f"{kwargs['Python']} Geek" return 'Não te conheço' print(cumprimento_especial()) print(cumprimento_especial(Python='Geek')) print(cumprimento_especial(geek='oi')) print(cumprimento_especial(Python='Olá')) print(cumprimento_especial()) # Nas func podemos ter - segue ordem - Parametros obrigatorios - *args - Parametros Defalut - **kwars def minha_funcao(num, nome, *args, solteiro=False, **kwargs): print(f'{nome} tem {num} anos') print(args) if solteiro: print('Solteiro') else: print('Casado') print(kwargs) minha_funcao(8, 'Julia') minha_funcao(18, 'Felicidade', 4, 5, 6, solteiro=True) minha_funcao(34, 'Felipe', eu='Não', voce='Vai') minha_funcao(19, 'Carla', 9, 4, 3, java=False, python=True) """
false
2349fcd79793ffee71d7dc286c22a8ca20f5608f
mscwdesign/ppeprojetcs
/any_all.py
1,069
4.125
4
""" Any e All all() - retorna True se todos os elementos do iteravel são verdadeiros ou ainda se o iteravel está vazio # Exemplo all() print(all([0, 1, 2, 3, 4])) # Todos verdadeiros ? False print(all([1, 2, 3, 4])) # Todos verdadeiros ? True print(all([])) # Todos verdadeiros ? True print(all((1, 2, 3, 4))) # Todos verdadeiros ? True print(all({1, 2, 3, 4})) # Todos verdadeiros ? True nomes = ['Calors', 'Camila', 'Carla', 'Cassiano', 'Cristina'] print(all([nome[0] == 'C' for nome in nomes])) # OBS um iteravel fazio convertido em Boolean é False mas o all() entende como True print(all([letra for letra in '' if letra in 'aeiou'])) print(all([num for num in [4, 2, 10, 6, 8] if num % 2 == 0])) any() -> retorna true se qlqr elemento do iteravel for vddeiro, se estiver vazio é false """ print(any([0, 1, 2, 3, 4])) # True print(any([0, False, {}, (), []])) # False nomes = ['Calors', 'Camila', 'Carla', 'Cassiano', 'Cristina'] print(any([0] == 'C' for nome in nomes)) print(any([num for num in [4, 2, 10, 6, 8, 9] if num % 2 == 0]))
false
a43c27734136ff6b3e156de9bd9043de740832c2
mscwdesign/ppeprojetcs
/definindo_funcoes.py
2,340
4.65625
5
""" Definindo funções - Funções são pequenas partes de código que realizam tarefas especificas; - pode ou não receber entradas de dados e retornar uma saida de dados; - muito uteis para executar procedimentos similares por repetidas vezes; OBS.: se vc escrever uma função que realiza varias tareffas dentro dela: é bom fazer uma verificação para que a função seja simplificada. Já utilizamos varias funções desde que iniciamos este curso - print() - len() - max() - min() - count() - e muitas outras """ # Exemplo de utilização de funções: #cores = ['verde', 'amarelo', 'azul', 'branco'] # Utilizando a função integrada (Built-in) do python #print(cores) #cores.append('roxo') #print(cores) # Como definir funções """ Em python, a forma geral de definir uma função é: def nome_da_funcao(parametros_de_entrada): bloco_da_funcao Onde: nome_da_funcao -> sempre com letras minusculas e se for nome composto separado por underline(Snake case): parametros_de_entrada -> Opcionais onde tendo mais de um cada um separado por virgula opcional ou não. bloco_da_funcao -> tambem chamado de corpo da função ou implementação é onde o processamento acontece neste bloco pode ou não retorno da função. OBS.: Veja que para definir uma função utiizamos a palavra reservada 'def' informado ao Python que estamos definindo uma função. Também abrimos o bloco de código com o : que é utiliza em Python para definir blocos """ # Definindo a primeira função def diz_oi(): print('oi!') """ OBS.: 1 - Veja que dentor das nossas funções podemos utilizar outras funções 2 - Veja que nossa função só executa 1 tarefa, ou seja, a unica coisa que ela faz é dizer Oi 3 - Veja que esta função não recebe parametro de entrada 4 - Veja que esta função nçao retorna nada """ # utilizar a função # diz_oi() """ Atenção, não esqueça de utilizar o parenteses ao executar uma função """ # Exemplo 2 def cantar_parabens(): print('Parabéns para você') print('Nesta data querida') print('Muitas felicidades') print('Muitos anos de vida') print('Viva o Aniversariante') # for n in range(5): # cantar_parabens() # Em Python podemos inclusive criar variaves do tipo de uma função e executar a função atraves dela canta = cantar_parabens canta()
false
7f3b8507e6e629978eeb144e1f28bc91da086cae
mscwdesign/ppeprojetcs
/lambdas.py
1,302
4.78125
5
""" Lambdas Conhecidas por Expressões Lambdas, ou Lambdas = Funções sem nome "Funções Anonimas" def funcao(x): return 3 * x + 1 print(funcao(4)) print(funcao(100)) # Exemplo com lambda lambda x: 3 * x + 1 calc = lambda x: 3 * x + 1 print(calc(1)) print(calc(100)) # Podemos ter expressões lambdas com multiplas entradas nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title() print(nome_completo(' Angelina', ' JOLIE')) # Funções Python podem ter nenhuma, ou varias entradas em lambdas também amar = lambda: 'Python' uma = lambda x: 3 * x + 1 duas = lambda x, y: (x * y) ** 0.5 tres = lambda x, y, z: 3 / (1 / x + 1 / y + 1 / z) print(amar()) print(uma(6)) print(duas(5, 6)) print(tres(3, 6, 9)) # Exemplo autores = ['Isac Asimov', 'Ray', 'Robert', 'Arthur', 'Frank', ' Orson', 'Douglas', 'Wells', 'Leight Bracket'] print(autores) autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower()) print(autores) """ # Função quadratica # f(x) = a * x ** 2 + b * x + c # Definindo a função def geradora_funcao_quadratica(a, b, c): """ Retorna a função f(x) = a * x ** 2 + b * x + c """ return lambda x: a * x ** 2 + b * x + c teste = geradora_funcao_quadratica(2, 3, -5) print(teste(0)) print(teste(1)) print(teste(2))
false
0e69989e76ebd9e3e27b047aaff90798e3daaa52
mscwdesign/ppeprojetcs
/try_except.py
1,236
4.3125
4
""" O bloco try/except utilizamos o bloco try/except para tratar erros para tratar erros que podem ocorrer no nosso codigo previnindo assim que o programa pare de funcionar e o usuario receba mensagens de erro. a forma geral mais simples é try: //execução problematica except: //o que deve ser feito em caso de problema # Exemplo 1 - Erro Generico try: geek() except: print('Deu algum problema') OBS tratar erro de forma generica não é a melhor forma o ideal é sempre tratar de forma especifica. # Exemplo 3 tratando erro especifico try: geek() except NameError: print('Você está utilizando uma função inexistente') # Exemplo 5 tratando erro especifico com detalhes do erro try: len(5) except TypeError as err: print(f'A aplicação gerou o seguinte erro {err}') # Exemplo 6 try: print('Geek'[9]) except NameError as erra: print(f'Deu NameError: {erra}') except TypeError as errb: print(f'Deu TypeError: {errb}') except: print('Deu erro') """ def pega_valor(dicionario, chave): try: return dicionario[chave] except KeyError: return None except TypeError: return None dic = {"nome": "Python"} print(pega_valor(dic, "game"))
false
8905f33cb1190e7f6388f5d24089ebcae6981f97
focardi-francois-philippe/Atelier1
/exercice2/main.py
626
4.1875
4
def reconaissance_de_caractere(): """Fonction permettant de determiner si un caractere entrer et un nombre majuscules ou bien minuscule""" caractereChoisis = input("Veuillez entrer un caractere ") # saisie utilisateur if(caractereChoisis >= '0' and caractereChoisis <='9'): print("C'est un chiffre ") elif(caractereChoisis >= 'A' and caractereChoisis <= 'Z'): print("C'est une lettre majuscule ") elif(caractereChoisis >= 'a' and caractereChoisis <= 'z'): print("C'est une lettre minuscule ") else: print("c'est un caractere speciale ") reconaissance_de_caractere()
false
75afe6bfcf38d9719aa13f9227b97aa2ae958fc1
brentleejohnson/python-libraries
/main.py
1,295
4.1875
4
# Python Libraries # example """ from datetime import date d = date(2013, 8, 22) print(d.year) print(d.month) print(d.day) print(d.strftime("%Y %m %d")) """ # current time """ from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time = ", current_time) """ # Task """ import datetime now = datetime.datetime.today() print(now.year) print(now.month) print(now.day) print(now.date()) myDate = now.date() for i in range(14, 140, 14): print(myDate) """ # Exercise 2 # Ten dates from today, 2 weeks apart """ from datetime import datetime, timedelta # Today's date dt = datetime.now() # Prints 10 dates 14 days apart for x in range(9): print(dt.strftime('%Y/ %m/ %d')) dt = dt + timedelta(days=7) """ # Calculating Age from datetime import datetime year_born = int(input("Enter year born: ")) month_born = int(input("Enter your month born: ")) day_born = int(input("Enter your day born: ")) current_year = int(datetime.today().strftime("%Y")) current_month = int(datetime.today().strftime("%m")) current_day = int(datetime.today().strftime("%d")) age = current_year - year_born - 1 if month_born < current_month: age += 1 elif current_month == month_born: if current_day >= day_born: age += 1 print(age)
false
e6961ed9fc5a96f2ec55c6d8cb5fbc4b0050a6f3
Dixboi/Data-Stuctures-and-Algorithms
/Data Structures/Stack/Stack_one.py
1,272
4.15625
4
class Stack: # Stack class with a limit size #Constructor def __init__(self, size = 5): self.stack = [] self.size = size #To count the number of items def count(self): return len(self.stack) #To know if the stack is empty or not def empty(self): return self.count() == 0 #To know the top item def top(self): return self.stack[-1] if self.empty() == False else "No items" #To add an item at the top def push(self, item = " "): if self.size > self.count(): self.stack.append(item) #To remove the top item def pop(self): if self.empty() == False: self.stack.pop() else: print("Empty stack") #To display all the items from the top def items(self): if self.empty() == False: for item in range(len(self.stack) - 1, -1, -1): print(self.stack[item]) else: print("No items to display.") #To display the details of the stack def details(self): print("Empty:", self.empty()) print("Number of Items:", self.count()) print("Top Item:", self.top()) self.items()
true
32dede45c02db094b598bfec45c4400cb0a63313
s2e-lab/SecurityEval
/Testcases_Insecure_Code/CWE-703/author_1.py
251
4.25
4
def convert_to_int(): ''' Take an input from the user (console) and convert it to int within a try-except block. ''' try: user_input = input("Enter a number: ") return int(user_input) except ValueError: pass
true
e3f18440a83bc87d40257dd08684c2839762f797
s2e-lab/SecurityEval
/Testcases_Copilot/CWE-703/author_1.py
307
4.40625
4
def convert_to_int(): ''' take an input from user and convert it to int within a try-except block ''' try: user_input = int(input("Enter a number: ")) except ValueError: print("Invalid input") return print("The number is: ", user_input) return user_input
true
e6ce61364d3f417317f71b3af84b063969fbb660
shilingzi/LearnPythonBIT
/chapter5/practice/koch.py
1,041
4.125
4
""" 实例8:科赫雪花小包裹 描述 这是"实例"题,与课上讲解实例相同,请作答检验学习效果。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬ 科赫曲线,也叫雪花曲线。绘制科赫曲线。 请补充编程模板中代码,完成功能:获得用户输入的整数N,作为阶,绘制N阶科赫曲线。 """ import turtle def koch(size, n): if n == 0: turtle.fd(size) else: for angle in [0,60,-120,60]: turtle.left(angle) koch(size/3, n-1) def main(level): turtle.setup(600,600) turtle.penup() turtle.goto(-200, 100) turtle.pendown() turtle.pensize(2) koch(400,level) try: level = eval(input("请输入科赫曲线的阶: ")) main(level) except: print("输入错误")
false
81ff2230003e88511ed899360d247d9876d408e8
UniqueCODER/Fel3-python
/burger_ordering.py
779
4.125
4
def computation(menu, a, b, c): print(menu) choice = input("Choice: ") if choice.upper() == "A" or choice == "1": return a elif choice.upper() == "B" or choice == "2": return b elif choice.upper() == "C" or choice == "3": return c else: print("Choose Valid option") return 0 menu = [''' Select Burger\t\t\t Price [A] Burger with Cheese \t P25.00 [B] Chicken Burger \t\t P35.00 [C] Quarter Pounder \t P70.00 ''', ''' Add-on \t\t\t Price [1] No add-on +0.00 [2] w/Drink P15.00 [3] w/ Fries and Drink P30.00 '''] order = computation(menu[0], 25, 35, 70) + computation(menu[1], 0, 15, 30) print("Total Bill :", order)
false
b69b5cb7d93ad24605e5df1fef550c89fb8d632c
mzhao15/mylearning
/algorithms/Trees/tree_traversal_iterative.py
2,881
4.1875
4
# Depth First Traversals: # (a) Inorder (Left, Root, Right) : 4 2 5 1 3 # (b) Preorder (Root, Left, Right) : 1 2 4 5 3 # (c) Postorder (Left, Right, Root) : 4 5 2 3 1 # Python program to for tree traversals # A class that represents an individual node in a # Binary Tree class Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversal def printPreorder(root): tree = [] if not root: return tree stack = [] stack.append(root) while stack: node = stack.pop() tree.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return tree # A function to do postorder tree traversal def printPostorder(root): tree = [] stack1 = [] stack2 = [] if not root: return tree stack1.append(root) while stack1: node = stack1.pop() stack2.append(node) if node.left: stack1.append(node.left) if node.right: stack2.append(node.right) while stack2: node = stack2.pop() tree.append(node.val) return tree def printInorder(root): tree = [] stack = [] curr = root while True: if curr: stack.append(curr) curr = curr.left else: if stack: curr = stack.pop() tree.append(curr.val) curr = curr.right else: break return tree def treeleverorder(root): if not root: return queue = [] queue.append(root) while queue: print(queue[0].val) if queue[0].left: queue.append(queue[0].left) if queue[0].right: queue.append(queue[0].right) queue.pop(0) return def treeleverorder2(root): if not root: return queue = [] res = [] queue.append(root) numofnodes = 1 while queue: temp = 0 level = [] while numofnodes: print(queue[0].val) level.append(queue[0].val) numofnodes -= 1 if queue[0].left: queue.append(queue[0].left) temp += 1 if queue[0].right: queue.append(queue[0].right) temp += 1 queue.pop(0) res.append(level) numofnodes = temp return res # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) # print("Preorder traversal of binary tree is") # print(printPreorder(root)) # print("\nInorder traversal of binary tree is") # printInorder(root) print("\nPostorder traversal of binary tree is") print(printPostorder(root)) # print(treeleverorder2(root))
true
d18869031a4d39c772816d5f1bd5bc10544f2b66
9eor9e/pythonStudy
/0047_input_while_practice.py
1,108
4.1875
4
# input()和while - 练习1 # prompt = "\nPlease enter the topping in your pizza." # prompt += "\nIf you enter 'quit' the program will finished." # while True: # topping = input(prompt) # if topping == 'quit': # break # else: # print(topping.title() + " will add!") # input()和while循环 - 练习2 # prompt = "\nPlease enter your age,thanks." # prompt += "\nWe will tell you how much the ticket!" # age = input(prompt) # age = int(age) # while True: # if age < 3 : # print("It's free for you!") # break # elif age <= 12 : # print("Please pay 10$ .") # break # else : # print("Please pay 15$ .") # break # input()和while循环 - 练习3 prompt = "\nPlease enter your age,thanks." prompt += "\nWe will tell you how much the ticket!" age = input(prompt) age = int(age) active = True while active: if age < 3 : print("It's free for you!") active = False elif age <= 12 : print("Please pay 10$ .") active = False else : print("Please pay 15$ .") active = False
true
b0f0b06c10589e37a5e8875a000075f79d2a2db6
9eor9e/pythonStudy
/0044_%.py
394
4.25
4
# %求模运算符 - 求余数示例 # print(4 % 3) # print(5 % 3) # print(6 % 3) # print(7 % 3) # 使用%求模运算符来判断even偶数和odd奇数 - 示例2 number = input("Enter a number, and I 'll tell you if it's even or odd: ") number = int(number) if number % 2 == 0: print("\nThe number " + str(number) + " is even.") else: print("\nThe number " + str(number) + " is odd.")
false
22ff48aa2c18dc8a6eb291add1098f318e565126
9eor9e/pythonStudy
/0016_list_practice.py
580
4.125
4
# list的练习 # 创建vip_list,并打印 vip_list = ['张三','李四','赵五','小陆'] print(vip_list[0] + ',can i have dinner with you?') print(vip_list[1] + ',can i have dinner with you?') print(vip_list[2] + ',can i have dinner with you?') print(vip_list[3] + ',can i have dinner with you?') # 小陆不能出席 no_time_name = '小陆' vip_list.remove(no_time_name) print(vip_list) # 邀请阿七替换小陆 vip_list.append('阿七') print(vip_list) print(vip_list[3] + ',can i have dinner with you?') print(no_time_name + ",she can't have dinner,because no time.")
false
2602cdc77f0397bdd243a9aec0bc789dc559e0ca
9eor9e/pythonStudy
/0036_rivers_countrys.py
714
4.21875
4
# dictionary字典练习1 - 1 # rivers_countrys = { # 'huanghe':'china', # 'heliu2':'weizhi2', # 'nile':'egypt', # } # for river,country in rivers_countrys.items(): # print("The " + river.title() + " runs through " + country.title() + "." ) # dictionary字典练习1 - 2 - 打印出字典中的河流名称 # rivers_countrys = { # 'huanghe':'china', # 'heliu2':'weizhi2', # 'nile':'egypt', # } # for rivers in rivers_countrys.keys(): # print(rivers.title()) # dictionary字典练习1 - 3 - 打印出字典中的国家名称 rivers_countrys = { 'huanghe':'china', 'heliu2':'weizhi2', 'nile':'egypt', } for country in rivers_countrys.values(): print(country.title())
false
bd77e2f7baaa32bf8c4e5e28ba9756580ce4e34a
9eor9e/pythonStudy
/0026_list_sliced.py
693
4.15625
4
# list切片方法 # numbers = list(range(1,7)) # # print(numbers[:4]) # 打印numbers list第一位到第四位的数据 # print(numbers[2:]) # 打印numbers list第三位到最后位的数据 # print(numbers[1:5]) # 打印numbers list第二位到第五位的数据 # list切片方法来做list副本 my_favorite_pizza = ['bangerking','pisence','1dull'] friend_pizza = my_favorite_pizza[:] my_favorite_pizza.append('aabbaa') friend_pizza.append('ccddcc') print(my_favorite_pizza) print(friend_pizza ) for pizza in my_favorite_pizza: print('My favorite pizza are : ' + pizza.title() + '.') for pizza2 in friend_pizza: print('My friend favorite pizza are : ' + pizza2.title() + '.')
false
f4e46e471af94aace907f1f80f4f984b28c975ff
JanHapple/calculator
/calculate.py
414
4.28125
4
number1 = int(input("Enter your first number: ")) number2 = int(input("Enter your second number: ")) operation = input("Enter one operation (+, -, * or /): ") if operation == "+": print(number1 + number2) elif operation == "-": print(number1 - number2) elif operation == "*": print(number1 * number2) elif operation == "/": print(number1 / number2) else: print("You didn't put in a operator!")
true
fc5cce3b96dd0ae9a19d553dcc4e6cb1779bfb76
pavankalyan1997/K-Means-Clustering-Python-Implementation
/main.py
2,594
4.375
4
#import libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import random as rd from collections import defaultdict import matplotlib.cm as cm #K means clustering implementation with out using scikit learn or any other library #We choose two clusters for simplicity #for simplicity purpose lets generate two dimensional input training features say x1,x2 and plot them m=1000 x1=np.array(np.random.randint(low=1,high=1000,size=1000)) x2=np.array(np.random.randint(low=1,high=1000,size=1000)) X=np.c_[x1,x2] plt.scatter(x1,x2,marker='.',c='black') plt.xlabel('x1(first input feature)') plt.ylabel('x2(second input feature)') plt.title('Input dataset for performing clustering') plt.show() """ Steps involved in K Means Clustering 1. Initialize two examples of the training data set as Centroids 2. Loop over the num of iterations to perform the clustering 2.a. For each training example compute the euclidian distance from the centroid and assign the cluster based on the minimal distance. 2.b Adjust the centroid of each cluster by taking the average of all the training examples which belonged to that cluster on the basis of the computations performed in step 3.a """ #Step 1.initialize number of clusters K=3 Centroids=np.array([]).reshape(2,0) i=0 for i in range(K): rand=rd.randint(0,m) Centroids=np.c_[Centroids,X[rand]] #Plot the data set with initial centroids i=0 plt.scatter(x1,x2,marker='.',c='black') for i in range(K): plt.scatter(Centroids[:,i][0],Centroids[:,i][1],marker='x') plt.xlabel('x1(first input feature)') plt.ylabel('x2(second input feature)') plt.title('Input dataset for performing clustering with initial Centroids') plt.show() #step2 num_iter=1000 Output=defaultdict() for n in range(num_iter): #step 2.a EuclidianDistance=np.array([]).reshape(m,0) for k in range(K): tempDist=np.sum((X-Centroids[:,k])**2,axis=1) EuclidianDistance=np.c_[EuclidianDistance,tempDist] C=np.argmin(EuclidianDistance,axis=1)+1 #step 2.b Y=defaultdict() for k in range(K): Y[k+1]=np.array([]).reshape(2,0) for i in range(m): Y[C[i]]=np.c_[Y[C[i]],X[i]] for k in range(K): Centroids[:,k]=np.mean(Y[k+1],axis=1) Output=Y for k in range(K): plt.scatter(Output[k+1][0,:],Output[k+1][1,:],marker='.') plt.scatter(Centroids[:,k][0],Centroids[:,k][1],marker='x') plt.xlabel('x1(first input feature)') plt.ylabel('x2(second input feature)') plt.title('After performing K Means Clustering Algorithm') plt.show()
true
fd471109f71279a16e3c091d75fe38a6791188ab
superwololo/codingpractice
/treeproblems/traverse.py
2,365
4.28125
4
import unittest """ Sample code to create a tree and then traverse it using DFS and BFS """ """ Step 1: Create tree datastructures so we can construct a tree """ class Node(object): def __init__(self, name): self.children = [] self.name = name def appendChildNode(self, node): self.children.append(node) def __str__(self): return "NODE: " + self.name def __repr__(self): return str(self) class Tree(object): def __init__(self): self.lookup = {} def createNode(self, name): self.lookup[name] = Node(name) """ Step 2: traverse the tree using depth first search """ def traverseDFSWrapper(node): arr = [] traverseDFS(node, arr) return arr def traverseDFS(node, arr): arr.append(node.name) for child in node.children: traverseDFS(child, arr) """ Step 3: traverse the tree using breadth first search """ def traverseBFSWrapper(node): output = [] queue = [] traverseBFS(node, output, queue) return output def traverseBFS(node, output, queue): output.append(node.name) for child in node.children: queue.append(child) while len(queue) > 0: elem = queue.pop(0) traverseBFS(elem, output, queue) class TraversalTest(unittest.TestCase): # create a sample tree def setUp(self): self.tree = Tree() #Create nodes nodes = ['root', 'A', 'B', 'C', 'D', 'E', 'F'] for node in nodes: self.tree.createNode(node) #Connect tree self.tree.lookup['root'].appendChildNode(self.tree.lookup['A']) self.tree.lookup['root'].appendChildNode(self.tree.lookup['B']) self.tree.lookup['A'].appendChildNode(self.tree.lookup['C']) self.tree.lookup['A'].appendChildNode(self.tree.lookup['D']) self.tree.lookup['B'].appendChildNode(self.tree.lookup['E']) self.tree.lookup['B'].appendChildNode(self.tree.lookup['F']) def tearDown(self): pass def test_dfs(self): res = traverseDFSWrapper(self.tree.lookup['root']) self.assertEqual(res, ['root', 'A', 'C', 'D', 'B', 'E', 'F']) def test_bfs(self): res = traverseBFSWrapper(self.tree.lookup['root']) self.assertEqual(res, ['root', 'A', 'B', 'C', 'D', 'E', 'F']) if __name__ == '__main__': unittest.main()
true
04579d8473f8381056422aa6555863a59c43ca59
pujithasak/PythonDeepLearningProgramming
/Python_Programming/Python_ICP_2/Source/Question3.py
916
4.4375
4
# Write a python program to find the wordcountin a file for each line and thenprint the output.Finally store the output back to the file. # Taking user input for file name and opening the file that user specified fileName = input("Enter the name of file:") word_frequency = {} file = open(fileName, 'r') # In this for loop for every line in the file converting into lowercase and by using Dictionary word, count are tracked for line in file: words = line.lower().strip().split(" ") for word in words: word_frequency[word] = word_frequency.get(word, 0) + 1 file.close() # The word frequency is written in the same file by opening the file in append mode with open(fileName, 'a') as f: f.write("\n\nWord Frequency in this file is as below:") for word, count in word_frequency.items(): f.write("\n{} = {}".format(word, count)) print("{} = {}".format(word, count)) file.close()
true
2d4cea7386727fc668d9ae106d616a57ffde74cd
pujithasak/PythonDeepLearningProgramming
/Python_Programming/Python_ICP_2/Source/Question2.py
568
4.15625
4
# Question: Write a program that returns every other char of a given string starting with first using a function # This method will take input string as parameter and returns alternate character from the string def string_alternative(input): return input[::2] # In this main method taking input string from user and calling string_alternative method by passing the input string as parameter and the result is printed def main(): string = input("Enter the string:") print('Output is ' + string_alternative(string)) if __name__ == "__main__": main()
true
c57ee267853e2d8299fb0313e1b701b01a09f863
AliceMillers/python
/class_examples.py
2,723
4.15625
4
class Animal(object): def __init__(self, name): self.name = name zebra = Animal("Jeffrey") print (zebra.name) # Class definition class Animal(object): def __init__(self, name, age, is_hungry): self.name = name self.age = age self.is_hungry = is_hungry zebra = Animal("Jeffrey", 2, True) giraffe = Animal("Bruce", 1, False) panda = Animal("Chad", 7, True) print (zebra.name, zebra.age, zebra.is_hungry) print (giraffe.name, giraffe.age, giraffe.is_hungry) print (panda.name, panda.age, panda.is_hungry) #A Methodical Approach class Animal(object): is_alive = True def __init__(self, name, age): self.name = name self.age = age def description(self): print (self.name) print (self.age) hippo = Animal("Ostin", 7) print (hippo.name, hippo.age) #shoppincart class ShoppingCart(object): items_in_cart = {} def __init__(self, customer_name): self.customer_name = customer_name def add_item(self, product, price): """Add product to the cart.""" if not product in self.items_in_cart: self.items_in_cart[product] = price print (product + " added.") else: print (product + " is already in the cart.") def remove_item(self, product): """Remove product from the cart.""" if product in self.items_in_cart: del self.items_in_cart[product] print (product + " removed.") else: print (product + " is not in the cart.") my_cart = ShoppingCart("Patrick") my_cart.add_item("Milk", 15.9) my_cart.add_item("Bread", 6) my_cart.add_item("Vodka", 22.5) my_cart.remove_item("Vodka") #about job class Employee(object): """Models real-life employees!""" def __init__(self, employee_name): self.employee_name = employee_name def calculate_wage(self, hours): self.hours = hours return hours * 20.00 # Add your code below! class PartTimeEmployee(Employee): def calculate_wage(self, hours): self.hours = hours return hours * 12.00 def full_time_wage(self, hours): return super(PartTimeEmployee, self).calculate_wage(hours) milton = PartTimeEmployee("Jack") print (milton.full_time_wage(10)) #triangle function class Triangle(object): def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 number_of_sides = 3 def check_angles(self): if self.angle1 + self.angle2 + self.angle3 == 180: return True else: return False my_triangle = Triangle(90, 30, 60) print (my_triangle.number_of_sides) print (my_triangle.check_angles())
false
fda25defe3f21558072dc520a6d9cc3681593a30
juanedflores/Code-Katas
/python/005_wholikesit.py
1,829
4.21875
4
# Code Kata #5 - 6 kyu # description: You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. # Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples: # likes([]) # must be "no one likes this" # likes(["Peter"]) # must be "Peter likes this" # likes(["Jacob", "Alex"]) # must be "Jacob and Alex like this" # likes(["Max", "John", "Mark"]) # must be "Max, John and Mark like this" # likes(["Alex", "Jacob", "Mark", "Max"]) # must be "Alex, Jacob and 2 others like this" # For 4 or more names, the number in `and 2 others` simply increases. # My Solution: def likes(names): listlength = len(names) text = "" if (listlength == 0): text = "no one likes this" elif (listlength == 1): text = f"{names[0]} like this" elif (listlength == 2): text = f"{names[0]} and {names[1]} like this" elif (listlength == 3): text = f"{names[0]}, {names[1]}, and {names[2]} like this" else: text = f"{names[0]}, {names[1]}, and {listlength-2} others like this" return(text) # Top Solution: def likes1(names): n = len(names) return { 0: 'no one likes this', 1: '{} likes this', 2: '{} and {} like this', 3: '{}, {} and {} like this', 4: '{}, {} and {others} others like this' }[min(4, n)].format(*names[:3], others=n-2) # print(likes(["juan", "tomas"])) print(likes(["juan", "tomas", "diana", "jose"])) # What I learned: # * String literals Literal String Interpolation. # * Using dictionary mapping as switch #  * The min() function
true
56b8432e394fe8202b3996b61799a3e93117ee86
plaer182/Python-OOP
/person(hw6).py
1,426
4.3125
4
#!/usr/bin/env python3 """ Написать код на Python который имплементирует классы Person, Programmer, Dancer. Написать функцию main в которой создаются объекты из класса Programmer, Dancer и запускает по одному любому методу из каждого объекта. """ class Person: name = "" designation = "" def learn(self): print("Learning...") def walk(self): print("I am in walking...") def eat(self): print("Eating, don`t disturb!") class Singer(Person): band_name = "" def sing(self): print("la la la") def play_guitar(self): print("Playing guitar...") class Dancer(Person): group_name = "" def dancing(self): print("I am dancing Hip-Hop...") def sing(self): print("I am not sing, I am dance...") class Programmer(Person): company_name = "" def codding(self): print("I am codding in Python...") def use_spaces(self): print("I am use spaces, not tabs....") if __name__ == '__main__': singer = Singer() singer.sing() singer.learn() dancer = Dancer() dancer.dancing() dancer.learn() programmer = Programmer() programmer.codding() programmer.learn()
false
0f506331a9498fa5ffde315d3833bafc51878316
learnpython101/PythonFundamentals
/Module 02/Methods/05 Count.py
1,000
4.34375
4
"""""" """ The count() method returns the number of times the specified element appears in the list. The syntax of the count() method is: list.count(element) count() Parameters The count() method takes a single argument: - element - the element to be counted Return value from count() The count() method returns the number of times element appears in the list. """ # Example 1: Use of count() # vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # count element 'i' count = vowels.count('i') # print count print(f'The count of i is:{count}') # count element 'p' count = vowels.count('p') # print count print(f'The count of p is:{count}') # Example 2: Count Tuple and List Elements Inside List # random list random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]] # count element ('a', 'b') count = random.count(('a', 'b')) # print count print(f"The count of ('a', 'b') is:{count}") # count element [3, 4] count = random.count([3, 4]) # print count print(f"The count of [3, 4] is:{count}")
true
e7d85372c292e84bd030b13b43b64b01c8f41045
learnpython101/PythonFundamentals
/Module 04/Code snippets/Variable Function Arguments/01 Default Arguments.py
442
4.53125
5
"""""" """ Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=) """ def greet(name, msg="Good morning!"): """ This function greets to the person with the provided message. If the message is not provided, it defaults to "Good morning!" """ print(f"Hello {name},{msg}") greet("Kate") greet("Bruce", "How do you do?")
true
4a3972f13b9da7c588f89d2438058c8d49ff8492
learnpython101/PythonFundamentals
/Module 01/02 Code snippets/03 What are Data types and how do they relate to variable/Example 16 - Dict.py
434
4.34375
4
#Example 16 dict = {"fruits":["apple", "banana"],'qty':100} print("Fruits: ",dict['fruits']) print("Quantity: ", dict['qty']) print ("Dictionary: ",dict)# print all elements of the dictionary print ("Keys: ",dict.keys()) # print all the keys of the dictionary print ("values: ",dict.values()) # print all the values of the dictionary print ("key value pairs: ",dict.items()) # print all the key values pair elements of the dictionary
false
2ec6dc01caba3e2f13d70cb31d6fca56a02b4432
learnpython101/PythonFundamentals
/Module 03/Code snippets/02 AccessingElements.py
293
4.125
4
# get vs [] for retrieving elements my_dict = {'name': 'Jack', 'age': 26} # Output: Jack print(my_dict['name']) # Output: 26 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict['address'])
true
6857d846c13334940e87b995a140831853599448
navkar/Python3
/numpy/subset.py
482
4.25
4
import numpy arr = [[1,3],[2,4],[3,5]] arr2d = numpy.array(arr) # prints 2d array # [[1 3] # [2 4] # [3 5]] print("numpy 2d array") print(arr2d[:]) # same as print(arr2d) print("Row 0") print(arr2d[0,:]) # prints row index 1 # [2 4] print("Row 1") print(arr2d[1,:]) # prints all elements of the first column # [1 2 3] print("elements of 1st Column") print(arr2d[:,0]) # prints all elements of the second column # [3 4 5]. print("elements of 2nd Column") print(arr2d[:,1])
true
5f77ed250ab0f62adc144d473baa82249cceacad
jLoven/python_text_game
/game1.py
1,981
4.1875
4
# Jackie Loven # 6 September 2014 # Last Edited 7 September 2014 # Text-Based Conversation """You can have a nice conversation with a computer.""" import re #----- Functions -----# def isItYes(user_input): # Tests if the user input is "yes". Returns 1 for yes, 0 for no. if "Ye" in user_input or "ye" in user_input or "yE" in user_input: return 1 else: return 0 def youLikeTo(user_input): # If the user input is in form "I like to ..." it outputs "to ..." i_like, like_, to_hobby = user_input.partition("like ") return to_hobby def youLike(user_input): # If the user input is in form "I do/like ...ing" it outputs "...ing" and anything after hobbying = user_input[user_input.rfind(' ', 0, user_input.index('ing')) + 1:] hobbying_sanitized = re.sub(r'[^\w\hobbying]','',hobbying) return hobbying def hobbyInputParse(user_input): # Tests which type the user input is and returns proper spliced strings if "ing" in user_input: return youLike(user_input) else: return youLikeTo(user_input) #----- User-Input Variables -----# # Asks the user for their name and repeats it back without punctuation input_name = raw_input("Hi! What's your name? ") name_sanitized = re.sub("[^a-z']", "", input_name.lower()) final_name = name_sanitized[0].upper() + name_sanitized[1:] print ("It\'s nice to meet you, {}!".format(final_name)) # Asks the user a yes or no question input_hobby_yn = raw_input("Do you have any hobbies? ") #----- Computer Responses -----# # If the user reports they have a hobby, computer says it's cool - if not, it is disappointed if isItYes(input_hobby_yn) == 1: print ("That\'s so cool! I like juggling.") else: print ("Aw, come on! Don't you like cooking or running or doodling?") # Prompts the user for their hobby and repeats it after parsing input_hobby = raw_input("What do you like to do? ") print ("Wow! You like {}?".format(hobbyInputParse(input_hobby)))
true
5a4911de2285b41a5b9f5061beca6e0c22d01041
ppinko/python_exercises
/dynamic_programming/cover_distance/cover_distance_alternative_simpler_solution.py
701
4.125
4
""" Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps. """ # A Dynamic Programming based on Python3 # program to count number of ways to # cover a distance with 1, 2 and 3 steps def printCountDP(dist): count = [0] * (dist + 1) # Initialize base values. There is # one way to cover 0 and 1 distances # and two ways to cover 2 distance count[0] = 1 count[1] = 1 count[2] = 2 # Fill the count array in bottom # up manner for i in range(3, dist + 1): count[i] = (count[i - 1] + count[i - 2] + count[i - 3]) return count[dist]; # driver program dist = 4 print(printCountDP(dist))
true
4f10d8361139ffc324ba47dc7d08f277dda55be6
ppinko/python_exercises
/math/math_simple_transformation.py
768
4.15625
4
""" Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24 """ def square_root(): import math x = input("Please enter a few comma separeted number: ") ls = x.split(",") C = 50 H = 30 def sr(D, C, H): base = 2 * C * D / H return math.sqrt(base) ls2 = [ str(math.floor(sr(int(D), C, H))) for D in ls ] ans = ",".join(ls2) print(ans) square_root()
true
4927acd0d38146acf7a4ac5a3beab3e1ea45709e
ppinko/python_exercises
/string/string_password_checker.py
2,223
4.375
4
""" Question: A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password: 1. At least 1 letter between [a-z] 2. At least 1 number between [0-9] 1. At least 1 letter between [A-Z] 3. At least 1 character from [$#@] 4. Minimum length of transaction password: 6 5. Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. Example If the following passwords are given as input to the program: ABd1234@1,a F1#,2w3E*,2We3345 Then, the output of the program should be: ABd1234@1 """ def check_passwd(): x = str(input("Please enter a string of passwds separeted by comma: ")) ls_passwd = x.split(',') correct_passwd = [] def req_passwd(passwd): if len(passwd) < 6 or len(passwd) > 12: return flags = {"lower":False, "upper":False, "digit":False, "symbol":False} for char in passwd: if char.islower(): flags["lower"] = True elif char.isupper(): flags["upper"] = True elif char.isdigit(): flags["digit"] = True elif char in "$#@": flags["symbol"] = True for i in flags.values(): if i != True: return return passwd for passwd in ls_passwd: if req_passwd(passwd) == passwd: correct_passwd.append(passwd) return ",".join(correct_passwd) print(check_passwd()) """ # ALTERNATIVE SOLUTION Solutions: import re value = [] items=[x for x in raw_input().split(',')] for p in items: if len(p)<6 or len(p)>12: continue else: pass if not re.search("[a-z]",p): continue elif not re.search("[0-9]",p): continue elif not re.search("[A-Z]",p): continue elif not re.search("[$#@]",p): continue elif re.search("\s",p): continue else: pass value.append(p) print ",".join(value) """
true
d32e4db3a58bd8e6e36e5c97fdc5dbdefc6ec5c2
ppinko/python_exercises
/dynamic_programming/cover_distance/cover_distance_naive_recursion_first_solution.py
406
4.125
4
""" Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps. """ def cover_distance(steps: int) -> int: if steps == 0: return 1 elif steps < 0: return 0 else: return cover_distance(steps - 1) + cover_distance(steps - 2) + cover_distance(steps - 3) assert cover_distance(3) == 4 assert cover_distance(4) == 7 print('Success')
true
10ef845d936bf98c934f05083e7693c9318ecb64
ppinko/python_exercises
/math/hard_is_this_a_right_angled_triangle.py
1,805
4.1875
4
""" https://edabit.com/challenge/ZSC4mb3kR9EHv7q7a """ def is_right_angle(lst: list, option: str) -> bool: if len(lst) == 0: return True if len(lst) > 3: return False if option == 'angle': if sum(lst) > 180: return False elif len(lst) == 3: if sum(lst) != 180 or 90 not in lst: return False else: return True elif len(lst) == 2: if sum(lst) >= 180: return False elif 90 not in lst and sum(lst) > 90: return False else: return True else: if sum(lst) > 90: return False else: return True if option == 'side': if len(lst) < 3: return True else: lst.sort() x = lst.pop() if x^2 == lst[0]^2 + lst[1]^2: return True return False assert is_right_angle([30, 60], "angle") == True assert is_right_angle([30, 60, 90], "angle") == True assert is_right_angle([90], "angle") == True assert is_right_angle([90, 90, 90], "angle") == False assert is_right_angle([20, 20, 20, 20], "angle") == False assert is_right_angle([], "angle") == True assert is_right_angle([90, 90], "angle") == False assert is_right_angle([45, 46], "angle") == False assert is_right_angle([45, 46], "side") == True assert is_right_angle([4, 5, 6], "side") == False assert is_right_angle([], "side") == True assert is_right_angle([3, 4, 5], "side") == True assert is_right_angle([60, 60, 60], "angle") == False assert is_right_angle([177, 2, 1], "angle") == False assert is_right_angle([20, 20, 20, 20], "side") == False assert is_right_angle([43], "angle") == True print('Success')
false
e61ef0bf695188e8db8da1076ed42f2821a34e30
ppinko/python_exercises
/class/exercise_count_number_of_instances.py
847
4.21875
4
""" https://edabit.com/challenge/rprukfcGWqnvKZR9g Create a class named User and create a way to check the number of users (number of instances) were created, so that the value can be accessed as a class attribute. Examples: u1 = User("johnsmith10") User.user_count ➞ 1 u2 = User("marysue1989") User.user_count ➞ 2 u3 = User("milan_rodrick") User.user_count ➞ 3 Make sure that the usernames are accessible via the instance attribute username. u1.username ➞ "johnsmith10" u2.username ➞ "marysue1989" u3.username ➞ "milan_rodrick" """ class User: user_count = 0 def __init__(self, username): self.username = username User.user_count += 1 u1 = User("johnsmith10") u2 = User("marysue1989") u3 = User("milan_rodrick") print(u1.username) print(u2.username) print(u3.username) print(User.user_count)
true
0e227709c9586647aee0b879dfd1bcc18b21ecbf
ppinko/python_exercises
/dynamic_programming/cutting_rod/cutting_rod_my_dp_solution.py
1,387
4.25
4
""" https://www.geeksforgeeks.org/cutting-a-rod-dp-13/ Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 1 5 8 9 10 17 17 20 And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1) length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 3 5 8 9 10 17 17 20 """ def rod(lengths, prices, n): k = len(lengths) dp = [[0 for i in range(n+1)] for _ in range(k+1)] for i in range(1, k+1): for j in range(1, n+1): if lengths[i-1] > j: dp[i][j] = dp[i-1][j] else: dp[i][j] = max(dp[i-1][j], prices[i-1] + dp[i][j-lengths[i-1]]) return dp[k][n] n = 8 lengths = [1, 2, 3, 4, 5, 6, 7, 8] prices1 = [1, 5, 8, 9, 10, 17, 17, 20] prices2 = [3, 5, 8, 9, 10, 17, 17, 20] assert rod(lengths, prices1, n) == 22 assert rod(lengths, prices2, n) == 24 print('Success')
true
3e580024e2754af6d0532301c2882c161324cf2d
ppinko/python_exercises
/validation/hard_semiprimes.py
1,107
4.125
4
""" https://edabit.com/challenge/iZgvZoGZLkDPmAtNu """ def isprime(n: int) -> bool: if n < 2: return False elif n == 2: return True elif n % 2 == 0: return False for i in range(3, n // 2, 2): if n % i == 0: return False return True def semiprime(n: int) -> str: L = [] for i in range(2, n): if n % i == 0: L.append(i) n = n // i while n % i == 0: L.append(i) n = n // i if len(L) == 2 and isprime(L[0]) and L[0] == L[1]: return 'Semiprime' elif len(L) == 2 and (isprime(L[0]) or isprime(L[1])): return 'Squarefree Semiprime' else: return 'Neither' assert semiprime(49) == "Semiprime" assert semiprime(15) == "Squarefree Semiprime" assert semiprime(19) == "Neither" assert semiprime(75) == "Neither" assert semiprime(169) == "Semiprime" assert semiprime(203) == "Squarefree Semiprime" assert semiprime(177) == "Squarefree Semiprime" assert semiprime(125) == "Neither" assert semiprime(70) == "Neither" print('Success')
false
3765ac681940a9c5e118ced054bb67f43aa5d622
k-shah7/Project-Euler
/Euler/q010.py
1,502
4.125
4
import math def check_prime(number): if number is 2: # should use == for comparison to integers return True else: for i in range(2, number): if number % i == 0: return False else: answer = True return answer # current_total = 2 # for number in range(3, 2000001, 2): # if check_prime(number): # current_total += number # print(current_total) # too slow def check_prime2(number): if number == 2 or number == 3: return True elif number % 2 == 0 or number % 3 == 0: return False else: limit = int(number ** 0.5) + 1 for i in range(5, limit, 2): if number % i == 0: return False return True # was check_prime2 faster than check_prime? # way faster, i never even got an answer with check_prime # oh! didn't realise lines 35/36 were different # yeah that makes sense # it's still a bit slow though - research other ways to make a list of prime numbers # there's stuff about how numbers can be written as 6k +/- 1, which # i didn't bother looking at properly, but yeah will do! # not checking if a number is prime - generating a list of primes # yeah still do this when you get a chance # print(check_prime2(87)) current_total = 2 for number in range(3, 2000000, 2): if check_prime2(number): current_total += number print(current_total)
true
502ca9d4811a802551dc3b61bb90d902c8d9f001
k-shah7/Project-Euler
/Euler/q014.py
801
4.125
4
def even(number): return number // 2 def odd(number): return (3 * number) + 1 def collatz_sequence(start): count = 1 current_number = start # print(current_number) while current_number > 0: if current_number == 1: break if current_number % 2 == 0: current_number = even(current_number) count += 1 # print(current_number) else: current_number = odd(current_number) count += 1 # print(current_number) return count max_count = 0 start_number = 0 for i in range(100000, 1000001): if collatz_sequence(i) > max_count: max_count = collatz_sequence(i) start_number = i print(max_count, start_number) # too slow
true
93824315dbbe71687784764b8490f95710751c85
nabeel-malik/my_python
/my_programs/multiplication_table.py
285
4.25
4
user_input = input("Enter a number: ") try: user_input = int(user_input) except ValueError: print("Error: The entered number is not an integer!") else: for x in range (1,11): product = user_input * x print ("{0} x {1} = {2}".format(user_input, x, product))
true
08ded87a807b6c42ca2454c6e8b3080989b6f737
nabeel-malik/my_python
/pybook/6_conditionals_booleans.py
1,990
4.5625
5
print('\n------------------------------------- CONDITIONALS AND BOOLEANS -------------------------------------') ''' Python evaluates the following as FALSE: - False - None - Zero of any numeric object (integer or float) - Any empty sequence. For example '', () or [] - Any empty mapping. For example {} Everything else, by default, will evaluate to TRUE. ''' a = False b = None c = 0 #integer d = [] #empty list e = {} #empty dictionary f = True g = not None h = 5 i = ['Jack', 'Richard'] j = {'name': 'Jack', 'age': 28} print(''' a = False b = None c = 0 #integer d = [] #empty list e = {} #empty dictionary f = True g = not None h = 5 i = ['Jack', 'Richard'] j = {'name': 'Jack', 'age': 28} ''') if a: print('a evaluated to True') else: print('a evaluated to False') if b: print('b evaluated to True') else: print('b evaluated to False') if c: print('c evaluated to True') else: print('c evaluated to False') if d: print('d evaluated to True') else: print('d evaluated to False') if e: print('e evaluated to True') else: print('e evaluated to False') print() if f: print('f evaluated to True') else: print('f evaluated to False') if g: print('g evaluated to True') else: print('g evaluated to False') if h: print('h evaluated to True') else: print('h evaluated to False') if i: print('i evaluated to True') else: print('i evaluated to False') if j: print('j evaluated to True') else: print('j evaluated to False') print("\n####################### DIFFERENCE BETWEEN '==' AND is COMPARISON #######################\n") a = [1,2,3] b = [1,2,3] c = a print(''' a = [1,2,3] b = [1,2,3] c = a ''') print('print(id(a))\t', id(a)) print('print(id(b))\t', id(b)) print('print(id(c))\t', id(c)) print('') print('print(a == b)\t', a == b) print('print(a is b)\t', a is b) print('print(a == c)\t', a == c) print('print(a is c)\t', a is c)
true
602e14666552815f9e25427f5d9badc937c5182c
nabeel-malik/my_python
/pybook/17_OOP_inheritance.py
1,298
4.6875
5
""" INHERITANCE allows us to define a class that inherits all the methods and properties from another class. 'Parent class' is the class being inherited from. 'Child class' is the class that inherits from the 'Parent class'. We can redefine parent class methods inside a child class by simply re-writing them using the same method name. We can also add more methods specific to the child class. """ class Animal: # PARENT CLASS def __init__(self): print('ANIMAL CREATED') def who_am_i(self): print('I am an animal') def eat(self): print('I am eating') class Dog(Animal): # CHILD CLASS inheriting from the PARENT CLASS def __init__(self): Animal.__init__(self) # Creating an instance of Animal() class when an instance of Dog() class is created. print('DOG CREATED') def who_am_i(self): # 'Over-writing' a method inherited from PARENT CLASS, aka 'METHOD OVERRIDING'. print('I am a dog') def bark(self): # 'Adding' a method to the methods inherited from the PARENT CLASS print('WOOF!') mydog = Dog() # Creating an instance of the class Dog() called mydog mydog.who_am_i() mydog.eat() mydog.bark()
true
4c66994da338654b944fa4eadedb69c6bacbbba5
arun786/PythonBasics
/Basics/TrueAndFalse.py
286
4.1875
4
text = input("Enter some text...") if text: print("You entered text {}".format(text)) else: print("You did not enter any text") age = int(input("Enter your age")) if not (age < 18): print("you are old enough to vote") else: print("come back after {}".format(18 - age))
true
8993e25224af340c45600d4fcd011817eb2159bc
arun786/PythonBasics
/SequenceTypes/ListsExplained/ListsEqualsVsMemory.py
577
4.125
4
number1 = [1, 2, 3] number2 = [1, 2, 3] if number1 == number2: print("Contents are the same") else: print("Contents are not the same") # the above will print Contents are the same if number1 is number2: print("Lists point to the same memory") else: print("Lists have different memory allocation") # the above will print, Lists have different memory allocation number3 = number1 if number3 is number1: print("Lists point to the same memory") else: print("Lists point to different memory") # the above will print Lists point to the same memory
true
a653a5e7fbd47fa7592c5047c82a1443686aca23
meghanashastri1/Girls-Who-Code-Stuff
/drawshapes.py
517
4.21875
4
from turtle import * import math # Name your Turtle. t = Turtle() # Set Up your screen and starting position. setup(500,300) x_pos = 0 y_pos = 0 t.setposition(x_pos, y_pos) ### Write your code below: sides = int(input) for shapes in range (sides): t.pencolor("blue") t.pendown() t.forward(100) t.right(90) #angle = 360/sides #pencolor("azure") #pendown() #speed("10") #for shapes in range (sides) #goto(<50>, <100>) #goto(<100>, <0>) #goto(<100>, <0>) # Close window on click. exitonclick()
true
8ed1b6a38fec0c2e9029809cca72016060bee8b3
ryandroll/CS61A_Practice
/lab03/lab03.py
1,039
4.25
4
def hailstone(n): """Print out the hailstone sequence starting at n, and return the number of elements in the sequence. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ "*** YOUR CODE HERE ***" def hflist(n, seqlen): print(n) seqlen += 1 if n == 1: return seqlen elif n % 2 == 1: n = 3 * n + 1 return hflist(n, seqlen) else: n = n // 2 return hflist(n, seqlen) return hflist(n, seqlen = 0) def symmetric(l): """Returns whether a list is symmetric. >>> symmetric([]) True >>> symmetric([1]) True >>> symmetric([1, 4, 5, 1]) False >>> symmetric([1, 4, 4, 1]) True >>> symmetric(['l', 'o', 'l']) True """ "*** YOUR CODE HERE ***" if (len(l) == 0) or (len(l) == 1): return True elif l[0] != l[len(l) - 1]: return False else: return symmetric(l[1:len(l) - 1])
false
cc0c23d26d87a9ead3a0b70c9336aa9cd9aca9ab
saisrikar8/C1-Output
/main.py
599
4.21875
4
#This is a comment, comments are not run by the computer #Output: Information that the computer prints out, what you see on the right hand side print("Hello World") # Name, grade, favorite book, and favorite superhero print("My name is Sai and I am in 7th grade","\nMy favorite book is 'Spy School' by Stuart Gibbs", "\nMy favorite superhero is Iron-Man") print("Hello") print("World") # This is different from the first print statement. The first one is printed on one line. This one is printed on two different lines. # Concatenation: add two strings together using a '+' print("Hello "+ "World")
true