blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
462d2b7e8520f86dd1a470ef9188d1ca4881734a
TheGoodReverend/LetterCode
/LetterCode.py
1,640
4.125
4
#! /user/bin/env python3 #Letter Code by KBowen from LetterCodeLogic import LetterCodeLogic #from filename import class def getChoice(): choice = -1 #while (choice > 0 and choice <3) while (choice!=0): try: choice = int(input("Choice? (1=Encode, 2=Decode, 0=Quit): ")) if (choice <0 or choice >2): print("Illegal input: 1, 2, or 0 please") choice = -1 elif choice ==1: #encode msg = str(input("Plese enter the message you wish to encode: ")) result = LetterCodeLogic.Encode(msg) print("Your encoded message is: \n " + result) elif choice ==2: #decode msg = str(input("Plese enter the message you wish to decode.\nPlease seperate by commas: ")) result = LetterCodeLogic.Decode(msg) print("Your decoded message is: \n " + result) elif choice ==0: return choice else: print("You're traveling through another dimension --" "a dimension not only of sight and sound but of mind." "A journey into a wondrous land whose boundaries are that of imagination." "That's a signpost up ahead: your next stop: the Twilight Zone!") except ValueError: print("Illegal input: 1, 2, or 0 please") def main(): print("Welcome to LetterCode program") print() getChoice() print("Thanks for using the program") if __name__ == "__main__": main()
true
dd9568201e6adbfd7aaf05e57716e20a70e28aa4
yeon4032/STUDY
/GIT_NOTE/03_python/chap03_DateStucutre/exams (1)/exam01_3.py
1,231
4.125
4
''' step01 문제 문3) 리스트(list)에 추가할 원소의 개수를 키보드로 입력 받은 후, 입력 받은 수 만큼 임의 숫자를 리스트에 추가한다. 이후 리스트에서 찾을 값을 키보드로 입력한 후 리스트에 해당 값이 있으면 "YES", 없으면 "NO"를 출력하시오. <출력 예시1> list 개수 : 5 1 2 3 4 5 3 <- 찾을 값 YES <출력 예시2> list 개수 : 3 1 2 4 3 <- 찾을 값 NO ''' size = int(input('list 개수 : ')) # list 크기 입력 list=[] for i in range(size): list.append(int(input())) list if int(input()) in list: print('yes') else: print('NO') #예시1 size = int(input('list 개수 : ')) # list 크기 입력 num=[] # 빈 list: 숫자 저장 for i in range(size): #0~4 num.append(int(input('숫자 입력: '))) num #[1, 2, 3, 4, 5] #원소 찾기 if int(input()) in num: print("yes") else: print('no') #예시2 size = int(input('list 개수 : ')) # list 크기 입력 num=[] # 빈 list: 숫자 저장 for i in range(size): #0~4 num.append(int(input('숫자 입력: '))) num #[1, 2, 3, 4, 5] #원소 찾기 if int(input()) in num: print("yes") else: print('no')
false
dd4e8ebb6559bc46730e00239a63d1f576a34fe5
Mr-MayankThakur/My-Python-Scripts
/Algorithms/Sorting/merge_sort.py
1,118
4.5625
5
def merge_sort(lst, reversed = False): """ Sorts the given list using recursive merge sort algorithm. Parameters ---------- lst (iterable)- python which you want to search reversed (bool): sorts the list in ascending order if False Returns ------- sorted_list """ if len(lst) == 1: return lst mid = (0+len(lst))//2 if reversed: return merge(merge_sort(lst[:mid]), merge_sort(lst[mid:]))[::-1] else: return merge(merge_sort(lst[:mid]), merge_sort(lst[mid:])) def merge(lst1, lst2): output = [] i = j = 0 while i<len(lst1) and j < len(lst2): if lst1[i] < lst2[j]: output.append(lst1[i]) i+=1 else: output.append(lst2[j]) j+=1 # checking if elements left in lst1 if i<len(lst1): output += lst1[i:] # checking if elements left in lst2 if j < len(lst2): output += lst2[j:] return output if __name__ == "__main__": l1 = [1,2, 4,6] l2 = [2, 3, 5] l3 = [99,22,33,44,88,55,77,66,11] print(merge_sort(l3, True))
true
b4579540cb8f9b77209d2019ae7528bcf64efd26
chttrjeankr/codechef2k19-dec6
/MUL35/program.py
670
4.28125
4
""" Problem Statement: If we list all the natural number below 20 that are multiples of 3 or 5, we get 3,5,6,9,10,12,15,18. The sum if these multiples is 78. Find the sum of all the multiples of 3 or 5 below N. """ def SumDivisibleBy35(n,target): """ Returns the sum of all the multiples of 3 or 5 below N """ if target > 0: p = target // n return (n*(p*(p+1))) // 2 else: return 0 if __name__ == "__main__": test = int(input()) while test: N = int(input()) target = N-1 print(SumDivisibleBy35(3,target) + SumDivisibleBy35(5,target) - SumDivisibleBy35(15,target)) test = test - 1
true
0a078dc2a9ec31df291f13cedb133988f99900b3
mehaktawakley/Python-Competitive-Programming
/ArmstrongNumber.py
849
4.3125
4
""" For a given 3 digit number, find whether it is armstrong number or not. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371 Input: First line contains an integer, the number of test cases 'T'. T testcases follow. Each test case contains a positive integer N. Output: For each testcase, in a new line, print "Yes" if it is a armstrong number else print "No". Constraints: 1 <= T <= 31 100 <= N < 1000 Example: Input: 1 371 Output: Yes """ t = int(input()) while(t>0): n = int(input()) cube = 0 temp = n while temp>1: temp1 = temp%10 temp //= 10 cube += temp1**3 if cube == n: print("Yes") else: print("No") t-=1
true
ec5e4826b8bbe03f8c0b73d22258bf42b363c73d
rigo5632/CS-2302-Data-Structures
/Lab1/lab1C.py
1,058
4.25
4
# Lab 1 # By: Rigobeto Quiroz # Class: 1:30 PM - 2:50 PM MW # This program will draw a binary Tree. The tree will create a center point # and will generate branches to the left and to the right according to center point # the more recursion calls the more branches the tree will have. Each branch will have # two children and so fourth. # 3A. n = 3 # 3B. n = 4 # 3C. n = 7 import matplotlib.pyplot as plt import numpy as np def binaryTree(ax,x,y,dx,dy,n): if n > 0: #Draws root and left branch ax.plot((x,x-dx),(y,y-dy),color='k') #Draws root and right branch ax.plot((x,x+dx),(y,y-dy),color='k') #Recursion calls for right and left branches binaryTree(ax,x-dx,y-dy,dx/2,dy,n-1) binaryTree(ax,x+dx,y-dy,dx/2,dy,n-1) plt.close("all") calls = int(input('Enter number of recursion calls?')) # x,y - coordinate for midpoints or root x = 50 y = 100 # dx, dy - Affects the next figures Xand Y directions dx = x / 2 dy = y * calls fig, ax = plt.subplots() binaryTree(ax,x,y,x,dy,calls) plt.axis('off') plt.show()
true
834a62bd5a68029a4ad27a7a0b4807b591de29f7
icebowl/python
/ed1/3.4.1.py
530
4.125
4
''' Input a word. If it is "yellow" print "Correct", otherwise print "Nope". What happens if you type in YELLOW? YellOW? Does the capitalizing make a difference? color = input("What color? ") if (color == "yellow"): print ("Correct") else: print ("Nope") color = input("What color? ") cString = color.lower() print(cString) if(cString == "yellow"): print("Correct") else: print("Nope") ''' cString = input("What color? ") print(cString) if(cString == "yellow"): print("Correct") else: print("Nope")
true
2a3dbfc45a73b2173af5b4cd3a0afeaf6869687d
icebowl/python
/ed1/3.5.py
368
4.125
4
# your code goes here ''' Input a grade number (9 - 12) and print Freshman, Sophomore, Junior, Senior. If it is not in [9-12], print Not in High School. ''' g = int(input("What grade are you in ? ")) if(g == 9): print("Freshman") elif (g==10): print("Sophomore") elif (g==11): print("Junior") elif (g==12): print("Senior") else: print("Not in High School.")
true
b7f6a92c8b7e6bca2f68535ecbdaf8d43a39fbdf
icebowl/python
/net/valid-ip.py
923
4.4375
4
# Python program to validate an Ip addess # re module provides support # for regular expressions import re # Make a regular expression # for validating an Ip-address regex = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)''' # Define a function for # validate an Ip addess def check(Ip): # pass the regular expression # and the string in search() method if(re.search(regex, Ip)): print("Valid Ip address") else: print("Invalid Ip address") # Driver Code if __name__ == '__main__' : # Enter the Ip address Ip = "192.168.0.1" # calling run function check(Ip) Ip = "192.101.109.80" check(Ip) Ip = "366.1.2.2" check(Ip)
false
7015096513fd7e28650960e928e4c53010024992
icebowl/python
/tkinter/drive_turtle_1.py
472
4.125
4
#apt install python3-tk import turtle wn = turtle.Screen() # create a turtle t = turtle.Turtle() t.color('green') # set the color t.forward(50) # draw a green line of leng t.up() # lift up the tail t.forward(50) # move forward 50 without drawing t.right(90) # change direction to the right, left works too t.down() # put the tail down t.backward(100) # draw a green line 100 units long wn.exitonclick()
true
19890d597a8050926402d054d783d608cfaf4c66
icebowl/python
/sift/example-ord.py
230
4.21875
4
#Python ord() #The ord() method returns an integer representing Unicode code point for the given Unicode character. print(ord('5')) # code point of alphabet print(ord('A')) # code point of character print(ord('$')) print(ord(0))
true
f6f7f1143b8ee417fb1ed800e7fa0a370de48804
UKDR/eng57_2
/Week_3_Python/lists_basics.py
1,607
4.5625
5
# List # list are exactly what you expect. They are lists # they are organised with index. This means it starts at 0 # syntax # [] = list print(type([])) print([]) # just prints the brackets [] print(len([])) # counts the number of items in the list # example # defining a list and assigning it to a variable contact_list = ['mike', 'kate', 'bell', 'kevin', 123, True] # index = [ 0 , 1 , 2, 3] # changing the entire variable name # you can use refractor to change entire variable name # print all values on the list above print(contact_list) print(type(contact_list)) # prints the type which is list print(type(contact_list[2])) # the type changes to string because you are accessing the data # access one entry of the list # use the index with the list print(contact_list[2]) print(contact_list[-1]) # re-assigning an entry print(contact_list) contact_list[-2] = "Patrick" print(contact_list) contact_list[-1] = "Parent Hotel" # to remove an entry from a list for example "Parent Hotel" contact_list.pop() # put the number on the list print(contact_list) # list.pop(index = -1) # add an entry to the list contact_list.append('Filipe Paiva') # adds Filipe to the list print(contact_list) contact_list.append('kevin') # adds kevin to the list print(contact_list) # list.pop() # remove entry and index 3 # what method? # where in the documentation contact_list.pop(2) # removes the 2nd item on the list # list.remove(object) # this only removes the first variable of that string even if there was two of the same name variables contact_list.remove('kevin') print(contact_list)
true
6f982282d53e973469174fdc4e139ec68699aea0
Jasplet/my-isc-work
/python_work/IO_ex.py
1,961
4.34375
4
#! /usr/bin/python # Exercise on input and output to files print 'Part One. \nReading a csv file' with open( './example_data/weather.csv', 'r') as readfile: #using with means we dont have to worry about closing the file. Readfile is a variable holding the open file pointer data = readfile.read() #Actually reads data from the file print 'The data from weather.csv has been read. Here it is:' print data print 'Part Two. \nReading line-by-line' with open( './example_data/weather.csv', 'r') as readfile: data = readfile.readline().replace("\n","") # Note how we can stack multiple methods from different objects together ! print data while data != "": # while the variable data is NOT empty data = readfile.readline().replace("\n", "") #data2 = data.replace("0", "#") print data print "It's over, it's finally over" print 'Part Three. Reading with a for loop and extracting values' with open('./example_data/weather.csv','r') as readfile: line1 = readfile.readline().replace('\n','') r = line1.strip().split(',')[-1] rain = [r, ] for line in readfile: print line r = line.strip().split(',')[-1] # Strip removes leading and trialing whitespaces. Split divides the string into a list based on the delimiter. in this case a comma. r = float(r) # makes r a float rain.append(r) # appends r to the list rain print rain with open('./example_data/rainfall.txt','w') as writefile: for r in rain: writefile.write( str(r) + '\n') print 'Part Four. \n Writing and Reading Binary Data' # firstly we need to import the module struct! import struct as st # this allows us to pack/unpack binary data bin_data = st.pack('bbbb',123,12,45,34) with open('./example_data/myfirstbinary.dat', 'wb') as wb: wb.write(bin_data) with open('./example_data/myfirstbinary.dat', 'rb') as wr: bin_data2 = wr.read() data = st.unpack('bbbb', bin_data2) print data
true
8d94faca022abfdeff8c5e2da1a179d7a8ab5596
EchoZen/Basics
/13. Dictionary.py
1,367
4.46875
4
# Use {} for dictionary # variable= {"key":"value", "key":"value"...} #1key:value is considered as 1 element in the dictionary # To access value in variable, you can use the key monthConversions= {"Jan": "January", "Feb": "February", "Mar": "March", "Apr": "April", "May": "May", "Jun": "June", "Jul": "July", "Aug": "August", "Sep": "September", "Oct": "October"} #1st way to retrieve value print(monthConversions["Mar"]) #2nd way print(monthConversions.get("Oct")) '''Good way of using get lets you know if your key is not mappable to any values in the dictionary, by adding a comma and a string. eg. monthConversions.get("invalid key", "insert something to let you know it is an invalid key)''' print(monthConversions.get("Aug", "birdwatching")) print(monthConversions.get("Long", "birdwatching")) #By putting something behind the comma, it prints that out if the key is not in the dictionary. #Keys must be immutable- can be strings, integers or tuples #Values can be anything #Dictionaries are mutable mydict={} mydict['bill']= 25 mydict['sun']="moon" print(mydict) print(mydict.items()) print(mydict.keys()) mydict.update(monthConversions) print(mydict)
true
129bdb0deee49b5b715dcf6b070611fc62651c6d
WT955/Codecademy_DataScience_Projects
/Python_SalesShipping.py
1,428
4.125
4
# Sal's Shipping # 1 def ground_shipping(weight): ground_cost = "" if weight <= 2: ground_cost = weight * 1.5 + 20.0 elif weight <= 6: ground_cost = weight * 3.0 + 20.0 elif weight <= 10: ground_cost = weight * 4.0 + 20.0 else: ground_cost = weight * 4.75 + 20.0 return ground_cost # 2 print(ground_shipping(8.4)) # 3 premium_ground_shipping = 125.0 # 4 def drone_shipping(weight): drone_cost = "" if weight <= 2: drone_cost = weight * 4.5 elif weight <= 6: drone_cost = weight * 9.0 elif weight <= 10: drone_cost = weight * 12.0 else: drone_cost = weight * 14.25 return drone_cost # 5 print(drone_shipping(1.5)) # 6 ground_price = "" drone_price = "" def cost_calculator(weight): ground_price = ground_shipping(weight) drone_price = drone_shipping(weight) final_price = "" method = "" if ground_price < drone_price and ground_price < premium_ground_shipping: final_price = ground_price method = "Ground Shipping" elif drone_price < ground_price and drone_price < premium_ground_shipping: final_price = drone_price method = "Drone Shipping" else: final_price = premium_ground_shipping method = "Premium Ground Shipping" return "The cheapest way to ship " + str(weight) + " pound package is using " + method + " and it will cost $" + str(final_price) + ".\n" print(cost_calculator(4.8)) print(cost_calculator(41.5))
false
3e47955a3c3ddaa01d12b198b1e7b09f46d08fa4
MiYoShi8225/python-flask-dev
/unit2(python base)/unit2/basic8.py
1,692
4.1875
4
#セット型 ''' ・同じ値を持たない! ・順序が保持されない! ・集合処理を高速化する! ''' set_a = {'a', 'b', 'c', 'd', 'a', 12} #aが2つあるが実際は1つしか入らない print(set_a) #実行するタイミングで毎回順番が違う print('e' in set_a) #'e'がset_aに入っていないのでFalse print('a' in set_a) #'a'がset_aに入っているのでTrue print(len(set_a)) # add remove discard pop clear set_a.add('A') print(set_a) set_a.remove('a') print(set_a) set_a.discard(12) #discardなら存在しない要素でもエラーにならない!(削除と一緒) print(set_a) val = set_a.pop() #ランダムの値がpopされる(システムが任意で選ぶ) print(val, set_a) print('\n第二章') ''' union :和集合(A|B) 両方の合計した集合 intersection :積集合 両方の領域に含まれるもの(A&B) 両方に存在するもの differende :片方にある集合と片方の集合にない要素を差集合にして返す(A-B) symmetric_differende :どちらか一方にだけある要素の集合(A^B) ''' s = {'a' ,'b' ,'c', 'd'} t = {'c', 'd', 'e', 'f'} #和集合 u = s|t u = s.union(t) print(u) #積集合 u = s&t u = s.intersection(t) print(u) #差集合 u = s - t u = s.difference(t) print(u) #対象差 u = s ^ t u = s.symmetric_difference(t) print(u) # issubset issuperset isdisjoint s = {'apple', 'banana'} t = {'apple', 'banana', 'lemon'} u = {'cherry'} print(s.issubset(t)) #sにtの要素が1つでもあるのでTrue print(s.issuperset(t)) #sの要素がtとすべて一致するとTrue 今回はFalse print(t.issuperset(s)) #tの要素がsとすべて一致するとTrue 今回はTrue
false
a1e8336a366d8c6ce2a7cf086be50799ed654593
KHulsy/Project_Echo
/App/spaceturtles.py
1,096
4.125
4
(Disclaimer: This was found via Google Fu. I in no way, shape or form coded this. This is absolutely not my work. This is inspiration for Project 3). # Click in the righthand window to make it active then use your arrow # keys to control the spaceship! import turtle screen = turtle.Screen() # this assures that the size of the screen will always be 400x400 ... screen.setup(400, 400) # ... which is the same size as our image # now set the background to our space image screen.bgpic("space.jpg") # Or, set the shape of a turtle screen.addshape("rocketship.png") turtle.shape("rocketship.png") move_speed = 10 turn_speed = 10 # these defs control the movement of our "turtle" def forward(): turtle.forward(move_speed) def backward(): turtle.backward(move_speed) def left(): turtle.left(turn_speed) def right(): turtle.right(turn_speed) turtle.penup() turtle.speed(0) turtle.home() # now associate the defs from above with certain keyboard events screen.onkey(forward, "Up") screen.onkey(backward, "Down") screen.onkey(left, "Left") screen.onkey(right, "Right") screen.listen()
true
65e23e31dbc4ac23ae5b274408141566e30d9a99
fgokdata/python
/extra/classes..py
899
4.25
4
# car is object and it has methods (in functions) class car: def __init__(self, brand, model, year): #starts the attribiutes self.brand = brand self.model = model # shows the features when it is created self.year = year def brandmodel(self): return f'brand of the car {self.brand} and the model is {self.model}' car_1 = car('bmw', 'i5', 2020) car_2 = car('mercedes', 'a4', 2019) #car_1.brand = 'bmw' #car_1.model = 'a4' #car_1.year = 2020 #car_2.brand = 'mercedes' #car_2.model = 'i5' #car_2.year = 2019 print(car_1) print(car_1.brand) print(car_1.brandmodel()) #################### class movie: def __init__(self, name, director): self.name = name self.director = director movie_1 = movie('eyes wide shut', 'kubrick') movie_2 = movie('interstellar', 'jolan') print(movie_1.director) print(movie_2.name)
true
8819dedaa14cf1324ef2276dbcc5d2427720b5e7
tomvdmade/LearnPython3
/ex15.py
885
4.4375
4
# from the module named sys, import argv (argument vector > parameters). # argv is a list containing all the command line arguments passed into the python script you're currently running. (run in the command line vs input) from sys import argv # define argv 0 and 1 as script and filename respectively script, filename = argv # create a variable called txt and assign it the file object open returns txt = open(filename) # print(f"Here's youre file {filename}:") # print the context of the returned file in line 8 print(txt.read()) txt.close() # print text print("Type that filename again:") # declare a variable named file_again to user input file_again = input("> ") # create a variable called txt and assign it the file object open returns txt_again = open(file_again) # print the context of the returned file assigned to txt_again print(txt_again.read()) txt_again.close()
true
94f3aaa071e89f5217efc356a35eb97c65ce5e98
rafaelgustavofurlan/basicprogramming
/Programas em Python/02 - If Else/Script9.py
1,056
4.125
4
# A secretaria de meio ambiente que controla o # indice de poluicao mantem 3 grupos de industrias # que sao altamente poluentes do meio ambiente. # O indice de poluicao aceitavel varia de 0.05 ate # 0.25. Se o indice sobe para 0.3 as industrias do # 10 grupo sao intimadas a suspenderem suas atividades, # se o indice crescer para 0.4 as industrias do 1o e 2o # grupo sao intimadas a suspenderem suas atividades, # se o indice atingir 0.5 todos os grupos devem ser # notificados a paralisarem suas atividades. Faca um # algoritmo que leia o indice de poluicao medido e emita # a notificacao adequada aos diferentes grupos de empresas. #entradas indice = float(input("Informe o índice de poluição: ")) #processamento if indice >= 0.3 and indice < 0.4: print("Atenção: Indústrias do 1o grupo devem suspender as atividades.") elif indice >= 0.4 and indice < 0.5: print("Atenção: Indústrias do 1o e 2o grupo devem suspender as atividades.") elif indice >= 0.5: print("Atenção: Todos os grupos devem suspender as atividades.")
false
4287ef8e5e9b41ec960621b9b8893061e8e44042
samsonfrancis/core_python_practice
/src/com/sam/IfElseTest.py
284
4.28125
4
name = "samson" # test if else if name is "samson": print("Name is samson") else: print ("Name is not samson") # test if elif else if name is "samson1": print("Name is samson1") elif name is "samson": print("Name is samson") else: print ("Name is not samson")
false
c4934517e47b92cd457dab5d1a87220f4ba7f465
rcjacques/Hexapod
/Simulation/more testing.py
2,522
4.125
4
from graphics import * import math width = 500 height = 500 NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 win = GraphWin('Polygon Rotation Testing',width,height) def drawGrid(): for i in range(10): line = Line(Point(i*width/10,0),Point(i*width/10,height)) line.draw(win) for j in range(10): line = Line(Point(0,j*height/10),Point(width,j*height/10)) line.draw(win) def grid(row, col): return row*width/10,col*height/10 def rotatePoint(centerPoint,point,angle): """Rotates a point around another centerPoint. Angle is in degrees. Rotation is counter-clockwise""" angle = math.radians(angle) temp_point = point[0]-centerPoint[0] , point[1]-centerPoint[1] temp_point = ( temp_point[0]*math.cos(angle)-temp_point[1]*math.sin(angle) , temp_point[0]*math.sin(angle)+temp_point[1]*math.cos(angle)) temp_point = temp_point[0]+centerPoint[0] , temp_point[1]+centerPoint[1] return temp_point def rotatePolygon(polygon,origin,theta): """Rotates the given polygon which consists of corners represented as (x,y), around the ORIGIN, clock-wise, theta degrees""" rotatedPolygon = [] for corner in polygon : rotatedPolygon.append(rotatePoint(origin,corner,theta)) return rotatedPolygon # def rotatePolygon(polygon,theta): # """Rotates the given polygon which consists of corners represented as (x,y), # around the ORIGIN, clock-wise, theta degrees""" # theta = math.radians(theta) # rotatedPolygon = [] # for corner in polygon : # rotatedPolygon.append(( corner[0]*math.cos(theta)-corner[1]*math.sin(theta) , corner[0]*math.sin(theta)+corner[1]*math.cos(theta)) ) # return rotatedPolygon my_polygon = [(200,200),(300,200),(300,300),(200,300)] # print rotatePolygon(my_polygon,90) def draw_poly(poly): first = None second = None for point in poly: if not first: first = point elif not second: second = point l = Line(Point(first[0],first[1]),Point(second[0],second[1])) l.setWidth(5) l.setFill('black') l.draw(win) else: l = Line(Point(second[0],second[1]),Point(point[0],point[1])) l.setWidth(5) l.setFill('black') l.draw(win) second = point l = Line(Point(second[0],second[1]),Point(first[0],first[1])) l.setWidth(5) l.setFill('black') l.draw(win) def main(): drawGrid() draw_poly(my_polygon) origin = (250,250) draw_poly(rotatePolygon(my_polygon,origin,45)) win.getMouse() win.close() main()
true
4a15586920f3a7803b527a503a2a8f9e62fe0cff
cash2one/BHWGoogleProject
/pyglib/elapsed_time.py
1,202
4.1875
4
# Copyright 2004-2005 Google Inc. # All Rights Reserved. # # Original Author: Mark D. Roth # def ElapsedTime(interval, fractional_seconds=0, abbreviate_days=0): """ Returns a string in the form "HH:MM:SS" for the indicated interval, which is given in seconds. If the time is more than a day, prepends "DD day(s) " to the string. If the fractional_seconds keyword argument is set to true, then two digits of sub-second accuracy will be included in the output. If the abbreviate_days keyword argument is set to true and the interval is more than a day, the number of days will be printed in an abbreviated fashion (e.g., "5d" instead of "5 day(s)"). """ # extract seconds interval, secs = divmod(interval, 60) # extract minutes interval, mins = divmod(interval, 60) # extract hours interval, hrs = divmod(interval, 24) # whatever's left is the days if interval: if abbreviate_days: text = '%dd ' % interval else: text = '%d day(s) ' % interval else: text = '' # construct and return string if fractional_seconds: text += '%02d:%02d:%05.2f' % (hrs, mins, secs) else: text += '%02d:%02d:%02d' % (hrs, mins, secs) return text
true
a332dcb77ef3acc6c6446df070e5d621648be2d4
bymestefe/Python_Task
/random_module_example/rock_paper_scissors.py
1,562
4.21875
4
import random # rock-paper-scissors (taş-kağıt-makas) # whoever reaches 3 is winner (3'e ulaşan kazanır) def control_of_winner(u,p): if u == 0 and p == 1: print("winner of this stage is pc") return 0 elif u == 0 and p == 2: print("winner of this stage is user") return 1 elif u == 1 and p == 0: print("winner of this stage is user") return 1 elif u == 1 and p == 2: print("winner of this stage is pc") return 0 elif u == 2 and p == 0: print("winner of this stage is pc") return 0 elif u == 2 and p == 1: print("winner of this stage is user") return 1 else: print("draw") return -1 score_of_user = 0 score_of_pc = 0 while True: choice_of_user = int(input("0 for rock, 1 for paper, 2 for scissors = ")) choice_of_pc = random.randint(0, 2) winner = control_of_winner(choice_of_user, choice_of_pc) if winner == 1: score_of_user += 1 elif winner == 0: score_of_pc += 1 else: score_of_user += 0 score_of_pc += 0 print("-"*15) print(f"Score of pc = {score_of_pc}") print(f"Score of user = {score_of_user}") if score_of_user == 3: print("") print("USER WON THE GAME") break # if the score reaches 3 the loop will stop if score_of_pc == 3: print("") print("PC WON THE GAME") break # skor 3'e ulaşırsa döngü duracak
true
03ff68ef13e367df0d1b6f953c04392843a48509
gerard-geer/Detergent
/Shower/logger.py
1,737
4.15625
4
from datetime import datetime class Logger: __slots__ = ('filename', 'buffer', 'maxBufferSize') def __init__(maxBufferSize): """ Creates an instance of Logger. The output file will be named the date and time of this instance's creation. Parameters: -maxBufferSize(Integer): The maximum number of messages to accrue before writing to file. """ # Create a file name based on the current date. self.filename = "shower_"+datetime.month+'_'+datetime.day+'_'+ \ datetime.year+'_'+datetime.hour+":"+datetime.minute+ \ ":"+datetime.second+".log" # Instantiate the message buffer self.buffer = [] # Store the maximum buffer size. self.maxBufferSize = maxBufferSize def log(message): """ Logs a message to the buffer that will eventually be written to file. Parameters: -message(String): The message to log. Returns: -None """ self.buffer.append(message) self.checkWrite() def plog(message): """ Logs a message to the buffer through log(), but also prints it to the screen. Parameters: -message(String): The message to log. """ print(message) log(message) def checkWrite(): """ Checks to see if the buffer is full and a write out to file is necessary. If so, the buffer contents are written out to the log file, and the buffer is cleared. Parameters: -None Returns: -None """ if len(self.buffer) > self.maxBufferSize: file = open(filename, 'a') if file != None: for message in buffer: f.write(str(message)) f.close() buffer = [] else: print("Could not write out buffer to file. Perhaps the log file is being used by another program?")
true
ae19d0ea8605c8306f265576d16894dd7657cd14
annehomann/python_crash_course
/02_lists/numbers.py
597
4.375
4
""" for value in range (1,11): print (value) """ # Takes numbers 1-10 and inputs them into a list numbers = list(range(1,11)) print(numbers) # Skipping numbers in a range # Starts with the value 2, adds 2 to the value until it reaches the final value of 11 even_numbers = list(range(2,11,2)) print(even_numbers) # # Starts with the value 1, adds 2 to the value until it reaches the final value of 11 # In both examples, the last value of 2 in the range is what increases each by 2 odd_numbers = list(range(1,11,2)) print(odd_numbers) test_numbers = list(range(0,101,10)) print(test_numbers)
true
3d3d84f1e1df87f19bf47e31b39f5839829af2aa
annehomann/python_crash_course
/03_if_statements/hello_admin.py
538
4.15625
4
# usernames = ['anne', 'somerset', 'admin', 'sally', 'darius'] # for username in usernames: # if 'admin' in username: # print("Hello " + username.title() + ", would you like to see a status report?") # else: # print("Hello " + username + ", thank you for logging in today.") # Using the if statement first allows you to check if the list is empty or not first usernames = [] if usernames: for username in usernames: print("Hello " + username + ".") else: print("We need to find some users!")
true
b2f93d7064571516d7485ceb9338f76f57a3ac33
Umangsharma9533/DataStructuresWithPython
/Stack_isParenthesisBalanced.py
1,144
4.25
4
#Import Stack class from the CreatingStack.py file from CreatingStack import Stack #define a function for comparing 2 character, Return True if both matches, False if no match def is_match(top,paren): if top=='{' and paren=='}': return True elif top=='[' and paren==']': return True elif top=='(' and paren==')': return True else: return False #Define a function to check whether string containing parenthesis is balanced or not #Take string as the input and return True if balanced , False if not balanced def isBalanced(paren_String): s=Stack() is_balanced=True index=0 while index<len(paren_String) and is_balanced==True: paren=paren_String[index] if paren in "[{(": s.push(paren) else: top=s.pop() if not is_match(top,paren): is_balanced=False index+=1 if s.is_empty() and is_balanced==True: return True else: return False #Calling the funtion to check the result #Print True if string is balanced #Print False if string is not balanced print(isBalanced("{{[([)]}}"))
true
3a9fc64d5d991be4f1bab97747ca1d6482f0d172
felixzhao/questions
/Linked_Lists/Merge_Sorted_Array.py
1,136
4.21875
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. time O(M + N), M is |copy_num1| which is less then |nums1| space O(M) logic: - copy values from nums1 - clean up nums1 may make logic simple - 2 pointers - compare and pick smaller into result key points - partial list copy is deep copy already, in python """ copy_num1 = nums1[:m] i = 0 j = 0 k = 0 while i < len(copy_num1) and j < len(nums2): if copy_num1[i] < nums2[j]: nums1[k] = copy_num1[i] i += 1 else: nums1[k] = nums2[j] j += 1 k += 1 while i < len(copy_num1): nums1[k] = copy_num1[i] k += 1 i += 1 while j < len(nums2): nums1[k] = nums2[j] k += 1 j += 1
true
dcf02197a487701312bf636007bdd108880e86c6
felixzhao/questions
/Trees_and_Graphs/Lowest_Common_Ancestor_of_a_Binary_Tree.py
1,124
4.125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.ans = None def find(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> bool: """ Recursive (Good and Clear Approach) logic: - keep 3 flags in each level - mid figure out current node match p or q - l, r figure out either left or right branch match p or q - if 2 of these 3 flags change to True, we found the result (lowest common ancestor) time O(N) space O(N) """ if not root: return False mid = False if root == p or root == q: mid = True l = self.find(root.left, p, q) r = self.find(root.right, p, q) if mid + l + r >= 2: self.ans = root return mid or l or r def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.find(root, p, q) return self.ans
true
da32faa6129dc6ec82c5746137f516d668bc721f
leoanrdoaguayo/Unidad-3
/LIAG_Ejercicios/Patterns/adapter.py
1,186
4.125
4
"""is used to transform an interface into another. Name:Leonardo Israel Aguayo González""" class Korean: """Korean speaker""" def __init__(self): self.name = "Korean" def speak_korean(self): return "An-meyong?" class British: """English speaker""" def __init__(self): self.name = "British" def speak_english(self): return "Hello!" class Adapter: """This change the generic method name to individual method names""" def __init__(self, object, **adapted_method): """Chaneg the name of the metod""" self._object = object self.__dict__.update(adapted_method) def __getattr__(self, attr): """Simply return the rest of attrubtes!""" return getattr(self._object, attr) # List to store speaker object objects = [] # Create a Korean Object korean = Korean() # Create a British object british = British() # Append the object to the objetct list objects.append(Adapter(korean, speak=korean.speak_korean())) objects.append(Adapter(british, speak=british.speak_english())) for obj in objects: print("{} says '{}' \n".format(obj.name, obj.speak()))
false
72d3888348e76741712c9d591a128f0d38a044e6
ajpiter/PythonProTips
/Stats/%ModuloDivison.py
910
4.5
4
#In addition to standard division using '/' in python you can also use '%' to get modulo or remainder division ----- #Leftover Calculator ----- #Think of % as the leftover calcualtor if you shared everything evenly #If you have an 8 slice pizza and 3 friends leftovers = 8 % 3 print(leftovers) #[output] 2 ----- #Team Assignment ---- #You are the 27th person in line. Everyone in line is counted off by 4s to determine which team they are on. #Your team number would be remainder my_team = 27 % 4 print("My team number is:", my_team) #[output] My team number is: 3 #Calculate the team numbers for those around you in line front_team2 = 25 % 4 front_team = 26 % 4 behind_team = 28 % 4 behind_team2 = 29 % 4 print(front_team2, front_team, my_team, behind_team, behind_team2) #[output] 1 2 3 0 1 #notice that team numbers are 0 through 3. There is not a team 4 because 4 divided by 4 is 0.
true
49dde09fe3d711e05f1c055cb46308f6a72d4b86
ajpiter/PythonProTips
/Databases/OrderingResults.py
1,129
4.25
4
#Ordering Query Results in SQL Alchmy #The order_by() command orders from lowest to highest, or alphabetically by default #Example of building a select statement, appending an order_by() clause and executing the statement #By Default this sorts alphabetically stmt = select([tablename.columns.columnname]) stmt = stmt.order_by(tablename.columns.columnname) results = connection.execute(stmt).fetchall() print(results[:10]) #To order by descending, or highest to lowest use desc() from sqlalchemy import desc stmt = select([tablename.columns.columnname]) rev_stmt = stmt.order_by(desc(tablename.columns.columnname)) rev_results = connection.execute(rev_stmt).fetchall() print(rev_results[:10]) #To order by multiple columns you can list multiple columns in the order_by() #columns will be sorted by the first column, and then by the second column if there are duplicates from the first #Example stmt = select([tablename.columns.columnname, tablename.columns.columnname]) stmt = stmt.order_by(tablename.columns.columnname, tablename.columns.columnname) results = connection.execute(stmt).fetchall() print(results[:10])
true
d8a9b8f3f280c85293d01a2f3e108fe53f61fb36
ajpiter/PythonProTips
/PythonBasics/Function/CreatingFunctions/Basics.py
2,762
4.71875
5
#Functions are useful when you will have to preform the same tasks repeatedly #Creating your own Function 1. define the function def function(parameter): print(parameter + "string") 2. call the function, function() ----- #Basic Function: Outputs a Print Statement ----- def function(parameter, parameter2, parameter3): print(parameter + "string" + parameter2 + "string" + paramenter3 + ".") def write_a_book(character, setting, special_skill): print(character + " is in " + setting + " practicing her " + special_skill) write_a_book('Superman', 'Smallville', 'xRayVision') #[output] Superman is in Smallville practicing her xRayVision. ----- #Function Return Statement Instead of Print ----- def write_a_book(character): return character == 'Superman' write_a_book('Batman') #[output] False print("Superman is the main character in your book" + write_a_book('Batman') #[output] Superman is the main character in your book False ----- #Data Type Rules Still Apply in Functions ----- #Functions that return a print() require all parameters to be strings def sales(grocery_store, item_on_sale, cost): print(grocery_store + " is selling " + item_on_sale + " for " + cost) sales("The Farmer’s Market", "toothpaste", "$1") #[output] The Farmer’s Market is selling toothpaste for $1 sales("Amazon", "Alexa", 20) #[output] can only concatenate str (not "int") to str ----- #Keywords as Parameters ----- #By using keywords with default values in the parameters argument of the function, any order could be used when calling the function def findvolume(length=1, width=1, depth=1): print("Length = " + str(length)) print("Width = " + str(width)) print("Depth = " + str(depth)) return length * width * depth; findvolume(length=5, depth=2, width=4) #Length = 5 #Width = 4 #Depth = 2 #40 #All keywords will still need to be defined findvolumne(lenth=5, depth=2) #[output] NameError: name 'findvolumne' is not defined ----- #Saving Outputs as Variables ----- def square_point(x, y, z): x_squared = x * x y_squared = y * y z_squared = z * z # Return all three values: return x_squared, y_squared, z_squared square_point(3, 4, 5) #[output] (9, 16, 25) #There is no ouput when assigning function values to multiple variables three_squared, four_squared, five_squared = square_point(3, 4, 5) #[output] #To see an output call a variable three_squared #[output] 9 #or write a print() with the specified variables print(three_squared, four_squared, five_squared) #[output] (9, 16, 25) #For more information on functions see Code Academy's cheat sheet on functions https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-functions/cheatsheet
true
3b0ac51f4dfe49fcae7757f3c0403267714eb55d
ajpiter/PythonProTips
/Stats/BinomialDistribution.py
760
4.125
4
#A binomial distrubution is the number of r successes in n Bernoulli trials with probability p of success. #Example, The number of heads in 4 coin flips of a fair coin. np.random.binomial(The number of coin flips, the proability of success) np.random.binomial(4, 0.5) #To conduct the experiment repeatedly use the size= argument np.random.binomial(4, 0.5, size=10) #to plot the binomial PMF import numpy as np variables = np.random.binomial(The number of trials, the probability of success, size=10000) #To plot the binomial CDF import matplotlib.pyplot as plt import seaborn as sns sns.set() x, y = ecdfd(samples) _ = plt.plot(x, y, marker='_', linestyle='none') plt.margins(0.02) _ = plt.xlabel('Label') _ = plt.ylabel('Label') plt.show()
true
8ff1b79dabf59fc2ff3d746878d3f891b602c1ad
ajpiter/PythonProTips
/PythonBasics/Lists/CopyingLists.py
617
4.40625
4
#Usually you want to create a new list, but by using the '=' you accidential create a reference to a list ----- #This creates a copy of the reference to the list ----- x = ['a', 'b', 'c'] y = x #Which means this will change the elements in both list x and y y[1] = 'z' print(x) print(y) #output ['a', 'z', 'c'] #output ['a', 'z', 'c'] ----- #This creates a copy of the list ----- x = ['a', 'b', 'c'] y = list(x) #or y = x[:] y[1] = 'z' print(x) print(y) #output ['a', 'b', 'c'] #output ['a', 'z', 'c'] #These are notes from the DataCamp course Introduction to Python, video Mainpulating Lists
true
82c6394b591153d264668ab7784b2efb48df3db2
ajpiter/PythonProTips
/DataVisualization/ScatterPlots.py
820
4.1875
4
#Scatter plots are best used to show the relationship bewteen two numeric variables or #to flag potential errors not found by looking at one variable. #To create a scatter plot using matplotlib import matplotlib.pyplot as plt lista = [2001, 2002, 2003, 2004] listb = [1, 2, 3, 4] plt.plot(lista, listb) plt.show() #To create a scatter plot using pandas import pandas as pd import matplotlib.pyplot as plt variable = pd.read_csv('file.csv') variable.plot(x='columnname', y='columnname2', kind='scatter') plt.xlabel('Label') plt.ylabel('Label') plt.show() #scatter plots can also have roatation variable.plot(kind = 'scatter', x = 'columnname', y = 'columnname', rot = 70) plt.show() #Scatter Plot of a Subset variable_subset.plot(kind = 'scatter', x = 'columnname', y = 'columnname', rot = 70) plt.show()
true
bb9b9d74a269478d6fd491dbf37df0ef5fd2b6ab
ajpiter/PythonProTips
/PythonBasics/Function/Method.py
822
4.125
4
### Methods call functions on objects #Objects (Lists, Strings etc) have built in methods and you cannot run the method on the wrong object type. #A method used on a list will not work on a string. ### List Methods #Example, use the function index() on a list to see the index number of a specified value basiclist = ['a', 1, 'b', 2, 'c', 3] basiclist.index('b') #output would be 2 #Example of using the count() function on a list to determine the number of times a specified value appears basiclist = ['a', 1, 'b', 2, 'c', 3] basiclist.count('b') #output would be 1 ### String Methods #example of using the capitalize() function on a string name = 'amanda' name.capitalize() #output would be 'Amanda' #example of using the replace() method notebook = Jupiter notebook.replace("i", "y") #output would be Jupyter
true
8b1f7b65588a94e86983856c089d94a5ec0bf7dc
ajpiter/PythonProTips
/Stats/ExploratoryDataAnalysis.py
1,289
4.28125
4
#The process of organizing, plotting, and summarizing a data set #Graphicial Exploratory Data Analysis, involves taking data from a table, and converting it into a graph #Below is how to take a table and convert it into a histogram #for EDA _ are used as a placeholder(dummy variable) when you don't care about the variable import matplotlib.pyplot as plt _ = plt.hist(dataframe['columnname']) _ = plt.xlabel('Label') _ = plt.ylabel('Label') plt.show() #Customize the bins, by calling bin_edges, and the calling bins=bin_edges import matplotlib.pyplot as plt bin_edges = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] _ plt.hist(dataframe['columnname'], bins=bin_edges) _ = plt.xlabel('Label') _ = plt.ylabel('Label') plt.show() #Or use the bins keyword argument to specify the number of bins. import matplotlib.pyplot as plt bin_edges = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] _ plt.hist(dataframe['columnname'], bins=20) _ = plt.xlabel('Label') _ = plt.ylabel('Label') plt.show() #You can use the seaborn styling package to customize the historgram #to make the style seaborns default use sns.set() function import matplotlib.pyplot as plt import seaborn as sns sns.set() _ = plt.hist(dataframe['columnname']) _ = plt.xlabel('Label') _ = plt.ylabel('Label') plt.show()
true
a1c5a32f3e9ace0630e97cbe0792b2811203a66b
vikmreddy/D09
/keys.py
1,150
4.375
4
""" Write three functions: sort1(langauges) sort2(languages) sort3(langauges) Goal: Print exactly the below w/ three functions: 1: Arabic English Koine Greek Latin Romanian C++ JavaScript Python R 2: R C++ Latin Arabic Python English Romanian JavaScript Koine Greek 3: JavaScript R Latin Python Romanian Koine Greek English Arabic C++ """ languages = {'JavaScript': 'P', 'Arabic': 'N', 'R': 'P', 'Python': 'P', 'C++': 'P', 'Koine Greek': 'N', 'Latin': 'N', 'Romanian': 'N', 'English': 'N'} print(sorted(languages)) # __getitem__ returns the value of d[key] print(sorted(sorted(languages), key=languages.__getitem__)) print(sorted(languages, key=len)) def sort1b(d): import operator # itemgetter acts on a list of tuples lst = sorted(sorted(d.items()), key=operator.itemgetter(1)) print("1:") for language,t in lst: print("\t"+language) #def last_letter(item): # pass #return item[-1] sort1b(languages)
true
ad7b6bd5d407d631e6c9f8d6ba0d0e7d7a5f29ea
GeorgiusKurli/GeorgiusKurli_ITP2017_Exercises
/4-11. My Pizzas, Your Pizzas.py
437
4.1875
4
#Taken from 4-1. Pizzas pizzas = ["Pepperoni", "Deluxe Cheese", "Tuna Melt"] for pizza in pizzas: print("I like " + pizza + " pizza.") print("\nI love pizza!") friend_pizzas = pizzas[:] pizzas.append("Meat Lover") friend_pizzas.append("Sausage") print("\nMy favourite pizas are:") for pizza in pizzas: print(pizza + " Pizza") print("\nMy friend's favorite pizzas are:") for pizza in friend_pizzas: print(pizza + " Pizza")
true
a720af16e5184b18331943faf8d99774ca269c9f
cococ0j/ThinkPython-answers
/11-11.py
980
4.125
4
""" Setting return True or False is essential in this part. """ from pronounce import read_dictionary def make_word_dict(): fin = open("words.txt") d = {} for line in fin: word = line.strip() word = word.lower() d[word]= word return d def homephones(a, b, phonetic): if a not in phonetic or b not in phonetic: return False if phonetic[a] == phonetic[b]: return True else: return False def find_that_word(word,d,phonetic): word1 = word[1:] if word1 not in d: return False word2 = word[0]+word[2:] if word2 not in d: return False if not homephones(word,word1,phonetic): return False if not homephones(word,word2,phonetic): return False else: return True if __name__ == '__main__': phonetic = read_dictionary() d = make_word_dict() for word in d: if find_that_word(word,d,phonetic): print(word)
true
07262adbfdfe29e9b5394a5103a2f21e405fba1c
enigmatic-cipher/basic_practice_program
/Q59) WAP onvert height (in feet and inches) to centimeters.py
369
4.1875
4
print("Feet & Inch Converter") value = float(input("Enter the value: ")) con = int(input("Press 1 to convert feet into centimeter or Press 2 to convert inch into centimeter: ")) if con == 1: print(f"{value} feet in centimeter is {value * 30.48} cm") elif con == 2: print(f"{value} Inch in centimeter is {value * 2.54} cm") else: print("Invalid Entry")
true
e5e40e8f0b20ac4428a073d467697cbd300e2814
Priya-dharshini-r/practice
/KMP_algo.py
690
4.15625
4
# Knuth Morris and pratt algorithm to find if there is a pattern in given text. ''' Step-1: Find an LPS(Longest purpose prefix which is also suffix) --> Working of LPS: 1. Create an 1D array with the size of the given pattern. LPS = []*len(Pattern) 2. Set LPS[0] = 0 3. Have two variable for iteration i and j respectively. i = 0, j = 1 4. Check for pattern[i], Pattern[j] if both are same, set LPS[j] = i+1 i = i+1, j = j+1 Again back to step - 3 5. If pattern[i] and pattern[j] is not matched, check for i, if i == 0 LPS[j] = 0 j = j+1 # Don't increment j. if i != 0, i = LPS[i-1] back to step - 3 6. Repeat untill all the values in the LSP is Filled. '''
true
f3889a806e21c723449d890ef0bd534f0813d31a
Priya-dharshini-r/practice
/multiply_elements_in_list.py
522
4.28125
4
# defining a function to multiply all the elements in a list def multiply_all_elements_in_a_list(mylist): length = len(mylist) result = 1 for i in range(length): element = mylist[i] result = result*element return result if __name__ == "__main__": n = int(input("Enter number of elements to be in list: ")) mylist = [] for i in range(n): elements = int(input()) mylist.append(elements) print(mylist) multiplied_list = multiply_all_elements_in_a_list(mylist) print("Multiplied elements ",multiplied_list)
true
b65cd1b868ea9e9e33789a7dc81a89089dafce56
Priya-dharshini-r/practice
/linear_search.py
810
4.21875
4
# Initialize a empty list and get elements from the user. list = [] n = int(input("Enter number of elements:")) # Use a for loop to get each element in the list. for i in range(n): elements = int(input()) list.append(elements) print(list) # Ask the element to be searched. search_element = int(input("Enter the element to be searched:")) # set element_found as false element_found = False # Compare the given element to each element in the list by its index position. # if the serached element and the list element are same return "Element-found" and its index position. # if element_found is false print "Element-not-found". for i in range(n): if(list[i] == search_element): element_found = True print("Element found at index",i) break if(element_found == False ): print("Element not found")
true
e1523bf2dc7b1da5c23c7cf3b98509a2108909e7
Comphus/five_tasks
/AWS_Docker_CentOS/flask/app/Task1/task_one.py
980
4.125
4
""" First Python Task. Reads a CSV file and output two CSV files First output file is a copy of the input, and second output file is the transposed version of the CSV file Written by Gabriel Lopez """ import pandas as pd def create_csv(file_name, output_one, output_two): """ The main function used to complete Task #1 Takes in a CSV file, then creates two new files. The first new file is the same as the input file, and the second new file is the transposed version of the input file Args: FileName: The name of the CSV file to read. output_one: The first output file to write to, will contain the contents of FileName. output_two: The second output file to write to, will contain the transposed contents of FileName. """ file = pd.read_csv(file_name, header=None) file.to_csv(output_one, header=False, index=False) file.T.to_csv(output_two, header=False, index=False) if __name__ == "__main__": create_csv("app/gender_submission.csv","Output.csv","Output2.csv")
true
8948bb91ecc62872f15ceebd11947e5e8761bb8f
DongYao01/Meijingzhuang-Python
/Grade.py
494
4.21875
4
score = input('Please enter your scores:') try : score = float(score) if score >= 0.9 and score < 1 : print('Grade is "A"') elif score >= 0.8 and score < 0.9 : print('Grade is "B"') elif score >= 0.7 and score < 0.8 : print('Grade is "C"') elif score >= 0.6 and score < 0.7 : print('Grade is "D"') elif score >= 0 and score < 0.6 : print('Grade is "F"') else : print('Bad score!') except : print('Bad score!')
true
608d42f0253576b66e40ebbe958f4391106babaf
Mehrnoush504/Miniature_Assembler
/assembler/decimal_and_binary_converter.py
239
4.125
4
# function for turning decimal into binary def decimal_to_binary(num): s = bin(num) s = s[2:] print(s) return s # function for turning binary to decimal def binary_to_decimal(binary): return int(binary, 2)
false
d6a0d47b411cb4e43944923922150cae4a1dc820
SimonWong35/daily-coding-problem-examples
/chapter-03-linked-lists/example-3-3-1.py
472
4.21875
4
#!/usr/bin/python def alternate(linkedlist): even = True current = linkedlist while current.next == True: if current.data > current.next.data and even: current.data, current.next.data = current.next.data, current.data elif current.data < current.next.data and not even: current.data, current.next.data = current.next.data, current.data even = not even current = current.next return linkedlist
true
ff506e9d27a830d6054d29c08df363b08043afb9
ark229/CodeAcademy_Python
/concatenating_strings.py
393
4.3125
4
###Write a function called account_generator that takes two inputs, first_name and last_name and ###concatenates the first three letters of each and then returns the new account name. first_name = "Julie" last_name = "Blevins" def account_generator(first_name, last_name): return first_name[:3] + last_name[:3] new_account = account_generator(first_name, last_name) print(new_account)
true
cfb3a939ce87417b8b6f4cf6e7a6da889d31f46b
ark229/CodeAcademy_Python
/iterating_strings_practice.py
299
4.125
4
###Write a new function called get_length() that takes a string as an input and returns the number of characters in that string. ###Do this by iterating through the string, don’t cheat and use len() def get_length(string): counter = 0 for length in string: counter += 1 return counter
true
710015293631e8dac8fac805ff16eaa56cd69a91
Semuca/PyConsole
/assets/jamesstuff/UsefulFile/shimport.py
2,076
4.125
4
import __main__ def Add (items): #Adds all floats passed - Takes two or more parameters if (len(items) >= 2): result = 0 for item in items: try: item = float(item) result = result + item except: return __main__.ThrowInvalidValueError(item) return result else: return __main__.ThrowParametersError("Add", 2, 100) def Divide (items): #Divides the first item by the next, then the product of that by the next, and so on - Takes two or more parameters if (len(items) >= 2): result = float(items[0]) for item in range(len(items) - 1): try: result = result / float(items[item + 1]) except: return __main__.ThrowInvalidValueError(item) return result else: return __main__.ThrowParametersError("Divide", 2, 100) def Multiply (items): #Multiplies all floats passed - Takes two or more parameters if (len(items) >= 2): result = 1 for item in items: try: item = float(item) result = result * item except: return __main__.ThrowInvalidValueError(item) return result else: __main__.InsertText("ERROR: The function 'Multiply' takes at least two items") return __main__.ThrowParametersError("Multiply", 2, 100) def Subtract (items): #Subtracts the first item by the next, then the product of that by the next, and so on - Takes two or more parameters if (len(items) >= 2): result = float(items[0]) for item in range(len(items) - 1): try: result = result - float(items[item + 1]) except: return __main__.ThrowInvalidValueError(item) return result else: return __main__.ThrowParametersError("Subtract", 2, 100) functions = { #Lists the functions to be read by PyConsole "Add" : Add, "Divide" : Divide, "Multiply" : Multiply, "Subtract" : Subtract }
true
8dcc3baccc3c3c0ee09ff4cb2ece986542565f06
0as1s/leetcode
/225_MyStack.py
1,590
4.1875
4
import queue class MyStack: def __init__(self): """ Initialize your data structure here. """ self.q1 = queue.deque() self.q2 = queue.deque() self.last = None def push(self, x: int) -> None: """ Push element x onto stack. """ if self.last is None: self.last = x return self.q1.append(self.last) self.last = x def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ if self.last: temp = self.last self.last = None return temp while len(self.q1) > 1: self.q2.append(self.q1.popleft()) self.q1, self.q2 = self.q2, self.q1 return self.q2.popleft() def top(self) -> int: """ Get the top element. """ if self.last: return self.last while len(self.q1) > 1: self.q2.append(self.q1.popleft()) self.last = self.q1.popleft() # self.q2.append(self.last) self.q1, self.q2 = self.q2, self.q1 return self.last def empty(self) -> bool: """ Returns whether the stack is empty. """ print(self.q1, self.q2, self.last) if self.q1 or self.q2 or self.last: return False return True # Your MyStack object will be instantiated and called as such: obj = MyStack() obj.push(1) obj.push(2) # obj.top() obj.pop() obj.top() print(obj.empty()) obj.pop() print(obj.empty())
true
5bbf71c627eea671325457b209805558dd174d7c
saribalarakeshreddy/Python-3.9.0
/Packages/Patterns_Package/alp/sml_alp/d.py
860
4.125
4
def for_d(): """ Pattern of Small Alphabet: 'd' using for loop """ for i in range(7): for j in range(5): if j==4 or i%3==0 and i>0 and j>0 or j==0 and i in (4,5): print('*',end=' ') else: print(' ',end=' ') print() def while_d(): """ Pattern of Small Alphabet: 'd' using while loop """ i=0 while i<7: j=0 while j<5: if j==4 or i%3==0 and i>0 and j>0 or j==0 and i in (4,5): print('*',end=' ') else: print(' ',end=' ') j+=1 i+=1 print()
false
7fe079dfb56acb38df785ec5b455b606db693c3f
saribalarakeshreddy/Python-3.9.0
/Packages/Patterns_Package/symbols/line_symbols/Square.py
432
4.25
4
def for_Square(): """ Pattern for : Square using for loop""" for i in range(7): for j in range(7): if i in (0,6) or j in(0,6): print('*',end=' ') else: print(' ',end=' ') print() def while_Square(): """ Pattern for : Square using while loop""" i=0 while i<7: j=0 while j<7: if i in (0,6) or j in(0,6): print('*',end=' ') else: print(' ',end=' ') j+=1 i+=1 print()
false
f9012f4d21ce0f3d4536fb9e3208060383460382
saribalarakeshreddy/Python-3.9.0
/Packages/Patterns_Package/alp/sml_alp/f.py
868
4.1875
4
def for_f(): """ Pattern of Small Alphabet: 'f' using for loop""" for i in range(8): for j in range(5): if j==1 and i>0 or i==0 and j in(2,3) or i==1 and j==4 or i==4 and j<4: print('*',end=' ') else: print(' ',end=' ') print() def while_f(): """ Pattern of Small Alphabet: 'f' using while loop""" i=0 while i<8: j=0 while j<5: if j==1 and i>0 or i==0 and j in(2,3) or i==1 and j==4 or i==4 and j<4: print('*',end=' ') else: print(' ',end=' ') j+=1 i+=1 print()
false
8b4571501c14d5419f2a218c46a57a098e1d2c24
zixk/pyBasics
/dataStructs/Stack.py
1,032
4.125
4
class Stack: class Node: def __init__(self, data: int): self.data = data self.next = None def __init__(self): self.top= None def isEmpty(self) -> bool: return self.top is None def peek(self) -> int: return self.top.data def push(self, data: int): node = self.Node(data) node.next = self.top self.top = node def pop(self) -> int: if(self.isEmpty()): raise TypeError("Stack is Empty") data = self.top.data self.top = self.top.next return data def print_values(self): value_to_print = self.top while(value_to_print is not None): print(value_to_print.data) value_to_print = value_to_print.next if __name__ == "__main__": r = Stack() print(r.isEmpty()) r.push(1) r.push(2) print(r.peek()) print("_____") r.push(113) r.push(13) r.print_values() print("_____") r.pop() r.print_values()
false
169580f806ce588eca48e78a42bfe5b754977b16
maato-origin/PythonPractice
/1-16.py
582
4.3125
4
#dictionary型 #初期化 dic={'key1':110,'key2':270,'key3':350} print(dic) #値へのアクセス print(dic['key1']) #print(dic['hoge']) #KeyError #getメソッド dic={'key1':110,'key2':270,'key3':350} print(dic.get('key1')) print(dic.get('hoge')) #値の更新 dic={'key1':110,'key2':270,'key3':350} dic['key1']=200 print(dic['key1']) #dict() dic=dict() dic['key1']=110 dic['key2']=270 dic['key3']=350 d1={'key1':110,'key2':270,'key3':350} d2=dict(d1) print(d2) #dictionaryの要素数 dic={'key1':110,'key2':270,'key3':350} print(len(dic))
false
1cb7d231402624ef09ea9d694dddb3872f495c9e
maato-origin/PythonPractice
/2-4.py
303
4.4375
4
#dictionary型のループ処理 #キーのループ dic = {'key1':110, 'key2':270, 'key3':350} for key in dic: print(key) print(dic[key]) #値のループ for value in dic.values(): print(value) #キーと値のループ for key, value in dic.items(): print(key, value)
false
af449683103bee78b3c995b9b8bc2c2a5a3ab55b
ChrisDel86/EDU.
/Timer_projekt/hello world.py
1,083
4.46875
4
# a simple miles calculator # Program make a simple calculator # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select form of calculation") print("1. Time Usage") print("2. Drive distance") while True: # take input from the user choice = input("Enter choice (1/2):") # check if choice is one of the two options if choice in ('1', '2'): num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '2': print(num1, "/", num2, "=", divide(num1, num2)) # check if user wants another calculation # break the while loop if answer is no next_calculation = input("Let's do next calculation? (yes/no): ") if next_calculation == "no": break else: print("Invalid Input")
true
ef069d6fa48b0bf1b9492df1d0b5bf5f64f7c359
rodobedrossian/python.io
/python.py
568
4.28125
4
# Test básico print("Esto es una suma") numero_uno = 2 numero_dos = 6 resultado = numero_uno + numero_dos print(resultado) print("Hola") print(55) print("Mi nombre es Rodrigo y tengo",24,"años") print("Mi nombre es {} y tengo {} años".format("Rodrigo",24)) print("2 + 2 is {}".format(2*2)) # Booleans a = 45 b = 10 print("{} * {} is {}".format(a,b,a*b)) resultado = a*b numero = 451 print(resultado == numero) # Power Operator print(2**5) # Es como usar el "elevado al" -> ^5 """ Esto se usa para descripciones, en caso de un comentario, usar sólo # """
false
46cf2c58fa3b6bb0a96b2544cef50acd4f547f64
SyedYousha/PythonProjects
/Rock Paper Scissors.py
2,391
4.90625
5
#rock, paper, scissors from random import randint #to import random numbers user = input('rock (r), paper (p), scissors (s)?') #Let's the user input something and assigns #it to whatever option it picked. So the next line, user will show as r, p, or s. print(user, 'against') #Just prints out the user input and the string against. random = randint (1,3) #Sets the range of the random integer to all numbers between #1 and 3, which also includes 1 and 3. if random == 1: computerChoice = 'rock' #Assigning the random integers to a specific string. elif random == 2: computerChoice = 'paper' else: computerChoice = 'scissors' # """COMMENT: The reason why else doesn't have a option like else random == 3: # is because else is used when it has to evaluate EVERYTHING else that is left, if you want # to make this user = input('rock (r), paper (p), scissors (s)?') #Let's the user input something and assigns # it to whatever option it picked. So the next line, user will show as r, p, or s.""" # """COMMENT: The reason why else doesn't have a option like else random == 3: # is because else is used when it has to evaluate EVERYTHING else that is left, if you want # to make this more restrictive, then just use another elif statement.""" print(computerChoice) if user == computerChoice: #So it can output if something is a draw. print('Draw!') elif user == 'rock' and computerChoice == 'scissors': #The colon at the end is important because print('You won!') elif user == 'rock' and computerChoice == 'paper': print('You lost!') elif user == 'paper' and computerChoice == 'rock': print('You won!') elif user == 'paper' and computerChoice == 'scissors': print('You lost!') elif user == 'scissors' and computerChoice == 'paper': print('You won!') elif user == 'scissors' and computerChoice == 'rock': print('You lost!') # """COMMENT: The code above consists of If and else statements that makes sure to include all # possible outcomes of this game, Since there are not that many outcomes, this works but # eventually there should be an easier way of doing this because you cannot just keep writing # IF and ELIF statements for several hundred outcomes. # The colon at the end of the statements is important because you are executing something. # """
true
17b0a29aa63fa0f84a49bab35f6a4eae61a3c6eb
arianjewel/Python_with_oop
/Python_OOP/class_n_object.py
2,041
4.25
4
'''class Car: name='' color='' def __init__(self,name,color): #constructor self.name=name self.color=color def start(self=0): print('Starting the engine') Car.name='Axio' Car.color='black' print('Name of car is',Car.name) print('color:',Car.color) Car.start() print(dir(Car)) my_car=Car() my_car.name='Allion' my_car2=my_car.name print(my_car2) my_car.start()''' '''class Car: name='' color='' def __init__(self,name,color): self.name=name self.color=color def start(self): print('Starting the engine') my_car=Car('Corolla','white') print(my_car.name) print(my_car.color) my_car.start()''' '''class Car: def __init__(self,n,c): self.name=n self.color=c def start(self): print('Starting the engine') my_car=Car('Corolla','white') my_car.year=2017 #add attribute with object out of class print(my_car.name,my_car.color,my_car.year) my_car.start()''' '''class Car: def __init__(self,n,c): self.name=n self.color=c def start(self2): print('Name:',self2.name) print('color:',self2.color) print('Starting the engine') my_car=Car('Corolla','white') my_car.start() my_car2=Car('Premio','black') my_car2.start() my_car3=Car('Allion','blue') my_car3.start()''' class Car: def __init__(self, name,manufacturer,color,year,cc): self.name=name self.manufacturer=manufacturer self.color=color self.year=year self.cc=cc def start(self): print('start engine') def brake(self): print('please brake') def drive(self): print('please drive') def turn(self): print('please turn') def change_gear(self): print('please change gear') my_car=Car('Toyota','Toyota company','Black',2018,800) print(my_car.name,my_car.manufacturer,my_car.color,my_car.year,my_car.cc) my_car.start() my_car.brake() my_car.drive() my_car.turn() my_car.change_gear()
true
3708b7832c2a4fb65565b88ed2c1052095a00e19
GeoffreyRe/python_exercices
/exercice_11_1/distance.py
1,528
4.4375
4
""" exercice 11.1 de la page 174 du livre de référence "apprendre à programmer en python 3" de Gérard swinnen ENONCE : Écrivez une fonction distance() qui permette de calculer la distance entre deux points. (Il faudra vous rappeler le théorème de Pythagore !) Cette fonction attendra évidemment deux objets Point() comme arguments. """ from math import * # importation du module math pour l'utilisation de la fonction sqrt ainsi que fabs # création d'une classe "Point", avec comme argument "Object" qui signifie que cette classe est une classe parente class Point(object): "définition d'un point géométrique" # commentaire sur la classe # définition d'une fonction distance(), qui prendra en paramètre 2 objets de la classe Point # et qui calculera la distance entre ces deux objets grâce au théorème de pythagore def distance(point_1,point_2): return sqrt((fabs(point_1.x - point_2.x))**(2) + (fabs(point_1.y - point_2.y))**2) # calcul de la "taille" de l'hypothénuse ( = distance) p1 = Point() # 1ere instance de la classe Point # assignation d'attributs d'instance "x" et "y" à l'objet p1, ce sont ces coordonnées dans un plan en deux dimensions p1.x = 15.5 p1.y = 12.222 # deuxième instanciation de la classe Point + assignation d'attributs d'instance p2 = Point() p2.x = -125.17 p2.y = 34.26 # appel de la fonction avec les deux objets p1 et p2 en paramètre + "capture" du résultat dans une variable distance_p1_p2 = distance(p1, p2) # affichage de la distance print(distance_p1_p2)
false
bc83b89e87778e75102f04f2124a4e6480c0600d
xx-m-h-u-xx/Natural-Language-Processing
/Supervised-Classification.py
2,411
4.125
4
''' Feature Extraction prog ''' ''' Classification is the task of choosing the correct class label for a given input ''' """The first step in creating a classifier is deciding what features of the input are relevant, and how to encode those features. The following feature extractor function builds a dictionary containing relevant information about a given name:""" # Gender Identification def gender_features(word): return {'last_letter': word[-1]} """ The returned dictionary, known as a feature set, maps from feature names to its values. - Feature names are case-sensitive strings that typically provide a short human-readable description of the feature (i.e. 'last_letter') - Feature values are values with simple types, such as booleans, numbers, and strings # gender_features('Shrek') # {'last_letter': 'k'} """ Prepare a list of examples & corresponding class labels """ from nltk.corpus import names labeled_names = ([(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')]) import random random.shuffle(labeled_names) """ Feature extractor then processes the names data; Divides resulting list of feature sets into training set and test set. The training set is used to train a new "naive Bayes" classifier """ featuresets = [(gender_features(n), gender) for (n, gender) in labeled_names] train_set, test_set = featuresets[500:], featuresets[:500] classifier = nltk.NaiveBayesClassifier.train(train_set) """ Tests alternative names not appeared in training data: classifier.classify(gender_features('Neo')) # 'male' classifier.classify(gender_features('Trinity')) # 'female' """ Systematically evaluates the classifier on much larger quantity of unseen data: """ print(nltk.classify.accuracy(classifier, test_set)) # 0.77 """ Examines the classifier to determine which features it found MOST EFFECTIVE for DISTINGUSIHING names' genders: classifier.show_most_informative_features(5) ''' Most Informative Features last_letter = 'a' female : male = 33.2 : 1.0 last_letter = 'k' male : female = 32.6 : 1.0 last_letter = 'p' male : female = 19.7 : 1.0 last_letter = 'v' male : female = 18.6 : 1.0 last_letter = 'f' male : female = 17.3 : 1.0 '''
true
7d5fa74a8179873d43fe7afee286a1878c400d7f
catherinealvarado/data-structures
/algorithms/sorting/quicksort/test_quick_sort.py
1,238
4.1875
4
import unittest from quick_sort import sort class QuickSortTests(unittest.TestCase): """ These are several tests for the function sort that is an implementation of quick sort. """ def test_empty_list(self): """Is an empty list sorted to an empty list?""" self.assertTrue(sort([])==[]) def test_len_one_list(self): """Does a list of length one return itself?""" self.assertTrue(sort([2])==[2]) def test_len_three_list(self): """List of length three is sorted correctly?""" self.assertTrue(sort([1,5,2])==[1,2,5]) def test_len_four_list(self): """List of length four is sorted correctly?""" self.assertTrue(sort([9,8,7,6])==[6,7,8,9]) def test_sorted_list(self): """A sorted list returns itself?""" self.assertTrue(sort([6,7,8,9])==[6,7,8,9]) def test_general_one(self): """Check if [1,5,2,8,3] if sorted correctly.""" self.assertTrue(sort([1,5,2,8,3])==[1,2,3,5,8]) def test_general_two(self): """"Check if [19,10,2,6,1,9,3,8,4,4] if sorted correctly.""" self.assertTrue(sort([19,10,2,6,1,9,3,8,4,4])==[1,2,3,4,4,6,8,9,10,19]) if __name__ == '__main__': unittest.main()
true
2079d4b550729ad517735ec9bed419062603e9f6
fleimari/PythonMultiThreading
/ex2/main.py
809
4.34375
4
"""" Exercise 2. Write similar program than in exercise 1 but this time use subclass of Thread of threding module and hello_world() -function printing the text should be member function (method) of class you created. The console output should look similar than in exercise 1. Hello World: 0 Hello World: 2 Hello World: 1 Hello World: 3 """ import threading class MyThread(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): print("Hello world from thread", self.name, "!") thread0 = MyThread("0") thread1 = MyThread("1") thread2 = MyThread("2") thread3 = MyThread("3") thread0.start() thread1.start() thread2.start() thread3.start() thread0.join() thread1.join() thread2.join() thread3.join() print("Completed")
true
32577919b341d4c5d58b45008a2df990f5a7c04d
mindful-ai/teq-b5-py-dsc-ml
/WEEK01/difference.py
385
4.25
4
# Program to identify if the result of subtraction # is positive, negative or zero # input a = int(input('Enter first number: ')) b = int(input('Enter second number: ')) # process d = a - b # output print('RESULT:' , d) if( d > 0 ): print('The result is positive') elif(d < 0): print('THe result is negative') else: print('The result is zero')
true
06c7ac7e4f8c5f0e7e614ba75a0ba9bfa9532410
goncalossantos/Algorithms
/Sorting/sorting.py
1,200
4.15625
4
import operator def insertion_sort(array, reverse=False): lt = operator.lt if not reverse else operator.gt for index in range(1, len(array)): currentvalue = array[index] position = index while position > 0 and lt(currentvalue, array[position - 1]): array[position] = array[position - 1] position = position - 1 array[position] = currentvalue return array # TODO: Improve memory usage (how in python?) and do a non recursive version # O(n*log(n)) def merge_sort(array, reverse=False): lt = operator.lt if not reverse else operator.gt def merge(array_merge, L, R): i = 0 j = 0 # Add infinity to end (sentinel) L.append(float("inf")) R.append(float("inf")) for k in range(len(array_merge)): if lt(L[i], R[j]): array_merge[k] = L[i] i += 1 else: array_merge[k] = R[j] j += 1 return array_merge if len(array) > 1: q = len(array) / 2 A1 = merge_sort(array[:q]) A2 = merge_sort(array[q:]) array = merge(array, A1, A2) return array
true
5e7fed9f5a1de854328aa9668bbd222163cf8824
goncalossantos/Algorithms
/Challenges/CCI/Chapter 02/remove.py
519
4.15625
4
from Algorithms.LinkedLists.linked_list import LinkedList def remove(node): if node.next: node.value = node.next.value node.next = node.next.next else: # Node at the end of the list raise Exception("Node not in the middle") def test_remove(): test_list = LinkedList([1, 2, 3, 4, 5]) middle_node = test_list.append(6) test_list.add_multiple([7, 8, 9]) expected = LinkedList([1, 2, 3, 4, 5, 7, 8, 9]) remove(middle_node) assert test_list == expected
true
e1b35ffa48c27ed608f44a04aa84e4077259cd27
Pranay2309/Python_Programs
/tuple concepts.py
426
4.1875
4
t1=10,20,30 #type=tuple t2=(10,20,30) #type=tuple #conversion of list into tuple a=[10,20,30,2,12] print(type(a)) t=tuple(a) print(t,type(t),"length of tuple =",len(t)) print(t[0]) #slice operator in tuple print(t[1:3]) print(t[::-1]) #reversing with the help of slice operator #sorting the tuple b=sorted(a) print("sorted tuple : ",b) print("min of tuple =",min(a),"\n","max of tuple =",max(a))
true
455bcc2376e475467f991bef419e2b4fcf82cbe1
Phil-U-U/leetcode-practice-2
/valid-binary-search-tree.py
1,798
4.3125
4
''' Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3], return false. Example of valid binary search tree: (All left nodes must be less than root; All right nodes must be greater than root ) 10 / \ 5 15 / \ / \ low, high 2 8 12 20 8: [5, 10] / \ 7 9 7: [5, 8] ; 9: [8, 10] Author: Phil H. Cui Date: 01/12/17 ''' # DFS: middle -> left -> right # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isValidBST(self, root): # DFS low, high = float("-inf"), float("inf") return self.helper( root, low, high ) def helper(self, node, low, high): if not node: return True return low < node.val and node.val < high \ and self.helper( node.left, low, node.val ) \ and self.helper( node.right, node.val, high ) if __name__ == "__main__": root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) print 'Expected:{} - Calculated: {}'.format( 'True', Solution().isValidBST( root ) ) root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) print 'Expected:{} - Calculated: {}'.format( 'False', Solution().isValidBST( root ) )
true
a56692a0dc54cb47bf6772fc08582cb44997de14
dragonOrTiger/pythonDemo
/sortFunc.py
951
4.3125
4
#Python内置的sorted()函数就可以对list进行排序, print(sorted([36,5,-12,9,-21])) #sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序 print(sorted([36,5,-12,9,-21],key=abs)) #默认情况下,对字符串排序,是按照ASCII的大小比较的 print(sorted(["bob","about","Zoo","Credit"])) #忽略大小写来对字符串排序 print(sorted(["bob","about","Zoo","Credit"],key=str.lower)) #反向排序,不必改动key函数,可以传入第三个参数reverse=true print(sorted(["bob","about","Zoo","Credit"],key=str.lower,reverse=True)) #我们用一组tuple表示学生名字和成绩,请用sorted()对上述列表分别按名字排序 L = [('Bob',75),('Adam',92),('Bart',66),('Lisa',88)] def by_name(stu): return stu[0].lower() L2 = sorted(L,key=by_name) print(L2) def by_score(stu): return stu[1] L3 = sorted(L,key=by_score) print(L3)
false
a83652453c60311b310f8e4abfedeba9446b3d2f
vandanagarg/practice_python
/learning_python/mit_lectures/functions/Coordinate.py
1,377
4.65625
5
''' Creating a Class/ random abstract datatype of type Coordinate This is an example for OOPS concept in programming ''' class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def distance(self, other): x_diff_sq = (self.x - other.x) ** 2 y_diff_sq = (self.y - other.y) ** 2 return (x_diff_sq + y_diff_sq) ** 0.5 def __str__(self): ''' Python calls __str__ method when used with print on the class object. Here we define that a Coordinate object on print must return below string ''' return "<" + str(self.x) + "," + str(self.y) + ">" c = Coordinate(3, 4) # representation of an object print(c) # <__main__.Coordinate object at 0x000000000238ABC8> o/p without __str__ method # also it makes sense that Coordinate itself is a class and its datatype is # type as datatype of any other datastructure is just type print(Coordinate) # <class '__main__.Coordinate'> print(type(Coordinate)) # <class 'type'> print(type(int)) # <class 'type'> print(type(list)) # <class 'type'> print(type(str)) # <class 'type'> print(type("int")) # <class 'str'> zero = Coordinate(0, 0) print(zero) print(c.distance(zero)) # or print(Coordinate.distance(c, zero)) # to check if an object is a Coordinate print(isinstance(c, Coordinate)) # True as c is an object of type Coordinate
true
084f6702316d76e460457ed6e4281fb4c730c253
vandanagarg/practice_python
/learning_python/classes/Circle.py
425
4.21875
4
class Circle: # Class Object Attribute PI = 3.14 def __init__(self, radius= 1): self.radius = radius self.area = radius*radius*self.PI # self.pi can also be written as Circle.pi #Method def get_circumference(self): return self.radius * self.PI * 2 my_circle = Circle(30) print(my_circle.PI) print(my_circle.radius) print(my_circle.get_circumference()) print(my_circle.area)
true
a0c0c1090d1f7e4a2f336762a2efe66ef4e06875
vandanagarg/practice_python
/learning_python/hacker_rank/problem23.py
692
4.15625
4
''' Given an integer, print the following values for each integer: Decimal Octal Hexadecimal (capitalized) Binary ''' n = int(input()) width = len("{0:b}".format(n)) for i in range(1, n+1): print("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format( i, width=width)) # 2nd option STDIN = 17 # print(bin(STDIN)) w = len(str(bin(STDIN)).replace('0b', '')) # print(oct(int(STDIN))) # print(oct(int(STDIN)).replace('0','', 1)) for i in range(1, STDIN+1): j = str(i).rjust(w, ' ') o = oct(int(i)).replace('0o', '', 1).rjust(w, ' ') h = hex(int(i)).replace('0x', '').upper().rjust(w, ' ') b = bin(int(i)).replace('0b', '').rjust(w, ' ') print(j, o, h, b)
false
c730fc75c052e419e7cd1748421a87bda129739a
vandanagarg/practice_python
/learning_python/data_structures/lists/lists_basic_operations.py
2,763
4.625
5
#Lists ,we have to use [] these brackets to store a bunch of values and thus we create a list of some related data that we wish to have #We can put anything in a list i.e: a number, boolean or a string #list is mutable friends = [ "Peeyush Singla", "PS", "groom", "VG"] friends_two = [ "Peeyush Singla", "PS", "groom", "VG"] print(friends) # o/p is as list # ['Peeyush Singla', 'PS', 'groom', 'VG'] print("My friends are: " + str(friends)) # it prints the whole list # o/p as string : My friends are: ['Peeyush Singla', 'PS', 'groom', 'VG'] # to print a particular value we have to do that by identifying it from their index(starts from 0) print(friends[0]) # prints first value print(friends[-2]) # prints second value from the last (so basically negative index is the values from last and it starts from -1 itself) # to grab a selective inputs #1. lets say from 2nd till last we want to o/p 2. we want to select 2nd and 3rd value print(friends[1:]) # from 2nd value till end print(friends[1:3]) # it will print from index value 1 to 2 and will not inclue 3 , thus will just output 2nd nd 3rd value #to modify any value at a specific location # lets say at 2nd value i want to change from PS to husband friends[1] = "Husband" print(friends[1]) ##list functions lucky_numbers = [4, 8 , 15, 16, 23, 42] friends = [ "Peeyush Singla", "PS", "groom", "VG", "Husband"] #to append a list use function extend friends.extend(lucky_numbers) print(friends) # it adds all values of lucky_numbers list in list friends at the end #add individual elements # append function allows us only to add anything at the end of the list friends.append("Jaana") print(friends) #in order to add any value in between the existing list at some random/ DEFINED place use insert function(will take 2 parameters : value and index value where we wish to insert) friends.insert(1, "Jaana") #thus inserts Jaana at 1st index place and rest all values are pushed off to the right print(friends) #to remove elements #use remove function and pass the value u wish to remove friends.remove("VG") print(friends) friends_two.clear() # to remove all elements or clear the list we use clear function print(friends_two) # o/p is [] friends.pop() # it basically pops /removes last element from the list print(friends) #to see if a value is present in the list , below code will return the index number of the value print(friends.index("VG")) #count the similar number of elements in the list print(friends.count("VG")) #sort ascending friends.sort() print(friends) #to reverse the order (its not in descending order), it just prints all opposite like back to front it prints print(friends) friends.reverse() print(friends) #to make a copy of existing list friends2= friends.copy() print(" friends2 = " + str(friends2) )
true
6594a05a236f4db69f0e71d0f3cc181afc967b2d
vandanagarg/practice_python
/learning_python/functions/functions/multiply.py
244
4.1875
4
#Q5: multiply all numbers in a list numbers = [2,5,8,4] def multiply(numbers): mul_result = 1 for item in range(0, len(numbers)): mul_result = mul_result * int(numbers[item]) return mul_result print(multiply(numbers))
true
d5dd531c6fa57baff853c95fb649ab83d96a50d4
vandanagarg/practice_python
/learning_python/problems/numbers_problems/valid_card.py
2,016
4.1875
4
#Problem 13 #Credit Card Validator - Takes in a credit card number from a common credit card vendor (Visa, MasterCard, American Express, Discoverer) # and validates it to make sure that it is a valid number (look into how credit cards use a checksum). # cc = str(raw_input("Enter a credit card number to validate (Mastercard, Visa, Discover, Amex only): ")) # # # def val_cc(number): # cc_rev = number[::-1] # total = 0 # for i in cc_rev[1::2]: # x = int(i) * 2 # if len(str(x)) == 2: # for a in str(x): # total += int(a) # else: # total += int(x) # # for i in cc_rev[::2]: # total += int(i) # # return total # # # if (int(cc[:2]) >= 51 and int(cc[:2]) <= 55 and len(cc) == 16) or \ # (int(cc[0]) == 4 and (len(cc) == 13 or len(cc) == 16)) or \ # ((int(cc[:2]) == 34 or int(cc[:2]) == 37) and len(cc) == 15) or \ # (int(cc[:4]) == 6011 and len(cc) == 16): # if val_cc(cc) % 10 == 0: # print # "%s is a valid credit card number" % cc # else: # print # "%s is NOT a valid credit card number" % cc # else: # print # "%s is NOT a valid credit card number" % cc def validate(n): intArray = intToArray(n) if len(intArray) % 2 == 0: oddEven(0, intArray) else: oddEven(1, intArray) if sum(intArray) % 10 == 0: return True else: return False def intToArray(n): myArray = str(n) intArray = [] for x in myArray: intArray.append(int(x)) return intArray # Doubles and sums array values # Odd numbers have startIndex 1 def oddEven(startIndex, intArray): for i in range(startIndex, len(intArray), 2): newDigit = intArray[i] * 2 if newDigit < 10: intArray[i] = newDigit else: intArray[i] = sumOfDigits(newDigit) def sumOfDigits(n): return (n / 10) + (n % 10) print(validate(input("Enter CC number to validate\r\n>")))
false
d761b068c2046f5ad0e9886a416f30f647ac1b03
vandanagarg/practice_python
/learning_python/branching_statements/statements.py
1,601
4.25
4
''' Pass/ Continue/ Break statements ''' ''' The break statement in Python terminates the current loop and resumes execution at the next statement ''' print("\n break examples:") # First Example print("\n Example 1st \n") my_sum = 0 for i in range(5, 11, 2): my_sum += i if my_sum == 5: break my_sum += 1 print("Inner sum", my_sum) print("outer sum " + str(my_sum)) # Second Example print("\n Example 2nd \n") for letter in 'Python': if letter == 'h': break print('Current Letter :', letter) print('Outer Letter :', letter) # Third Example print("\n Example 3rd \n") var = 10 while var > 0: print('Current variable value :', var) var = var - 1 if var == 5: break print("Good bye!", var) ''' The continue statement in Python returns the control to the beginning of the while loop. It rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. ''' print("\n Continue example:") my_sum = 0 for i in range(5, 11, 2): my_sum += i if my_sum == 5: continue my_sum += 1 print("Inner sum", my_sum) print("outer sum " + str(my_sum)) '''The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes ''' print("\n pass example:") my_sum = 0 for i in range(5, 11, 2): my_sum += i if my_sum == 5: pass my_sum += 1 print("Inner sum", my_sum) print("outer sum " + str(my_sum))
true
595c7f9c7d393a3c757add264fd0e71e837f49ce
vandanagarg/practice_python
/learning_python/hacker_rank/problem2.py
269
4.15625
4
# swapcase and reversing the string def reverse_words_order_and_swap_cases(sentence): return sentence = "aWESOME is cODING" # print(len(sentence)) s = sentence.split() print(s) s.reverse() print(s) text = " " new = text.join(s) print(new) print(new.swapcase())
true
bb99751daf0c097ce76c2c3e2b3e4fc8de96c452
vandanagarg/practice_python
/learning_python/inheritance/Chef/ChineseChef.py
1,125
4.15625
4
#lets say we have a chinese chef who has all qualities of generic chef (Chef.py) and it makes something extra as well class ChineseChef: def make_chicken(self): print("The chef makes a chicken.") def make_salad(self): print("The chef makes a salad.") def make_special_dish(self): print("The chef makes orange chicken.") def make_fried_rice(self): print("The chef makes fried rice.") # In the above line of codes we have explicitly mentioned all the functions that we inside Chef.py i.e: were already a part of generic chef class. #Now in case we want to use inheritance(use existing generic class) this is how programm will look from Chef import Chef class ChineseChef_import(Chef): # inheriting Chef function from Chef file inside class ChineseChef #but now since the make_special_dish function is different in this class we will need to over ride that function here else it shows the generic function's o/p def make_special_dish(self): print("The chef makes orange chicken.") def make_fried_rice(self): print("The chef makes fried rice.")
true
bd57a1f076b12e7cd5f278b832061c86e921d865
juniorppb/arquivos-python
/ExerciciosPythonMundo1/35. Import math 2.py
493
4.1875
4
from math import sqrt num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raiz quadrada de {} é igual a {:.3f}.'.format(num, raiz)) print('_' * 25) from math import sqrt, floor num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raiz quadrada de {} é igual a {}.'.format(num, floor(raiz))) print('_'* 25) from math import sqrt, ceil num = int(input('Digite um número: ')) raiz = sqrt(num) print('A raiz quadrada de {} é igual a {}.'.format(num, ceil(raiz)))
false
27f25895ffbfb386e04cbf925ebbb6dfbd232f8f
rvaishnavigowda/Hackerrank-SI-Basic
/compute fibonacci number.py
521
4.4375
4
''' For a given positive integer - N. Compute Nth fibonacci number. Input Format Input contains a positive integer - N. Constraints 1 <= N <= 20 Output Format For given input, print the Nth fibonacci number. Sample Input 0 4 Sample Output 0 3 Explanation 0 The fibonacci series: 1, 1, 2, 3, 5, 8,...... At 4th position we have 3. ''' def Fibonacci(n): if n==0: return 0 elif n==1: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) n=int(input()) print(Fibonacci(n))
true
095c60da97bb1967ab80b83b71db16acada6980e
pshushereba/Data-Structures
/singly_linked_list/singly_linked_list.py
2,536
4.15625
4
class ListNode: def __init__(self, value, next=None): self.value = value self.next = next class LinkedList: def __init__(self, node=None): self.head = node self.tail = node self.length = 1 if node is not None else 0 def add_to_tail(self, value): node = ListNode(value) self.length += 1 # if head does not exist, set both head and tail to the node that you created. if self.head is None: self.head = node self.tail = node # if head exists else: # set previous tail next pointer from None to node that you created. self.tail.next = node # set the list tail to the node you created. self.tail = node def add_to_head(self, value): node = ListNode(value) self.length += 1 # check to see if there is a head (Is the list empty right now?) if self.head is None: self.head = node self.tail = node else: # take node that I'm creating and point the next pointer to the current head node.next = self.head # tell the linked list that the inserted node is the new head self.head = node def contains(self, value): current_node = self.head while current_node is not None: if current_node.value == value: return True current_node = current_node.next return False def remove_head(self): # update self.head pointer if self.head is not None: cur_val = self.head self.head = self.head.next if self.head is None: # checking to see if we have removed the last node self.tail = None self.length -= 1 return cur_val.value else: return None def get_max(self): if self.head is None: return None node = self.head incr = 0 value = 0 while incr < self.length: incr += 1 if value < node.value: value = node.value node = node.next return value # def reverse(self, node, prev): # # will need to call reverse(node.next, node) again # if prev is not None: # prev.next = None # if self.head != node: # self.add_to_head(node) # if node is not None: # self.reverse(node.next, node)
true
1ea82532b088aa28d7ecf5e26a59532b969cc4ca
jtutuncumacias/tekturtle
/dict.py
1,446
4.375
4
import turtle #Dictionaries visualization lab (using turtle) #----------STARTER CODE BEGINS----------# grid = turtle.Turtle() grid.color("gray") grid.hideturtle() grid.speed(0) for num in range(-10, 11): grid.penup() grid.goto(-200, num * 20) grid.pendown() grid.goto(200, num * 20) for num in range(-10, 11): grid.penup() grid.goto(num * 20, -200) grid.pendown() grid.goto(num * 20, 200) bob = turtle.Turtle() # our main character bob bob.shape("turtle") sally = turtle.Turtle() sally.shape("turtle") sally.color("blue") sally.penup() sally.goto(100, 0) #sally lives at the coordinates (100, 0) alex = turtle.Turtle() alex.shape("turtle") alex.color("green") alex.penup() alex.goto(160, 80) #alex lives at (160, 80) #----------STARTER CODE ENDS----------# # Exercise 1: get bob to where sally lives addressbook = {'sally': 5, 'carly': 2} for num in range(addressbook['sally']): #bob moves forward the number of steps it takes to get to sally bob.forward(20) # Exercise 2: with lists (turtle goes in 2+ directions) # get bob to where alex lives bob.goto(0, 0) #bob goes back to his original position alex_address = [8, 4] dave_address = [2, 2] addressbook2 = {'alex': alex_address, 'dave': dave_address} for num in range((addressbook2['alex'])[0]): bob.forward(20) bob.left(90) for num in range((addressbook2['alex'])[1]): bob.forward(20)
false
eff62d6bf7cee49e3d70be04d6924ee75392a3f2
mmcgee26/PythonProjects
/6_2.py
2,055
4.28125
4
class Node: def __init__(self,data): self.val = data self.next = None # create a linked list (adding nodes) that is identified as 'head' head = Node(None) n1 = Node(10) n2 = Node(20) n3 = Node(30) head.next = n1 n1.next = n2 n2.next = n3 # print the linked list def print_linked_list(head): node = head.next while True: print (node.val, end=' ') if node.next == None: break node = node.next print_linked_list(head) print('') ##################### code for lecture 6_2 ############################# def add_to_ordered(head, new_node): ''' if head.next == None: # if the Linked_List is empty head.next = new_node # add the new_node to the List and return # terminate the function ''' current = head.next previous = head while True: if current.next == None: new_node.next = None current.next = new_node break elif current.val >= new_node.val: new_node.next = previous.next previous.next = new_node break else: previous = current current = current.next n4 = Node(15) add_to_ordered(head,n4) # add 15 n5 = Node(40) add_to_ordered(head,n5) # add 40 print_linked_list(head) print('') ########################## def search(head, data): node = head.next result = False while True: if node.val == data: result = True break if node.next == None: break node = node.next return result r = search(head,240) print(r) ######################### def size(head): ''' if node.next == None: return 0 ''' node = head.next count = 0 while True: count = count + 1 if node.next == None: break node = node.next return count r = size(head) print('num of nodes :', r)
true
435480dc29ac57b67823cac19ec5b0b114e7d164
mmcgee26/PythonProjects
/hw3example.py
2,226
4.1875
4
print("Post-fix Calculator") print("For help, type \"help\" or \"?\"") while True: str_in = raw_input("> ") tokens = str_in.split(" ") stack = [] if tokens[0] == "help" or tokens[0] == "?": print("Post-fix calculator takes in post-fix formatted equations and evaluates them.") print("Input should be formatted in such a way that the equation can be evaluated fully.") print("Ex. \"1 2 + 4 *\" equals \"12\"") elif tokens[0] == "quit" or tokens[0] == "q": break else: while len(tokens) > 0: item = tokens.pop(0) if item.isdigit(): stack.append(int(item)) elif item == "+": if len(stack) > 1: stack.append(stack.pop() + stack.pop()) else: #ERROR print("ERROR: Invalid expression. Not enough input.") break elif item == "-": if len(stack) > 1: tmp = stack.pop() stack.append(stack.pop() - tmp) else: #ERROR print ("ERROR: Invalid expression. Not enough input.") break elif item == "*": if len(stack) > 1: stack.append(stack.pop() * stack.pop()) else: #ERROR print ("ERROR: Invalid expression. Not enough input.") break elif item == "/": if len(stack) > 1: tmp = stack.pop() stack.append(stack.pop() / tmp) else: #ERROR print ("ERROR: Invalid expression. Not enough input.") break elif item == "^": if len(stack) > 1: tmp = stack.pop() stack.append(pow(stack.pop(), tmp)) else: #ERROR print ("ERROR: Invalid Expression. Not enough input.") break else: #ERROR break print stack.pop()
true
cd28b6cfa1510ca81f8ec70d98e422ed92f167a9
maayansharon10/intro_to_cs_python
/ex2/temperature.py
606
4.3125
4
def is_it_summer_yet(best_temp, first_temp, second_temp, third_temp): """ the function recieves 4 arguments - the first is the 'best temperature' which is the pre-condition. function will return True when the 2nd and 3rd and 4th arg are larger then best_temp. Otherwise will return False """ if (first_temp > best_temp) and (second_temp > best_temp): return True elif (first_temp > best_temp) and (third_temp > best_temp): return True elif (second_temp > best_temp) and (third_temp > best_temp): return True else: return False
true
d45cf56b1772f426995514d004e71895e75f0765
maayansharon10/intro_to_cs_python
/ex2/shapes.py
1,567
4.3125
4
""" זה אוטומטית חוזר לי לNONE לא משנה מה אני מקלידה""" import math def circle_area(): """ receives input from user about the radius and calculates the area of a circle""" radius = float(input("choose radius")) circle_calc = radius*radius*math.pi return circle_calc def rectangle_area(): """receives an input about 2 ribs and caculates the area of a circle""" edge_a = float(input()) edge_b = float(input()) calc_rectangle_area = edge_a*edge_b return calc_rectangle_area def triangle_area(): """all 3 ribs are the same. recives an input about a rib and caculates the area of a circle""" t_edge = float(input("insert triangle edge")) clac_triangle = (((3**0.5)/4) * (t_edge**2)) return clac_triangle def shape_area(): """this function will recieve an input from user regarging the shape, circle, traingle or ractangle, then it will aske the user for mesures and caculate the area of the shape. it reutrns the size of the area""" user_shape = int(input("Choose shape (1=circle, 2=rectangle, " "3=triangle): ")) if user_shape == 1: # will call circle_area and return it's value return circle_area() elif user_shape == 2: # will call rectangle_area and return it's value return rectangle_area() elif user_shape == 3: # will call triangle_area and return it's value return triangle_area() else: return None
true
982fde0bb1d327f7f05692a652c8f74730ef14da
kdgreen58/is210_lesson_06
/task_02.py
818
4.40625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Task 02 code.""" import task_01 import data def get_average(numbers): """Finds the average of a list. Args: numbers(num): A numeric type that reads in number(s). Returns: numeric (float): returns the average of a list Example: >>>get_average(data.task_O1) 2,833,713.08 """ total = 0.0 for num in numbers: total += num return total / len(numbers) TOTAL_AVG = get_average(data.TASK_O1) EVEN_AVG = get_average(task_01.evens_and_odds(data.TASK_O1)) ODD_AVG = get_average(task_01.evens_and_odds(data.TASK_O1, False)) REPORT = '''Task 02 Report --------------------------------- Total AVG: {0:,.2f} Even AVG: {1:,.2f} Odd AVG: {2:,.2f}''' print REPORT.format(TOTAL_AVG, EVEN_AVG, ODD_AVG)
true
f47e7289d64bac0638fa9fdceacfb8297ca0bc1a
Lior303/NumAnalytics
/root/secant_method.py
1,330
4.34375
4
def secant_method(f, x0, x1, epsilon=10**-4, nMax=100): """ secant method to calculate x's (roots) of a function :param f: the function :param x0: start value :param x1: start value :param epsilon: fault degree allowed :param nMax: maximum of iterations """ n=1 while n<=nMax: x2 = x1 - f(x1) * ((x1 - x0) / float(f(x1) - f(x0))) if (abs(f(x2))<epsilon): print("\nThe root is: {}".format(x2)) return x2 else: print("x0: {}, x1: {}".format(x0, x1)) x0=x1 x1=x2 return False if __name__ == "__main__": print("Enter a function f(x): ") func=eval("lambda x: " + input("")) print("Enter start values: x0 and x1") secant_method(func, float(input("x0=")), float(input("x1="))) """ Takes a function f, start values [x0,x1], tolerance value(optional) epsilon and max number of iterations(optional) nMan and returns the root of the equation using the secant method. The function f must be continuous in the section [x0, x1]. Secant method does not uses derivative of function f, therefore if the function f have a complicated derivative or if the derivative is to complex the secant method will be converge faster than the newton-raphson method. f(x1) - f(x0) must be different that zero. """
true
0d52c863746f5bbf169e94e7d61a8569d5a648ea
nevosial/learnpy
/refresh/sets.py
685
4.21875
4
#Sets in 3.6 p = {True, 3, 'nev', 4, 6, 7} q = {False, True, 1,2,'vic', 'zoe',6, 7, 'nev'} # union will return new set with all elements r = p.union(q) print(r) # intersection will return only the common elements found in both s = p.intersection(q) print(s) # difference will return only the uncommon elements found in both t = p.difference(q) print(t) #issubset will return if subset of another print(f"Is {p} subset of {q} :",p.issubset(q)) #adding item to the Set p.add("False") print(p) #remove will take out an item from the Set. p.remove("nev") print(p) #pop will remove arbitary element from the Set. p.pop() print(p) # clear the Set with clear() p.clear() print(p, q)
true
fcbf8c044c03803243cf850f225f6ccdceb6caa0
Shridevi-PythonDev/quotebook
/day6_learning.py
1,640
4.15625
4
### Conditions # if a = 90 b = 60 if b<a: print("Yes a is greater than b") print(b) print(a*b) else: print("b is greater") print(a) #### elif a = 25 b = 18 if b > a: print("if condtion, b greater") elif a == b: print("you are in elif condition, equal") else: print("else condition, a is greater") ### and a = 200 b = 30 c = 20 if a>b and c>b: print("b is smallest, AND condition") else: print("b is not smaller") ### OR a = 200 b = 30 c = 20 if a>b or c>b: print("b is smallest, OR condition") else: print("b is not smaller") ### While loop x = 1 while x < 3: print("you are in while", x) x = x + 1 print(x) ##### Infinite #while True: # print("you are in while") ## While and Else count = 0 while count < 5: print(count, "is lesser than 5") count = count + 1 else: print(count, " You are in else ") ### For loop fruits = ["apple", "banana", "cherry"] for temp in fruits: print(temp) for x in temp: print(x) ##### Control Statements:: ### Break in For loop for letter in "Python": if letter == 'h': break print("current letter", letter) ## Break in While var = 10 var = 5 while var > 0: print("Current variable value: ", var) ##var = var - 1 if var == 5: break print("after break") ### Continue # for letter in "Python": if letter == 'h': continue print("current letter", letter) var = 10 while var > 0: print("Current variable value: ", var) var = var - 1 if var == 5: continue
true
e408596819cc7e6e54a9b5581e90e694854ae231
Desnord/lab-mc102
/lab01/tiago-dalloca.py
1,096
4.34375
4
# DESCRIÇÃO # Escreva um programa que calcule a circunferência C de um determinado # planeta, com base na observação do ângulo A, entre duas localidades C1 e # C2, e na distância D, em estádios, entre elas. # Suponha que as localidades estejam no mesmo meridiano de um planeta # esférico. O seu programa deverá imprimir a circunferência do planeta em # estádios e em quilômetros. # ENTRADA # A entrada do programa será composta da distância D, em estádios, e do # ângulo A, em graus, respectivamente, um número em cada linha. # SAÍDA # A saída mostra a circunferência Ce, em estádios, e Ckm, em quilômetros, # do planeta seguindo o cálculo feito por Eratóstenes para a Terra com uma # casa decimal de precisão. def read_float(): return float(input()) # converte e para km def e_to_km(e): return 0.1764 * e # printa floats com 1 digito depois da vírgula def print_1f(f): print("%.1f" % f) D = read_float() A = read_float() # 360/A = o número de vezes que a distância D # ocorre no planeta E = D * (360 / A) print_1f(E) print_1f(e_to_km(E))
false
3287cbc23a4aaa096004f94cf7ece69f4029ac5f
Kodermatic/SN-web1
/07_HW - Python (write into file)/Storing_data_into_file.py
1,279
4.34375
4
# Plan: # User enters lines of file # User can exit adding new lines with :q # User is asked if file shall be saved. If yes file is saved and user is asked if file shall be printed. path = "./07_HW - Python (write into file)/" new_line = "" file_text = "" while True: if new_line != ":q\n": file_text = file_text + new_line new_line = input("Prease enter line content: ") + "\n" else: while True: save_option = input("Do you want to save entered content? (y/n) :").lower() if save_option in ["y", "yes"]: filename = input("Please enter name of file :") with open(path + filename, "w") as myfile: myfile.write(str(file_text + "\n")) print("File is saved") break elif save_option in ["n", "no"]: new_line = "" file_text = "" break else: print("Entered option is not valid.") while True: print_option = input("Do you want to print content of the file? (y/n): ") if print_option in ["y", "yes"]: with open(path + filename, "r") as myfile: print(myfile.read()) break elif print_option in ["n", "no"]: break else: print("Entered option is not valid.") print("Thank you and goodbye!") break
true
80694ad66007e718d884ced92f79c7ef5c9eab6a
yash872/PyDsa
/Array/Search_a_2D_Matrix.py
1,086
4.15625
4
''' Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: - Integers in each row are sorted from left to right. - The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [[1,3,5,7], [10,11,16,20], [23,30,34,60]], target = 3 Output: true ''' #------------------------------------- # Time-> O(Log(MxN)) | Space-> O(1) #------------------------------------- class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix or target is None: return False rows, cols = len(matrix), len(matrix[0]) low, high = 0, rows * cols - 1 while low <= high: mid = (low + high) // 2 num = matrix[mid // cols][mid % cols] if num == target: return True elif num < target: low = mid + 1 else: high = mid - 1 return False
true
d1274fc5de939a7e26602bc32c150f9f38b98736
thithick/selenium-python
/D1_reverse_method1.py
319
4.25
4
# Method2 # Using function def reverseNumber(number): reverse = 0 while (number > 0): lastDigit = number % 10 reverse = (reverse * 10) + lastDigit number = number // 10 print(reverse) number = int(input("Please input a number to be reversed.\n")) reverseNumber(number);
true
b5dd39b448ae8e248f7a62a5be894596606fbfae
learnMyHobby/if_python
/leapYear.py
498
4.3125
4
# Write a program to check whether the entered year is leap year or not. # leap year means it has to be 366 days and it will occur once every four years year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))
true