blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
870430a89fb57bdadf8863b9ee8a43ccd3bff287
NhatNam-Kyoto/Python-learning
/100 Ex practice/ex8.py
375
4.125
4
'''Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world ''' inp = input('Nhap chuoi: ') l = inp.split(',') l.sort() print(','.join(l))
true
a93dd6d0d3929fb5e0004fc9f86ae9703c0a7a60
Lifefang/python-labs
/CFU07.py
1,880
4.25
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Name: Matthew Rodriguez # Section: 537 # Assignment: CFU-#9 # Date: 10/23/2019 # this program is going to allow the user to enter in values for height in both feet and inches # it will do this until the user enters in 0 0 # the program is then going to return theses values in centimeters user_input = input('Please input the height in the form feet followed by inches separated by row_3 single space:').split() # making the strings row_3 points_to_evaluate cm_list = [] # making row_3 empty points_to_evaluate that will be the final output while user_input[0] and user_input[1] != 0: # making row_3 loop to check the user input every time if user_input[0] and user_input[1] == 0: # if the value of 0 0 is entered the program should stop break # breaking out of the program so no more inputs can be placed, the break will print the final points_to_evaluate of cms print('you have inputted the height of', user_input[0], 'feet', user_input[1], 'inches') inch_conversion = float(user_input[0]) * 12 + float(user_input[1]) # feet times 12 + how ever many inches gets # total inches cm_conversion = inch_conversion * 2.54 # the conversion for inches to cm print('The entered height of', user_input[0], 'feet', user_input[1], 'inches is:', cm_conversion, 'cm.') # output user_input = input( 'Please input another height in the form feet followed by inches:').split() # getting another input for the # points_to_evaluate cm_list.append(float(cm_conversion)) # making the points_to_evaluate append to the final out put print(cm_list) # this is the points_to_evaluate of heights converted to cms
true
0311d830fd6398fc5056583cfe1ac83e2b1ea5bf
Lifefang/python-labs
/Lab3_Act1_e.py
1,031
4.25
4
# By submitting this assignment, all team members agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Names: Isaac Chang # Matthew Rodriguez # James Phillips # Ryan Walterbach # Section: 537 # Assignment: Lab 3, Act 1 # Date: 9/10/2019 # This program converts number of Miles per Hour to Meters per Second print("This program converts number of miles per hour to number of meters per second") Miles_Per_Hour_Input = float(input("Please enter the number of miles per hour to be converted to meters per second:")) Meters_Per_Second_Output = (Miles_Per_Hour_Input * 0.44704) # 1 mile per hour is equivalent to 0.44704 meters per # second print(str(Miles_Per_Hour_Input)+" Milers per hour is equivalent to",str(Meters_Per_Second_Output) + "Meters per " "second.")
true
0e1b7ba647bf813dc211973b5a06720dc2c77eb2
Lifefang/python-labs
/Lab3_Act1_a.py
894
4.125
4
# By submitting this assignment, all team members agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # # Names: Isaac Chang # Matthew Rodriguez # James Phillips # Ryan Walterbach # Section: 537 # Assignment: Lab 3, Act 1 # Date: 9/10/2019 # This program converts number of pounds to number of Newtons print("This program converts number of pounds to number of Newtons") pounds_input = float(input("Please enter the number of pounds to be converted to Newtons:")) # # float must be added because trying to multiply row_3 string by row_3 non-float int cant be complied. Newtons_output = (pounds_input * 4.4482216) # 1 pound is 4.4482216 Newtons print(str(pounds_input)+" Pounds is equivalent to",str(Newtons_output)+"Newtons.")
true
b408bb03477e3949e571946a04c75bb58a32e149
eloybarbosa/Fundamentos-de-programacao-com-Python
/TP1/Atividade 08.py
1,061
4.125
4
#8. Escreva um programa em Python que receba três valores reais X, Y e Z, guarde esses valores numa tupla e verifique se esses valores podem ser os comprimentos dos lados de um triângulo e, neste caso, retorne qual o tipo de triângulo formado. print('Nessa atividade vamos receber três valores reais (X, Y e Z) guardalos em uma tupla, verificar se os valores informados podem ser os comprimentos dos lados de um triângulo e se for o caso retornar qual o tipo de triângulo.') print() X=int(input('Insira o valor de X:')) Y=int(input('Insira o valor de Y:')) Z=int(input('Insira o valor de Z:')) T=() T= (X, Y, Z) if (X>Y+Z) and (Y>Z+X) and (Z>X): print('Essas medidas não formam um triângulo') else: if (X==Y) and (Y==Z): print("De acordo com as medidas informadas o Triangulo é Equilátero") elif (X==Y) or (Y==Z) or (X==Z): print("De acordo com as medidas informadas o Triangulo é Isósceles") elif (X!=Y) and (Y!=Z) and (Z!=X): print("De acordo com as medidas informadas o Triangulo é Escaleno")
false
fa05d06ca10271b82850f978d5a737e47e1d6adb
eloybarbosa/Fundamentos-de-programacao-com-Python
/TP1/Atividade 18.py
1,371
4.15625
4
#18. ) Em jogos antigos era possível ver que os desenhos eram compostos por vários triângulos. Como uma maneira de treinar isso, a partir do N dado pelo usuário desenhe um polígono de lado N composto somente por triângulos como na figura: import math import turtle #referencia: https://github.com/AllenDowney/ThinkPython/blob/master/code/pie.py def polypie(t, n, r): """Draws a pie divided into radial segments. t: Turtle n: number of segments r: length of the radial spokes """ angle = 360.0 / n for i in range(n): isosceles(t, r, angle/2) turtle.left(angle) turtle.speed(100) turtle.done() def isosceles(t, r, angle): """Draws an icosceles triangle. The turtle starts and ends at the peak, facing the middle of the base. t: Turtle r: length of the equal legs angle: peak angle in degrees """ y = r * math.sin(angle * math.pi / 180) turtle.right(angle) turtle.forward(r) turtle.left(90+angle) turtle.forward(2*y) turtle.left(90+angle) turtle.forward(r) turtle.left(180-angle) t= int(input('De quantos lados o poligono será composto? (Obrigatóriamente acima de 4 lados.) ')) if t > 4: polypie(turtle, t, 100) else: print('Favor executar novamente e digitar um valor maior que 4 conforme solicitado. ')
false
3fa6134a2488116dbe43bca9e3cb24676b1bfbae
eloybarbosa/Fundamentos-de-programacao-com-Python
/TP1/Atividade 05.2.py
1,024
4.25
4
#5.2. Dada uma tupla, retorne 2 tuplas onde cada uma representa uma metade da tupla original. print('Nessa atividade vamos criar uma tupla inserindo quanto elemento desejarmos, a tupla e encerrada quando for digitada a palava "sair". ') print('Depois o programa vai nos retornar 2 tuplas onde cada uma representa uma metade da tupla original. ') print() t=() i=0 t1=() t2=() while i % 2 == 0: print('A tupla precisa obrigatóriamente de um numero par de elementos') t= () ## len(t) = (len(t))+1 elemento = input("Entre com o primeiro elemento: ") while elemento != "sair": t+=(elemento,) elemento = input("Entre com o próximo elemento: ") i=len(t) i=i+1 ##print(len(t)) r=int(len(t)/2) ##print(r) print() t1=(t[:r]) print('A primeira metade da tupla é: ',t1) t2=(t[-r:]) print('A segunda metade da tupla é:',t2) ##for i1 in range (0,r): ## print(i1, end=' ') ## ##t = (10, 20, 30, 40) ## ##t1 = (t[0], t[1]) ## ##t2 = (t[2], t[3]) ## ##print(len(t)) ##
false
41c89e83236a971c90349a0cef1c89753a191993
lcgarcia05/370-Group5Project
/name/backend_classes/temporary_storage.py
1,293
4.15625
4
from name.backend_classes.playlist import Playlist class TemporaryStorage: """ A class which will handle the temporary storage of a created playlist and store the list of songs in a text file. """ def __init__(self, temp_playlist): """ Initializes the temp_playlist class and converts playlist to a string. temp_playlist: A playlist object """ self.temp_playlist = temp_playlist self.my_string = self.convert_to_string() def convert_to_string(self): """Retrieves the necessary data from the playlist object and converts it to a string for display in a file. """ song_names = [i.song_name for i in self.temp_playlist.songs] to_print = "Playlist name: " + self.temp_playlist.playlist_name + "\n" to_print = to_print + "Songs: " + "\n" for song_name in song_names: to_print = to_print + " " + song_name + "\n" return to_print def save_to_file(self): """Saves the current playlist to a .txt file with the same name as the playlist. """ file_name = self.temp_playlist.playlist_name f = open(file_name + ".txt", "w") f.write(self.my_string) f.close()
true
6a350be7b75cc55510365c0992478dea32fabef0
apatten001/strings_vars_ints_floats
/strings.py
786
4.3125
4
print('Exercise is a good thing that everyone can benefit from.') var1 = "This is turning a string into a variable" print(var1) # now i'm going to add two strings together print("I know im going to enjoy coding " + ","+ " especially once I've put the time in to learn.") # now lets print to add 2 blank lines in between strings print('\n' * 2) var2 = "This is the string after the blank lines" print(var2) # here I am going to format with the strings print('\n') print("{} is a great {} to learn for my {} coding experience".format("Python","language", "first")) # now lets use % to add characters strings intergers and floats print("My favorite letter is %c. I love to %s. I'm going to the bahamas in %i months. My college gpa was %.2f" %('A','read', 3, 3.61))
true
d2ad7cfbd2bb9c727dc6e60d38da40a323b3105d
CaseyNord-inc/treehouse
/Write Better Python/docstrings.py
457
4.3125
4
# From Docstrings video in Writing Better Python course. def does_something(arg): """Takes one argument and does something based on type. If arg is a string, returns arg * 3; If arg is an int or float, returns arg + 10 """ if isinstance(arg, (int, float)): return arg + 10 elif isinstance(arg, str): return str * 3 else: raise TypeError("does_something only takes int, floats, and strings")
true
c9b4ec541b0b9ab0f390b6792fe553789c2c3302
Rrawla2/cs-guided-project-python-i
/src/demonstration_1.py
1,696
4.375
4
""" Define a function that transforms a given string into a new string where the original string was split into strings of a specified size. For example: If the input string was this: "supercalifragilisticexpialidocious" and the specified size was 3, then the return string would be: "sup erc ali fra gil ist ice xpi ali doc iou s" The assumptions we are making about our input are the following: - The input string's length is always greater than 0. - The string has no spaces. - The specified size is always a positive integer. """ def split_in_parts(s, part_length): # we need to split the input string into smaller chucks of whatever # the specified size is # initialize an output array to hold the split letters # initialize a an empty substring to hold counted letters output = [] s_substring = "" # iterate over characters in the input string for letter in s: # add letter to the substring until it's equal to the part_length if len(s_substring) < part_length: s_substring += letter # when substring is equal to part_length, append to output and reset # substring to empty string to start over if len(s_substring) == part_length: output.append(s_substring) s_substring = "" # if any letters are left over, add them at the end. if s_substring != "": output.append(s_substring) # make the array into a string result = " ".join(output) # return output array return result print(split_in_parts("supercalifragilisticexpialidocious", 3)) print(split_in_parts("supercalifragilisticexpialidocious", 5)) print(split_in_parts("oscargribble", 5))
true
fd2958044308c991ea843b73987860bb7fc75a3b
Anushree-J-S/Launchpad-Assignments
/problem1.py
412
4.15625
4
#Create a program that asks the user to enter their name and age. #Print out a message addressed to them that tells them the year that they will turn 100 years old print("Code for problem 1") from datetime import datetime name=input("Enter your name:") age=int(input("Enter your age:")) year=int((100-age) +datetime.now().year) print("Hey! ",name) print("You will turn 100 in the year " ,year)
true
3941b7f787b9a23e4f64732bfa8215baa7abd7ff
klkael/Ujian_Bank
/PYTHON/0.py
1,416
4.28125
4
print(1+1) nama = "asd" umur = 12 print(nama) print("halo, aku " + nama) print("umurku" + str(umur)) print("umurku", umur) print('saya ' + nama + 'usia ' + str(umur)) print('saya', nama, 'usia', umur) print('saya %s umur %d' %(nama, umur)) print('saya {} usia {}'.format(nama, umur)) print(f'saya {nama} usia {umur}') print('-\n-') print("jum'at") print('jum\'at') print('purwadhika\tSchool') print('purwadhika\nSchool') print('-\n-') nama = 'andi raharja' print(nama.lower()) print(nama.upper()) print('-\n-') print(nama.islower()) print(nama.isupper()) print(nama.lower().isupper()) print(nama.upper().islower()) print('-\n-') namaa = 'python oke sekali' print(len(namaa)) print(namaa[0]) print(namaa[0:len(namaa)]) print(namaa[0:5]) # [start : stop : step] print(namaa[0:len(namaa):2]) # huruf paling belakang ke berapa print(namaa[len(namaa)-2]) print(namaa.index('a')) print(namaa.replace('oke', 'keren')) nama = 'Purwadhika Startup & Coding school' # mencari jumlah huruf print(len(nama.replace(' ', ''))) print(len(nama)) print(nama.lower().count('c')) nama = 'Hari ini Hari tidak masuk sekolah' # jumlah huruf h cari = 'h' x = nama.upper().replace(cari.upper(), '') print(x) h = len(nama) - len(x) print(f'Jumlah huruf \'{cari}\' ada = {h}') cari = 'hari' x = nama.upper().replace(cari.upper(), '') print(x) jumlahcari = int((len(nama) - len(x)) / len(cari)) print(f'jumlah kata \'{cari}\' ada = {jumlahcari}')
false
5eeb25bf53ae5078589644cf03a7830a03803979
EduardoPNK/Atividades_funcoes
/3.py
419
4.1875
4
#Faça um programa, com uma função que necessite de três argumentos, e que forneça a soma desses três argumentos. def soma(n1, n2, n3): resultado = n1 + n2 + n3 return resultado numero1 = int(input('Informe um numero para soma: ')) numero2 = int(input('Informe um numero para soma: ')) numero3 = int(input('Informe um numero para soma: ')) print(f'a soma é {soma(numero1, numero2, numero3)}')
false
2c07ea5764d7173d72c7b85a1d0622a6a7c8e145
vinodh1988/python-code-essentials
/conditional.py
436
4.15625
4
name=input('enter you name >> ') print(len(name)) if(len(name)>=5): print('Valid name it has more than 4 characters') print('We shall store it in the database') elif(len(name)==3 or len(name)==4): print('type confirm to store it into the database >>') if 'confirm'==input(): print('stored in the database') else: print('wrong input') else: print('name should have atleast three characters')
true
9fbbc0f624b4d73e88b72a51ed23d50c52d8331d
jaekeon02/Studying-Progress
/python/gui/Calculatortest.py
1,986
4.1875
4
# 계산기를 만들어 보겠습니다. # Entry 2개 -> 숫자 2개를 각각 입력받습니다. # 버튼 5개 #| +, -, *, /, %| # Entry 두개에 값을 채워 넣고 #| +, -, *, /, %|버튼을 누르면 두 엔트리에 들어있던 값을 토대로 # 결과값을 출력해줍니다 # Label 1개 => 결과값을 콘솔창이 아닌 Label에 출력해보세요 from tkinter import * calculator = Tk() calculator.configure(width="75m",height="100m") ##########함수배치부분########### def ADD(): data1=0 data1=int(E1.get())+int(E2.get()) Lb2=Label(calculator, text=str(data1)) Lb2.place(x=110,y=40,width=100,height=30) def MINUS(): data1=0 data1=int(E1.get())-int(E2.get()) Lb2=Label(calculator, text=str(data1)) Lb2.place(x=110,y=40,width=100,height=30) def MULTI(): data1=0 data1=int(E1.get())*int(E2.get()) Lb2=Label(calculator, text=str(data1)) Lb2.place(x=110,y=40,width=100,height=30) def DIVIDE(): data1=0 data1=int(E1.get())/int(E2.get()) Lb2=Label(calculator, text=str(data1)) Lb2.place(x=110,y=40,width=100,height=30) def REMAIN(): data1=0 data1=int(E1.get())%int(E2.get()) Lb2=Label(calculator, text=str(data1)) Lb2.place(x=110,y=40,width=100,height=30) ##########창배치부분############ # 엔트리 창 설정 E1=Entry(calculator) E1.place(x=10,y=10, width=100,height=30) E2=Entry(calculator) E2.place(x=10,y=80, width=100,height=30) # 버튼설정 Button(calculator, text="+", command=ADD).place(x=10,y=120,width=30,height=30) Button(calculator, text="-", command=MINUS).place(x=50,y=120,width=30,height=30) Button(calculator, text="*", command=MULTI).place(x=10,y=160,width=30,height=30) Button(calculator, text="/", command=DIVIDE).place(x=50,y=160,width=30,height=30) Button(calculator, text="%", command=REMAIN).place(x=90,y=120,width=30,height=70) # 레이블설정 Lb1=Label(calculator, text="결과판") Lb1.place(x=120,y=10,width=100,height=30) calculator.mainloop()
false
0b1ba18925bc89c7564a8cfb61c18749eeb5f168
sh-am-si/numerical_python
/asteriks.py
499
4.125
4
''' :author: Volodya :created: 16/12/2019 Introduction to Python Lecture 3, Functions and comprehensions Asteriks ''' lst = [1, 2, 3] print('calling without asteriks', lst) print('calling with asteriks', *lst) def my_sum(a, b, c): return a + b + c lst = [1, 2, 3] print(my_sum(*lst)) dic = {'a': 1, 'b': 2, 'c': 3} print(my_sum(**dic)) lst = [1, 2, 3, 4] print(my_sum(*lst)) # error dic = {'a': 10, 'b': 20, 'c': 30, 'd': 4} print(my_sum(**dic)) # error
false
e3c217f79478ea89de35f9f7b761d19fbfdde837
x223/cs11-student-work-Karen-Gil
/Countdown2.py
438
4.28125
4
countdown = input('pick a number') number= countdown while number>0: #number has to be grater than zero in order for it to countdown duh!!! print number number= number-1 #In order for there to be a countdown it has to be number-1 print('BOOM!!!') # I origanaly wrote print boom as showen below but it printed boom after every number it counted down so I didnt put any white #space that fixed my code #print ('boom')
true
d50968987468a7fd1ac886ace6ca45dd8cb0a167
sanket-khandare/Python-for-DS
/Stage 1.py
710
4.25
4
# Task 1 - Hello World print('Hello World!') # Task 2 - basic operations name = 'sanket' print('Hello '+ name) # Task 3 - using lists name_list = ['Sanket','Abhay','Pravin',['Friends', 3]] print(name_list[3][1]) # Task 4 - copy & update list new_name_list = name_list[:] new_name_list[3][0] = 'Total Friends' print(new_name_list) # Task 5 - check help doc #help(round) # Task 6 - use len and type of print(len(new_name_list)) print(type(new_name_list[3])) print(len(new_name_list[3])) # Task 7 - sort list print(sorted(new_name_list)) # Task 8 - use index print(name_list.index('Pravin')) # Task 9 - append list & reverse name_list.append("Sagar") print(name_list) name_list.reverse() print(name_list)
false
0da6b491db0b5599895b81f1fd57a72df49b1393
Farheen2302/ds_algo
/algorithms/sorting/quicksort.py
1,223
4.25
4
def quicksort(arr, start, end): if start < end: pivot = _quicksort(arr, start, end) left = quicksort(arr, 0, pivot - 1) right = quicksort(arr, pivot + 1, end) return arr def _quicksort(arr, start, end): pivot = start left = start + 1 right = end done = False while not done: while left <= right and arr[left] < arr[pivot]: left += 1 while right >= left and arr[right] > arr[pivot]: right -= 1 if left >= right: done = True else: """ Making use of python's swapping technique http://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python """ arr[left], arr[right] = arr[right], arr[left] #swap(arr, left, right) arr[pivot], arr[right] = arr[right], arr[pivot] #swap(arr, pivot, right) return right def swap(arr, left, right): temp = arr[left] arr[left] = arr[right] arr[right] = temp # Test Cases arr = [8, 7, 6, 5, 4, 3, 2, 1] arr1 = [54, 26, 93, 17, 77, 31, 44, 55, 20] assert sorted(arr1) == quicksort(arr1, 0, len(arr1) - 1) assert sorted(arr) == quicksort(arr, 0, len(arr)-1)
true
26ba767c26370a46d7c5998cd0bff03a9e4ea7af
soli1101/python_workspace
/d20200720/test7.py
685
4.1875
4
print('------- 문제3 -------') # 태어난 년도를 입력하면 띠 출력 # 년도를 12로 나눈 나머지를 구한다 # 자축인묘진사오미신유술해 # 4,5,6,7,8,9,10,0,1,2,3 year = input("출생년도는?") year = int(year) mod = year%12 if mod == 4: print('쥐띠') if mod == 5: print('소띠') if mod == 6: print('호랑이띠') if mod == 7: print('토끼띠') if mod == 8: print('용띠') if mod == 9: print('뱀띠') if mod == 10: print('말띠') if mod == 11: print('양띠') if mod == 0: print('원숭이띠') if mod == 1: print('닭띠') if mod == 2: print('개띠') if mod == 3: print('돼지띠')
false
e749028dba668306be4afba488e05fae22ef49e3
Tania-Aranega/Python
/Módulo 8/Ejercicio2_Generadores&Potencias.py
431
4.1875
4
# def potencia(base): # """Documentación""" # exponente=1 # while True: # yield base**exponente # exponente+=1 # i = 0 # it = potencia(2) # while i < 100: # print(it.__next__()) # i += 1 def potencia(base, exponente): i = 0 result = 1 while i < exponente: result = base*result i += 1 yield result return for i in potencia(2, 3): print(i)
false
0bb37602e0531c8d9340ce0f9335d817c0730b97
donato/notes
/interviews/2017/practice/linked-list-palindrome.py
1,265
4.15625
4
def find_middle(head): """FInd meddle of linked list using 2 runner strategy and return if it's an odd length list return middle_node, is_odd(Bool) """ r1 = head r2 = head while r2.next: if not r2.next.next: return r1, False r1 = r1.next r2 = r2.next.next return r1, True def reverse_list(head, end): prev = head head = head.next while head != end: next = head.next head.next = prev prev = next head.next = prev def compare_lists(head1, head2): while head1 and head2: if head1.data != head2.data: return False head1 = head1.next head2 = head2.next return True def palindrome(head): middle, is_odd = find_middle(head) list_2 = middle.next reverse_list(head, middle) if is_odd: list_1 = middle.next else: list_1 = middle result = compare_lists(list_1, list_2) reverse_list(middle, head) return result class LinkedListNode: data = None next = None def __init__(self, d): self.data = d l1 = LinkedListNode('p') l2 = LinkedListNode('o') l2 = LinkedListNode('o') l3 = LinkedListNode('p') l1.next = l2 l2.next = l3 print(palindrome(l1))
true
8c0cf4f81e474e9ddbc409bcd235e6013dde6cf0
SadeghShabestani/8_time
/8_time.py
301
4.21875
4
hour = float(input("Enter Hour: ")) minute = float(input("Enter Minute: ")) second = float(input("Enter Second: ")) print(f"{hour} : {minute} : {second}") result_hour = hour * 3600 result_minute = minute * 60 result = result_hour + result_minute + second print(f"Seconds: {result}")
false
6df318d7ca006994d1cd820a2188de161880468d
valentynbez/practicepython-solutions
/06_string_lists.py
369
4.125
4
# https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html def pal_check(): pal = input('Please add sentence: ') new_pal = [n.lower() for n in pal if n.isalpha()] rev_pal = ''.join(new_pal[::-1]) new_pal = ''.join(new_pal) if new_pal == rev_pal: print("It's palindrome!") else: print('No, it is not a palindrome')
false
72d4699df84a1d7776185f448f3d6aa2f8d05107
Sitarko/learn-homework-2
/1_date_and_time.py
900
4.28125
4
""" Домашнее задание №2 Дата и время 1. Напечатайте в консоль даты: вчера, сегодня, 30 дней назад 2. Превратите строку "01/01/20 12:10:03.234567" в объект datetime """ from datetime import datetime, timedelta def print_days(date_now): try: dt1 = timedelta(days = 1) yesterday = date_now - dt1 dt2 = timedelta(days = 30) month = date_now - dt2 print (f'Вчера: {yesterday},\nСегодня: {date_now},\n30 дней назад: {month}') except TypeError: print('Введите корректную дату') def str_2_datetime(date_string): date = datetime.strptime(date_string, '%d/%m/%y %H:%M:%S.%f') return date if __name__ == "__main__": print_days(datetime.now()) print(str_2_datetime("01/01/20 12:10:03.234567"))
false
4701dc2609fcbc88935c0a52dca736fd40fa5099
Ricardo-Sillas/Project-1
/Main.py
964
4.21875
4
import hashlib def hash_with_sha256(str): hash_object = hashlib.sha256(str.encode('utf-8')) hex_dig = hash_object.hexdigest() return hex_dig # starts numbers off with length 3, increments the number by one, then increments length by one at the end of that length def getNum(s, n): if len(s) == n: check(s) return for i in range(10): getNum(s + str(i), n) # Gets number from getNum, adds the salt value to the end, hashes it, and then checks if the two hashed passwords are the same def check(s): text = open("password_file.txt", "r") read = text.readlines() for line in read: parts = line.split(",") user = parts[0] salt = parts[1] old = parts[2].replace('\n','') new = hash_with_sha256(s + salt) if(old == new): print("The password for", user, "is", s) return text.close() def main(): hex_dig = hash_with_sha256('This is how you hash a string with sha256') print(hex_dig) for n in range(3,8): getNum("",n) main()
true
795979147914ef731e1a331174035def44ec225b
simple2source/macugEx
/macugEx/datastruct/Link_list.py
1,677
4.15625
4
# -*- coding:utf-8 -*- """ python 实现数据结构-链表 """ class Node(object): """定义节点和指针,指针指向下一个节点的值 """ def __init__(self, data): self.data = data self.next = None class LinkList(object): def __init__(self): self.head = None self.tail = None def append(self, data): node = Node(data) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node def iter(self): if not self.head: return cur = self.head yield cur.data while cur.next: cur = cur.next yield cur.data def insert(self, idx, data): if self.head is None: if idx == 0: node = Node(data) self.head = node self.tail = node else: raise IndexError('index error') cur = self.head cur_idx = 0 while cur_idx < idx-1: cur = cur.next if cur is None: raise IndexError('length is short than index') cur_idx += 1 node = Node(data) node.next = cur.next cur.next = node if node.next is None: self.tail = node def remove(self, idx): if self.head is None: raise IndexError('empty list') cur = self.head cur_idx = 0 while cur_idx < idx-1: cur = cur.next cur_idx += 1 cur.next = cur.next.next if cur.next is None: self.tail = cur def __len__(self): cur = self.head if cur is None: return 0 cur_idx = 1 while True: cur = cur.next cur_idx += 1 if cur.next is None: break return cur_idx if __name__ == '__main__': L1 = LinkList() for i in range(10): L1.append(i) L1.insert(3, 'www') L1.remove(7) for x in L1.iter(): print x print len(L1) a = [] print len(a) print L1.tail.data
false
c12295ae7f494a67fa97ae8e15a1a8629df2caaa
khushalk77/khushal-kumar
/khushal 2k18csun01066 PT3 .py
1,290
4.4375
4
#!/usr/bin/env python # coding: utf-8 # # 1. What is the syntax to call a constructor of a base class from child class # # ans: class parentclassname: # def _init_(self,var): # self.var=var # print(self.var) # class childclassname(parentclassname): # pass # x=10 # obj = childclassname(x) # # class A: # def _init_(self,x): # self.x=x # print(self.x) # class B(A): # pass # x=10 # d1 = B(x) # # # # 2. How is a class made as inherited class (syntax of child class) # class childclassname(parentclassname): # pass # obj = childclassname() # obj.methodofparentclass() # # # # class A: # def find(self): # print('good morning') # class B(A): # pass # d1 = B() # d1.find() # # # 3. Print an element of a nested dictionary # # # d1={1:'A',2:'B',3:('C','D'),4:['E','F','G','H'],5:{'A':1,'B':2,'C':3}} # d1 # d1[4][0] # # set c # # ques 1 # In[2]: import math value1=int(input("enter any number : ")) value2=int(input("enter any number : ")) value3=int(input ("enter any number: ")) m=((2*value1*value2)/(value3)) print(math.sqrt(m)) # # ques 2 # In[7]: x= input('enter the string: ') y=x[::2] print(y) # In[ ]:
false
09f75de95ac1f64a6ffd3b73e803b32ed8a209a8
rakeshsukla53/interview-preparation
/Rakesh/python-basics/call_by_reference_in_python.py
1,081
4.28125
4
def foo(x): x = 'another value' # here x is another name bind which points to string variable 'another value' print x bar = 'some value' foo(bar) print bar # bar is named variable and is pointing to a string object # string objects are immutable, the value cannot be modified # you can not pass a simple primitive by reference in Python bar += 'rakesh' # here you are creating another object of string type print bar # you can pass reference only in immutable types in Python like list, dictionary # call by value and call by reference are definitely a thing but we need to take care of which type of object are we talking about here # we can pass by reference the following objects # Mutable: everything else, # # mutable sequences: list, byte array # set type: sets # mapping type: dict # classes, class instances # etc. # we cannot pass by reference the following objects, because here a complete new object will be created # Immutable: # # numbers: int, float, complex # immutable sequences: str, tuples, bytes, frozensets
true
de4fc062a33d209172ed71d02074dda15ebbe5d4
rakeshsukla53/interview-preparation
/Rakesh/trees/Symmetric_Tree_optimized.py
888
4.28125
4
# for this method I am going to use the reverse binary tree method to check for symmetric tree # 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 __init__(self): self.count = True def sym(self, L, R): if L is None and R is None: return True if L and R and L.val == R.val: self.sym(L.left, R.right) self.sym(L.right, R.left) else: self.count = False def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root or (root.left is None and root.right is None): return True self.sym(root.left, root.right) return self.count # optimized solution of symmetric tree
true
dc53ce7c76f9b149441aeda751214149d8933c17
rakeshsukla53/interview-preparation
/Rakesh/python-iterators/remove_while_iteration.py
636
4.125
4
__author__ = 'rakesh' somelist = range(10) for x in somelist: somelist.remove(x) #so here you are modifying the main list which you should not be doing print somelist somelist = range(10) for x in somelist[:]: #Because the second one iterates over a copy of the list. So when you modify the original list, you do not modify the copy that you iterate over somelist.remove(x) print somelist #list(somelist) will convert an iterable into a list. somelist[:] makes a copy of an object that supports slicing. So they don't necessarily do the same thing. In this case I want to make a copy of the somelistobject, so I use [:]
true
d9d3972659395307fb5353071b3615a0ad82c1bc
rakeshsukla53/interview-preparation
/Rakesh/Google-interview/breeding_like_rabbits_optimized_method.py
2,970
4.5
4
__author__ = 'rakesh' #here we have to know about memoization #Idea 1 - To sabe the result in some variables ---but it is not feasible. Fibonacci can be done since only two variables #are required. Also in the memoization part there is only recursion process not all. #Idea 2 - Use some kind of hash table here, but it will occupy lots of memory. Chances of memory error #Idea 3 - For this type of problem if you have do memoization through recursion #Idea 4 - if there is no base condition then there is no way a recursion can happen and the base condition should keep on decreasing #Idea 5 - ''' Yes. The primitive recursive solution takes a lot of time. The reason for this is that for each number calculated, it needs to calculate all the previous numbers more than once. Take a look at the following image. Tree representing fibonacci calculation It represents calculating Fibonacci(5) with your function. As you can see, it computes the value of Fibonacci(2) three times, and the value of Fibonacci(1) five times. That just gets worse and worse the higher the number you want to compute. What makes it even worse is that with each fibonacci number you calculate in your list, you don't use the previous numbers you have knowledge of to speed up the computation – you compute each number "from scratch." There are a few options to make this faster: 1. Create a list "from the bottom up" The easiest way is to just create a list of fibonacci numbers up to the number you want. If you do that, you build "from the bottom up" or so to speak, and you can reuse previous numbers to create the next one. If you have a list of the fibonacci numbers [0, 1, 1, 2, 3], you can use the last two numbers in that list to create the next number. This approach would look something like this: >>> def fib_to(n): ... fibs = [0, 1] ... for i in range(2, n+1): ... fibs.append(fibs[-1] + fibs[-2]) ... return fibs ... Then you can get the first 20 fibonacci numbers by doing >>> fib_to(20) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765] Or you can get the 17th fibonacci number from a list of the first 40 by doing >>> fib_to(40)[17] 1597 2. Memoization (relatively advanced technique) Another alternative to make it faster exists, but it is a little more complicated as well. Since your problem is that you re-compute values you have already computed, you can instead choose to save the values you have already computed in a dict, and try to get them from that before you recompute them. This is called memoization. It may look something like this: >>> def fib(n, computed = {0: 0, 1: 1}): ... if n not in computed: ... computed[n] = fib(n-1, computed) + fib(n-2, computed) ... return computed[n] This allows you to compute big fibonacci numbers in a breeze: >>> fib(400) 176023680645013966468226945392411250770384383304492191886725992896575345044216019675 '''
true
1b1e945ef82db250c50dd635c5da0a86a8ec32fc
rakeshsukla53/interview-preparation
/Rakesh/Common-interview-problems/product of array except self.py
912
4.15625
4
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] Logic : You will use two loops one going from left to right, and other from right to left for example if a = [1, 2, 3, 4] Going from left -> a = [1, 1, 2, 6] Going from right -> a = [24,12,8,6] here you will refer back to [1,2,3,4] The problem is the list will grow with the input array """ size, temp = len(nums), 1 output = [1] * size # left loop array for i in range(1, size): temp *= nums[i - 1] output[i] = temp temp = 1 for j in range(size - 2, -1, -1): temp *= nums[j + 1] output[j] *= temp return output # this slicing and merging of the arrays are O(n) operation Solution().productExceptSelf([1, 2, 3, 4])
true
23ca1215a474d6a40ac0c93df2446b5475adce9a
rakeshsukla53/interview-preparation
/Rakesh/Common-interview-problems/Ordered_Dict.py
1,795
4.21875
4
__author__ = 'rakesh' #What is orderedDict #An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. from collections import OrderedDict LRUCache = OrderedDict() count = 1 for i in [2, 4, 5, 6, 7, 9, 10]: LRUCache[i] = count count += 1 print LRUCache LRUCache.popitem(last=False) print LRUCache # print LRUCache # # # del LRUCache[2] #if you delete the old entry then you ened # # LRUCache[2] = "" # # print LRUCache # # #The best thing about orderedDict is that it remembers the order in which the keys are inserted. If the new entry overwrites and existing entry, the original insertion position will remain unchanged. Deleting an entry and reinseeting it will move to the end. This is really good for LRU Cache will deletes the entry # # #dictionary sorted by key # # LRUCache = sorted(LRUCache.items(), key= lambda t: t[1]) # print LRUCache #It is really amazing that you can sort your LRUCache # # #there are lots of operation that you can perform # # >>> # regular unsorted dictionary # # >>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2} # # # # >>> # dictionary sorted by key # # >>> OrderedDict(sorted(d.items(), key=lambda t: t[0])) # # OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) # # # # >>> # dictionary sorted by value # # >>> OrderedDict(sorted(d.items(), key=lambda t: t[1])) # # OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) # # # # >>> # dictionary sorted by length of the key string # # >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0]))) # # OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
true
dcb5dc0d8b77109893f6c8f0446daf75e4cf57f8
rakeshsukla53/interview-preparation
/Rakesh/Natural Language Processing/word_tokenize.py
750
4.1875
4
__author__ = 'rakesh' #http://pythonprogramming.net/tokenizing-words-sentences-nltk-tutorial/ from nltk.tokenize import sent_tokenize, word_tokenize EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard." print(sent_tokenize(EXAMPLE_TEXT)) print(word_tokenize(EXAMPLE_TEXT)) ''' Now, looking at these tokenized words, we have to begin thinking about what our next step might be. We start to ponder about how might we derive meaning by looking at these words. We can clearly think of ways to put value to many words, but we also see a few words that are basically worthless. These are a form of "stop words," which we can also handle for. '''
true
dfdc48c3cc68c316dd4f21725016f669f365d0b2
WillDavid/Python-Exercises
/BuscaPython/algoritmoBusca02.py
267
4.1875
4
numeros = [] x = int(input("Informe a quantidade de numeros: ")) for i in range(x): numero = float(input("Informe um número real: ")) numeros.append(numero) lista = [] for i in numeros: if i not in lista: lista.append(i) print("Lista Ordenada: ", lista)
false
6d3aba17b75e3eff3b706bc6ec4bdf1b583dc0a8
katiemharding/ProgrammingForBiologyCourse2019
/problemsets/PythonProblemSets/positiveOrNegative.py
996
4.59375
5
#!/usr/bin/env python3 import sys # for testing assign a number to a value unknown_number = int(sys.argv[1]) # first test if it is positive if unknown_number>0: print(unknown_number, "is positive") if unknown_number > 50: # modulo (%) returns the remainder. allows testing if divisible by if unknown_number%3 == 0: print(unknown_number, "is larger than 50 and divisible by 3") else: print(unknown_number, "is bigger than 50") elif unknown_number == 50: print(unknown_number, "is even and equal to 50") else: print(unknown_number, "is less than 50") # modulo tests if a number is even. # it returns the remainder (the numbers remaining after division) # if it is zero then there is no remainder if unknown_number%2 == 0: print(unknown_number, "is even") else: print(unknown_number, "is odd") # What to do if not positive: # test if equals 0 elif unknown_number == 0: print("equals 0") # if not positive test if negative? else: print(unknown_number, "is negative")
true
c97df9692c0d772e8cef6a60bdb23a59ba803ccd
sxd7/p_ython
/python.py
413
4.21875
4
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> import math >>> radius=float(input("enter the radius of the circle:")) enter the radius of the circle:5 >>> area=math.pi*radius*radius; >>> print("area of the circle is:{0}".format(area)); area of the circle is:78.53981633974483 >>>
true
222f287965120511ecb52663994e286d2752d363
PradeepNingaiah/python-assginments
/hemanth kumar python assginment/14.exception.py
1,734
4.5625
5
#1. Write a program to generate Arithmetic Exception without exception handling try: a = 10/0 print (a) except ArithmeticError: print ("This statement is raising an arithmetic exception.") else: print ("Success.") #----------------------------------------------------------------------------- #6.Write a program to create your own exception class notaccepted(Exception): def __init__(self, hai): self.hai=hai try: raise notaccepted("i'm busy right now") except notaccepted as err: # perform any action on YourException instance print("Message:", err.hai) #----------------------------------------------------------------------------- #7. Write a program with finally block #Implementing try,except and finally try: x=int(input("Enter First No:")) y=int(input("Enter Second No:")) z=x/y print(z) except(ZeroDivisionError): print("2nd No cannot be zero") finally: # here prints msg of finally block before terminating abnormally print("welcome to hyd...........") print("end") #Try the execution for all the 3 cases ,in all 3 cases finally will be executed #----------------------------------------------------------------------------- #9. Write a program to generate FileNotFoundException #FileNotFoundError: try: f=open("C:/data/demo5.txt","r") #r--->read mode print(f.read()) f.close() except(FileNotFoundError): print("File doesnt exist") except: print("Error") else: print("File opened Successully") print("end") #------------------------------------------------------------------------------
true
5c805c9c2964f9a1ee57fc8549e2dae20c2aa693
christianns/Curso-Python
/05_Entradas_y_salidas/06_Ejercicio_3.py
909
4.3125
4
''' Ejercicio 3 Crea un script llamado descomposicion.py que realice las siguientes tareas: Debe tomar 1 argumento que será un número entero positivo. En caso de no recibir un argumento, debe mostrar información acerca de cómo utilizar el script. El objetivo del script es descomponer el número en unidades, decenas, centenas, miles... tal que por ejemplo si se introduce el número 3647: ''' import sys if len(sys.argv) == 2: numero = int(sys.argv[1]) if numero < 0 or numero > 9999: print("Error - Número es incorrecto") print("Ejemplo: descomposicion.py [0-9999]") else: # Aqui va la lógica cadena = str(numero) longitud = len(cadena) for i in range(longitud): print( "{:04d}".format( int(cadena[longitud-1-i]) * 10 ** i )) else: print("Error - Argumentos incorrectos") print("Ejemplo: descomposicion.py [0-9999]")
false
1a544cb42c9ad4753c9759abcf5df19547c09897
christianns/Curso-Python
/03_Control_de_flujo/20_Ejercicio_15.py
2,301
4.28125
4
# Problema 15: Realiza un sistema para controlar el ingreso a un cine, donde ofrezca # películas de terror, acción y aventuras. En cada opción tenga restricción por edad. # Categorías $ Edad (%) # Terror 18 - 55 # Acción 10 a mas # Aventura 4 a mas # Análisis: Para la solución de este problema, se requiere que tenga un menú de opciones para # elegir si desea terror, acción o aventura y se permita el ingreso de acuerdo a la edad. while True: print ("=========================") print ("Bienvenido a Nuestro Cine") print ("=========================") print ("Elija la categoria: ") print ("1 - Terror") print ("2 - Acción") print ("3 - Infantil") print ("4 - Salir") opcion = int(input("Ingrese la opcion:")) if opcion == 1: edad = int(input("Ingrese su edad:")) if edad >= 18 and edad <= 55: print ("====================") print ("Disfrute su pelicula") print ("====================\n\n") else: print ("============================================") print ("No tiene permitido acceder a ver la pelicula") print ("============================================\n\n") elif opcion == 2: edad = int(input("Ingrese su edad:")) if edad >= 10: print ("====================") print ("Disfrute su pelicula") print ("====================\n\n") else: print ("============================================") print ("No tiene permitido acceder a ver la pelicula") print ("============================================\n\n") elif opcion == 3: edad = int(input("Ingrese su edad:")) if edad >= 4: print ("====================") print ("Disfrute su pelicula") print ("====================\n\n") else: print ("============================================") print ("No tiene permitido acceder a ver la pelicula") print ("============================================\n\n") elif opcion == 4: print ("Grcias por visitarnos\n") break else: print ("Opcion no valida") print ("Intentelo nuevamente")
false
d114c4ca0205f54dd4f3c90e48cd1d7440fb1184
christianns/Curso-Python
/07_Errores_y_excepciones/08_Ejercicio_4.py
958
4.25
4
''' Ejercicio 4 Realiza una función llamada agregar_una_vez(lista, el) que reciba una lista y un elemento. La función debe añadir el elemento al final de la lista con la condición de no repetir ningún elemento. Además si este elemento ya se encuentra en la lista se debe invocar un error de tipo ValueError que debes capturar y mostrar este mensaje en su lugar: # Error: Imposible añadir elementos duplicados => [elemento]. Cuando tengas la función intenta añadir los siguiente valores a la lista 10, -2, "Hola" y luego muestra su contenido. ''' elementos = [1, 5, -2] # Completa el ejercicio aquí def agregar_una_vez(lista, el): try: if el in lista: raise ValueError else: lista.append(el) except ValueError: print("Error: Imposible añadir elementos duplicados =>", el) agregar_una_vez(elementos, 10) agregar_una_vez(elementos, -2) agregar_una_vez(elementos, "Hola") print(elementos)
false
dd44d58ab9c771cfbeb0a0c0099d12170ab62839
christianns/Curso-Python
/04_Coleccion_de_datos/05_Diccionarios.py
2,425
4.375
4
# Diccionarios. # Son junto a las listas las colecciones más utilizadas y se basan en una # estructura mapeada donde cada elemento de la colección se encuentra # identificado con una clave única, por lo que no puede haber dos claves iguales. # En otros lenguajes se conocen como arreglos asociativos. # Los diccionarios se definen igual que los conjuntos, utilizando llaves, # pero también se pueden crear vacíos con ellas: datos = {} # Diccionario vacio. # Para cada elemento se define la estructura clave:valor datos ={'blue': 'azul', 1: 'Uno', 2:'Dos'} print (datos) print (datos[1]) # Muestra la clave de la posición 1. print (type(datos)) # Mutabilidad # Los diccionarios son mutables, por lo que se les puede añadir # elementos sobre la marcha a través de las claves: datos ['Verde'] = "Green" # Agrega una clave y un valor print (datos) datos [1] = "UNO" # Reemplaza en valor. print (datos) del(datos['blue']) # Sirve para borrar un elemento del diccionario print (datos) # Una utilidad de los diccionarios es que podemos trabajar directamente # con sus registros como si fueran variables: edades = {'Hector':27,'Juan':45,'Maria':34} edades['Hector']+=1 print (edades) # Lectura secuencial # Es posible utilizar iteraciones for para recorrer los elementos del diccionario: # Muesta las claves del diccionario secuencialmente for d in datos: print (d) # Muesta las valores del diccionario secuencialmente for clave in datos: print (datos[clave]) # El método .items() nos facilita la lectura en clave y valor de los elementos. # Devuelve ambos valores en cada iteración automáticamente y nos permite almacenarlos: for clave, valor in datos.items(): # Metodo .items permite leer print (clave,'-', valor) # Lista de Diccionarios # El método .items() nos facilita la lectura en clave y valor de los elementos. # Devuelve ambos valores en cada iteración automáticamente y nos permite almacenarlos: personajes = [] # Lista vacia Gandalf = {'Nombre':'Gandalf','Clase':'Mago','Raza':'Humano'} Legolas = {'Nombre':'Legolas','Clase':'Arquero','Raza':'Elfo'} Gimli = {'Nombre':'Gilmi','Clase':'Guerrero','Raza':'Enano'} personajes.append(Gandalf) personajes.append(Legolas) personajes.append(Gimli) # Muestra la lista de diccionarios print (personajes) # Mostras por partes for personaje in personajes: print (personaje['Nombre'], '-', personaje['Clase'], '-', personaje['Raza'])
false
c9a753fc4a85c8874a49112449b6c924397339ab
christianns/Curso-Python
/06_Programacion_de_funciones/09_Ejercicio_1.py
541
4.21875
4
''' Ejercicio 1 Realiza una función llamada area_rectangulo(base, altura) que devuelva el área del rectangulo a partir de una base y una altura. Calcula el área de un rectángulo: su base y altura ingrese por teclado. Nota: El área de un rectángulo se obtiene al multiplicar la base por la altura. ''' base = int(input('Ingrese base:\n')) altura = int(input('Ingrese altura:\n')) def area_rectangulo (base, altura): area = base * altura return area print ('El area del rectangulo es: ' + str(area_rectangulo(base, altura)))
false
5c8ce54a695bc87fa2e214eed81bea061134739e
christianns/Curso-Python
/04_Coleccion_de_datos/06_Pilas.py
1,090
4.53125
5
''' Pilas Son colecciones de elementos ordenados que únicamente permiten dos acciones: - Añadir un elemento a la pila. - Sacar un elemento de la pila. La peculiaridad es que el último elemento en entrar es el primero en salir. En inglés se conocen como estructuras LIFO (Last In First Out). Las podemos crear como listas normales y añadir elementos al final con el append(): # En python no existen las pilas pero se pueden simular con listas ''' # Las podemos crear como listas normales y añadir elementos al final con el append(): pila = ['auto', 3, 4, 5] pila.append(6) # Agrega al final de la lista el 6 pila.append(7) # Agrega después del 6 el 7 print (pila) # Para sacar los elementos utilizaremos el método pop(). print(pila.pop()) # Quita el ultimo datos print (pila) # ya no existe en la lista # Si queremos trabajar con él deberíamos asignarlo a una variable numero = pila.pop() # Guarda el ultimo dato en una variable print (numero) # Quita todos los datos y finalmente que una lista vacia []. pila.pop() pila.pop() pila.pop() pila.pop() print (pila)
false
dac0c4fbd04f7c8d193cc2dd8bb3a0cb42948202
christianns/Curso-Python
/06_Programacion_de_funciones/07_Funciones_recurcivas.py
1,154
4.65625
5
''' Funciones recursivas Se trata de funciones que se llaman a sí mismas durante su propia ejecución. Funcionan de forma similar a las iteraciones, pero debemos encargarnos de planificar el momento en que dejan de llamarse a sí mismas o tendremos una función rescursiva infinita. Suele utilizarse para dividir una tarea en subtareas más simples de forma que sea más fácil abordar el problema y solucionarlo. ''' # Ejemplo sin retorno - Cuenta regresiva hasta cero a partir de un número: # Ejemplo 1 de una funcion recursiva. def cuenta_regresiva (n): n -= 1 if n > 0: print (n) cuenta_regresiva(n) else: print ('Booom ¡¡¡¡¡¡¡¡¡¡') cuenta_regresiva(3) # Ejemplo con retorno # El factorial de un número corresponde al producto de todos los números desde # 1 hasta el propio número. Es el ejemplo con retorno más utilizado para # mostrar la utilidad de este tipo de funciones: # Ejemplo 2 de una funcion recursiva def factorial(num): print ('Valor inicial -->', num) if num > 1: num = num * factorial(num - 1) print ('valor final -->', num) return num print(factorial(5))
false
9bcaa72b193d3b5ce12db67faffd751c3f1cc7c5
girisagar46/KodoMathOps
/kodomath/mathops/quiz_service.py
1,377
4.15625
4
from decimal import Decimal from asteval import Interpreter class SubmissionEvaluator: """A helper class to evaluate if submission if correct or not. """ def __init__(self, expression, submitted_result): self.expression = expression self.submitted_result = submitted_result # https://stackoverflow.com/a/18769210/4494547 @staticmethod def remove_exponent(num): """To remove trailing zeros form a floating point number Args: num: Decimal object Returns: Decimal object with 2 decimal places if there is no trailing zero Example: >>> SubmissionEvaluator.remove_exponent(Decimal(1.01)) 1.010000000000000008881784197 >>> SubmissionEvaluator.remove_exponent(Decimal(1.0)) 1 """ return num.quantize(Decimal(1)) if num == num.to_integral() else num.normalize() def evaluate(self): """A helper method to check if submitted answer for the provided question is correct or not. This helper function uses asteval to perform check """ expression_interpreter = Interpreter() correct = SubmissionEvaluator.remove_exponent( Decimal("{:.3f}".format(expression_interpreter(self.expression))[:-1]) ) return str(correct) == self.submitted_result
true
493cc5ee3132d01c05cca6495738e3e4f6ab1436
rbodduluru/PythonCodes
/Duplicatenumsinlist.py
448
4.25
4
# #!/usr/bin/python # Python program to find the duplicate numbers in the list of numbers def finddup(myList): for i in set(myList): if myList.count(i) > 1: print "Duplicate number(s) in the list : %i"%i if __name__ == '__main__': myList = [] maxNumbers = 10 while len(myList) < maxNumbers: numbers = input("Enter numbers to find duplicates :") myList.append(numbers) finddup(myList)
true
285f282b32ba4233a000dcab3f7131bff31e638e
JancisWang/leetcode_python
/572.另一个树的子树.py
1,705
4.15625
4
''' 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。 示例 1: 给定的树 s: 3 / \ 4 5 / \ 1 2 给定的树 t: 4 / \ 1 2 返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。 示例 2: 给定的树 s: 3 / \ 4 5 / \ 1 2 / 0 给定的树 t: 4 / \ 1 2 返回 false。 在真实的面试中遇到过这道题? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/subtree-of-another-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: if not t: return True if not s: return False return self.isSame(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t) def isSame(self, s, t): if not t and not s: return True if not t or not s: return False return s.val==t.val and self.isSame(s.left, t.left) and self.isSame(s.right, t.right) class Solution: def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: ss = self.inorder(s) tt = self.inorder(t) return tt in ss def inorder(self, s): if not s: return '#' return '*' + str(s.val) + self.inorder(s.left) + self.inorder(s.right)
false
20c489dd909c4846446ecf15b8169f6a5fe9da13
dwambia/100daysofhacking
/Tiplator.py
565
4.28125
4
#Simple python code to calculate amount a user is to tip total_bill = input("What is your total bill? ") #ignore the $ sign if user inputs total_bill= total_bill.replace("$","") #convert users bill to float total_bill=float(total_bill) print(total_bill) #list of possible tips calculation tip_1= 0.15*total_bill tip_2= 0.18*total_bill tip_3= 0.20*total_bill #list out all tips print("Here's a recommendation of amounts that you can tip") #converts results of calculation to 2 d.p print(f"1. ${tip_1:.2f}") print(f"2. ${tip_2:.2f}") print(f"3. ${tip_3:.2f}")
true
c48ae9d514b516831db37fb3efbe033cdd007c90
AlexDuo/DuoPython
/OOP/inherit.py
1,369
4.46875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Duo # 使用人类做继承的例子 class relation(object): def make_friends(self,obj): print("%s is making friends with %s"%(self.name,obj.name)) self.friendlist.append(obj) class humanbeings: def __init__(self,name,age): self.name = name self.age = age self.friendlist = [] def eat(self): print("%s is eating" %self.name) def drink(self): print("%s is drinking" %self.name) def talk(self): print("%s is talking" %self.name) class man(humanbeings,relation): # man继承了humanbeings # 当我们要在父类的基础之上追加新的实例属性 def __init__(self,name,age,specialorgan): # humanbeings.__init__(self,name,age) 继承父类构造函数的第一种方法 super(man, self).__init__(name,age) #继承父类构造函数的第二种方法 self.specialorgan = specialorgan def protectfamily(self): #定义了子类的私有方法 print("%s is a man, he will protect the family") def eat(self): humanbeings.eat(self) print("He eats a lot of food") m1 = man("Duo Zhang",27,"adam's apple") m2 = man("Alex","27","adam's apple") print(m1.name+" born with a special organ named %s" %m1.specialorgan) m1.make_friends(m2) print(m1.friendlist[0].name)
false
b7a4c138b9106c64d6db33f53e6cd0b5b35e5648
olotintemitope/Algo-Practice
/quick_sort.py
1,732
4.125
4
def quick_sort(lists): lists_length = len(lists) if lists_length > 2: current_position = 0 """ Partition the lists """ for index in range(1, lists_length): pivot = lists[0] if lists[index] <= pivot: current_position += 1 swap = lists[index] lists[index] = lists[current_position] lists[current_position] = swap """ End of partitioning """ swap = lists[0] lists[0] = lists[current_position] lists[current_position] = swap left_sorted = quick_sort(lists[0:current_position]) right_sorted = quick_sort(lists[current_position + 1:lists_length]) lists = left_sorted + [lists[current_position]] + right_sorted return lists print(quick_sort([1, 4, 21, 3, 9, 20, 25, 6, 21, 14])) def QuickSort(arr): elements = len(arr) # Base case if elements < 2: return arr current_position = 0 # Position of the partitioning element for i in range(1, elements): # Partitioning loop if arr[i] <= arr[0]: current_position += 1 temp = arr[i] arr[i] = arr[current_position] arr[current_position] = temp temp = arr[0] arr[0] = arr[current_position] arr[current_position] = temp # Brings pivot to it's appropriate position left = QuickSort(arr[0:current_position]) # Sorts the elements to the left of pivot right = QuickSort(arr[current_position + 1:elements]) # sorts the elements to the right of pivot arr = left + [arr[current_position]] + right # Merging everything together return arr print(QuickSort([21, 4, 1, 3, 9, 20, 25, 6, 21, 14]))
true
326aa90db503a36ee76c999842089ea710c8dd97
Mcps4/ifpi-ads-algoritmos2020
/LISTA_2_FABIO_PARTE_2/F2_P2_Q5_PRODUTOS.PY
1,041
4.125
4
def main(): produto_1 = float(input('Digite o preço primeiro produto:')) produto_2 = float(input('Digite o preço segundo produto:')) produto_3 = float(input('Digite o preço terceiro produto:')) precos(produto_1, produto_2, produto_3) def precos(produto_1, produto_2, produto_3): if produto_1 < produto_2 and produto_2 < produto_3: print('Compre o primeiro produto') if produto_2 < produto_1 and produto_1 < produto_3: print('Compre o segundo produto') if produto_3 < produto_2 and produto_2 < produto_1: print('Compre o terceiro produto') if produto_1 < produto_3 and produto_3 < produto_2: print('Compre o primeiro produto') if produto_2 < produto_3 and produto_3 < produto_1: print('Compre o segundo produto') if produto_3 < produto_1 and produto_1 < produto_2: print('Compre o terceiro produto') if produto_1 < produto_2 and produto_2 < produto_3: print('Compre o primeiro produto') main()
false
36b47b83057b9df45ac0df30a99c54dc7ba604e6
Dex4n/exercicios-python
/exercicio_03.py
875
4.46875
4
#3 - Crie uma classe calculadora com as quatro operações básicas (soma, subtração, multiplicação e divisão). # usuário deve informar dois números e o programa deve fazer as quatro operações. class Calculadora: def soma (self, numero1, numero2): return numero1 + numero2 def subtracao(self, numero1, numero2): return numero1 - numero2 def multiplicacao(self, numero1, numero2): return numero1 * numero2 def divisao(self, numero1, numero2): return numero1 / numero2 c1 = Calculadora() soma = c1.soma(1,3) divisao = c1.divisao(10,2) multiplicacao = c1.multiplicacao(2,4) subtracao = c1.subtracao(33,3) print ("Resultado da soma: %.2f" %(soma)) print ("Resultado da divisão: %.2f" %(divisao)) print ("Resultado da multiplicação: %.2f" %(multiplicacao)) print ("Resultado da subtração: %.2f" %(subtracao))
false
93173a6bfe98ad20e0492289b53e0fe63ec4bd37
Alm3ida/resolucaoPythonCursoEmVideo
/desafio35.py
646
4.125
4
"""Analise os comprimentos e verifique se é possível formar um triângulo""" from math import fabs a = float(input('Digite o valor do primeiro lado: ')) b = float(input('Digite o valor do segundo lado: ')) c = float(input('Digite o valor do terceiro lado: ')) """ A condição de existência de um triângulo de lados a, b, c é dada por: |a-b| < c < a + b |a-c| < b < a + c |b-c| < a < b + c """ if fabs(a-b) < c and c < (a + b) and fabs(a-c) < b and b < (a + c) and fabs(b-c) < a and a < (b + c): print('É possível formar um triângulo com esses lados!!!') else: print('Não é possível formar um triângulo com esses lados!!!')
false
fc022efeb99cf1ca3f7c4e9b9e8b3754061d8439
Alm3ida/resolucaoPythonCursoEmVideo
/desafio58.py
684
4.15625
4
""" Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer """ from random import randint contagem = 0 numC = randint(0, 10) numP = int(input(''' Estou pensando em um número entre 0 e 10... Tente adivinhar qual!: ''')) while numP != numC: if numP < numC: print('Mais... Tente mais uma vez. ') contagem += 1 else: print('Menos... Tente mais uma vez. ') contagem += 1 numP = int(input('Digite novamente: ')) contagem += 1 print(f'Acertou com {contagem} tentativas, Parabéns!!!')
false
92146b3c6056ca9ba4fcdcd849a340716999b743
Alm3ida/resolucaoPythonCursoEmVideo
/desafio42.py
925
4.125
4
""" Refaça o desafio 35 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: - Equilátero: todos os lados iguais - Isósceles: dois lados iguais - Escaleno: todos os lados diferentes """ import math a = int(input('Digite o valor do primeiro lado: ')) b = int(input('Digite o valor do segundo lado: ')) c = int(input('Digite o valor do terceiro lado: ')) if math.fabs(a-b) < c and c < (a + b) and math.fabs(a-c) < b and b < (a + c) and math.fabs(b-c) < a and a < (b + c): print('É possível formar um triângulo!!!') if a == c and c == b: print('O triângulo formado é Equilátero') elif (a == b and a != c) or (a == c and a != b) or (b == c and b != a): print('O triângulo formado é Isósceles!') elif (a != b) and (a != c) and (b != c): print('O triângulo formado é Escaleno!') else: print('Não é possível formar um triângulo.')
false
3f749cb2850ed64d6f566e23b75c1df30023bab7
Divyalok123/CN_Data_Structures_And_Algorithms
/more_problems/Test2_P2_Problems/Minimum_Length_Word.py
298
4.28125
4
#Given a string S (that can contain multiple words), you need to find the word which has minimum length. string = input() newArr = string.split(" ") result = newArr[0] for i in range(1, len(newArr)): if(len(newArr[i]) < len(result)): result = newArr[i] print(result)
true
f312341382425fcd01f4a489b0fc7e615ac3ba22
diek/backtobasics
/trade_apple_stocks.py
1,541
4.1875
4
'''Suppose we could access yesterday's stock prices as a list, where: The indices are the time in minutes past trade opening time, which was 9:30am local time. The values are the price in dollars of Apple stock at that time. So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500. Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.''' stock_prices_yesterday = [10, 7, 5, 8, 11, 9] # No "shorting"—you must buy before you sell. You may not buy and sell in the # same time step (at least 1 minute must pass). def get_best_profit(stock_prices_yesterday): # we'll greedily update min_price and best_profit, so we initialize # them to the first price and the first possible profit min_price = stock_prices_yesterday[0] best_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0] for index, stock in enumerate(stock_prices_yesterday): # skip the first (0th) time if index == 0: continue # see what our profit would be if we bought at the # min price and sold at the current price potential_profit = stock - min_price # update best_profit if we can do better best_profit = max(best_profit, potential_profit) # update min_price so it's always # the lowest price we've seen so far min_price = min(min_price, stock) return best_profit print(get_best_profit(stock_prices_yesterday))
true
a0e534755de438b61477b6e823fca6069a07aeb4
beggerss/algorithms
/Sort/quick.py
1,410
4.1875
4
#!/usr/bin/python2 # Author: Ben Eggers (ben@beneggers.com) import time import numpy as np import matplotlib.pyplot as plt import itertools # Implementation of a quicksort in Python. def main(): base = 10000 x_points = [] y_points = [] for x in range(1, 20): arr = [np.random.randint(0, base*x) for k in range(base*x)] start = int(round(time.time() * 1000)) arr = quick_sort(arr) end = int(round(time.time() * 1000)) x_points.append(len(arr)) y_points.append(end - start) print("%d ms required to sort array of length %d using quicksort." % (end - start, len(arr))) make_plot(x_points, y_points) def quick_sort(arr): if len(arr) <= 1: return arr # There are many ways to choose a pivot, we'll just grab a random element pivot_index = np.random.randint(0, len(arr) - 1) pivot = arr[pivot_index] del arr[pivot_index] less = [] greater = [] for x in arr: if x <= pivot: less.append(x) else: greater.append(x) lists = [quick_sort(less), [pivot], quick_sort(greater)] # pivot must be in its own sublist for the below list comprehension to work return [item for sublist in lists for item in sublist] def make_plot(x_points, y_points): plt.plot(x_points, y_points, 'ro') plt.axis([0, max(x_points), 0, max(y_points)]) plt.xlabel('length of array') plt.ylabel('time to sort (milliseconds)') plt.title('Efficiency of quick sort') plt.show() if __name__ == "__main__": main()
true
fc7388718bca1ed338e149cca0db47afca7f135c
Shasheen8/just_tests
/palindrome.py
541
4.1875
4
def Palindrome(mystr): try: mystr= "malayalam" rev_mystr= reversed(mystr) if (mystr == rev_mystr): return ("The string is a palindrome") else : return ("The string is not a palindrome") except ValueError: return "valid only for a string" def test1(): assert Palindrome("malayalam") def test2(): assert Palindrome("shasheen") =="The string is not a palindrome" def test3(): assert Palindrome("123")== "The string is not a palindrome"
false
3c50a395000e9474c8be1cd4233e55137df20293
jscs9/assignments
/moves.py
1,681
4.1875
4
import random as rand def request_moves(how_many): ''' Generates a string representing moves for a monster in a video game. how_many: number of move segments to be generated. Each segment occurs in a specific direction with a distance of between 1 and 5 steps. Segment directions do not repeat, or immediately double back on themselves, e.g. 'u' cannot follow 'd', 'l' cannot follow 'r', etc. Returns: A string of characters made of 'l', 'r', 'u', 'd' that describes how the monster moves. ''' dirmap = ['l', 'r', 'u', 'd'] # a list of abbreviations for directions # generate an initial direction and distance between 1 and 5 steps dir = dirmap[rand.randint(0, 3)] moves = dir*rand.randint(1, 5) # For each move, randomly determine its direction, and how far (between 1 and 5 steps) for i in range(how_many-1): # get a random number between 0 and 3 # generate directions randomly until we get a direction that # is not the same as the previous direction. dir = moves[-1] while (dir == moves[-1] or (dir == 'r' and moves[-1] == 'l') or (dir == 'u' and moves[-1] == 'd') or (dir == 'l' and moves[-1] == 'r') or (dir == 'd' and moves[-1] == 'u')): dir = dirmap[rand.randint(0, 3)] # map the number to a legal move character using 'dirmap', # make between 1 and 5 copies of that move character, # and concatenate it with the existing moves generated so far. moves = moves + dir * rand.randint(1, 5) return moves
true
d743d3a14ada3869d20047f59194f3d92cee2d62
okomeshino/python-practice
/basic/range.py
398
4.125
4
# encoding:utf-8 # 10を引数で渡す → 10回ループ for i in range(10): print(i) if i == 9: print("------------------------------") # 2と10を引数で渡す → 2から始まって9までループ for i in range(2, 10): print(i) if i == 9: print("------------------------------") # 負の数を渡すことも可能 for i in range(-2, 10): print(i)
false
a77fa382d0086b208654915fd2e6dde4d31ce021
krzysztof-laba/Python_Projects_Home
/Polymorphism/polymorphism_3.py
1,194
4.21875
4
class Document(): def __init__(self, name): self.name = name def show(self): raise NotImplementedError("Subclass must implement abstract method.") class Pdf(Document): def show(self): return "Show pdf documents!" class Word(Document): def show(self): return "Show word documents!" documents = [Pdf('Document_1'), Pdf('Document_2'), Word('Document_3')] for document in documents: print(document.name + ' : ' + document.show()) print("") print("*** How inheritance works. ***", end="\n\n") class Base_class(): def __init__(self, name): self.name = name print("__init_ in base class. Name: '{0}'.".format(self.name)) def test(self): raise NotImplementedError("Abstract class.") class Another_class(Base_class): def test(self): self.show_inheritance() self.show_inheritance_2() def show_inheritance(self): print("inheritance from method 1") def show_inheritance_2(self): print("inheritance_2 from method 2") another_class = Another_class("1-st class") another_class.test() print("") another_class_2 = Another_class("2-nd class") another_class_2.test()
false
1e9d15bcc381cea35ba1496e94a25c4ed981878f
krzysztof-laba/Python_Projects_Home
/CodeCademy/SchoppingCart.py
970
4.15625
4
class ShoppingCart(object): """Creates shopping cart objects for users of our fine website""" items_in_cart = {} def __init__(self, customer_name): self.customer_name = customer_name print("Customer name:", self.customer_name) def add_item(self, product, price): """Add product to the cart""" if not product in self.items_in_cart: self.items_in_cart[product] = price print(product, " added.") else: print(product, " is arleady in the cart.") def remove_item(self, product): """Remove product from the cart.""" if product in self.items_in_cart: del self.items_in_cart[product] print(product, " removed") else: print(product, " is not in the cart.") my_cart = ShoppingCart("Krzysztof Laba") my_cart.customer_name my_cart.add_item("Mleko", 3) my_cart.add_item("Bułka", 0.5) my_cart.add_item("Ciastko", 2.2) my_cart.add_item("Jabłko", 1.5) print(ShoppingCart.items_in_cart) my_cart.remove_item("Bułka") print(ShoppingCart.items_in_cart)
true
05aa5bd36eba8a10f25800c4d61829f1e5710a67
RadioFreeZ/Python_October_2018
/python_fundamentals/function_basic2.py
1,655
4.34375
4
#Countdown - Create a function that accepts a number as an input. Return a new array that counts down by one, from the number # (as arrays 'zero'th element) down to 0 (as the last element). For example countDown(5) should return [5,4,3,2,1,0]. def countdown(num): return [x for x in range(num, -1,-1)] print(countdown(5)) #Print and Return - Your function will receive an array with two numbers. Print the first value, and return the second. def printAndReturn(arr): print("First Value -", arr[0]) return(arr[1]) print(printAndReturn([5,6])) def firstPlusLength(arr): return arr[0] + len(arr) print(firstPlusLength([1,2,3,4])) #Values Greater than Second - Write a function that accepts any array, # and returns a new array with the array values that are greater than its 2nd value. # Print how many values this is. If the array is only one element long, have the function return False def greaterThanSecond(arr): if (len(arr) == 1): return False array = [] for val in arr: if(val > arr[1]): array.append(val) print(len(array)) return array print(greaterThanSecond([1,4,6,7,8,1,2])) # This Length, That Value - Write a function called lengthAndValue which accepts two parameters, size and value. # This function should take two numbers and return a list of length size containing only the number in value. # For example, lengthAndValue(4,7) should return [7,7,7,7]. def LengthAndValue(size, value): # new_arr = [] # for count in range(size): # new_arr.append(value) # return new_arr return [value for i in range(size)] print(LengthAndValue(7,5))
true
9257ae7106cf111e01eae338b262a65947204458
DishaCoder/Solved-coding-challenges-
/lngest_pall_str.py
221
4.125
4
inputString = input("Enter string : ") reverse = "".join(reversed(inputString)) size = len(inputString) if (inputString == reverse): print("Longest pallindromic string is ", inputString) else: for
true
eb31fc6b5c6b5957bf62c9a7c48864dee92aeba5
lyvd/learnpython
/doublelinkedlist.py
1,521
4.5
4
#!/usr/bin/python ''' Doubly Linked List is a variation of Linked list in which navigation is possible in both ways either forward and backward easily as compared to Single Linked List. ''' # A node class class Node(object): # Constructor def __init__(self, data, prev, nextnode): # object data self.data = data # previous node self.prev = prev # next node self.next = nextnode # Dobule list of nodes class DoubleList(object): def __init__(self): self.head = None self.tail = None # append a node to the list def append(self, data): tail = Node(data, None, None) # create a new node new_node = Node(data, None, None) # if node is the last node if self.head is None: # head = tail = new node self.head = self.tail = new_node else: # point prev link of new node to tail new_node.prev = self.tail # create a new node new_node = None # point next link of tail to new node self.tail.next = new_node # tail is the new node self.tail = new_node # Show nodes def show(self): print("Showing list data:") # external variable point to head current_node = self.head # loop until the end of the list while current_node is not None: print(current_node.data) if hasattr(current_node.prev, "data") else None, print(current_node.data), print(current_node.next.data) if hasattr(current_node.next, "data") else None current_node = current_node.next d = DoubleList() d.append(5) d.append(6) d.append(50) d.append(30) d.show()
true
df9f7a91df1bbb03d9f9661ece0c905936aba7b8
lyvd/learnpython
/node.py
552
4.1875
4
#!/usr/bin/python # Create a class which presents a node class BinaryTree: def __init__(self, rootObj): # root node self.key = rootObj # left node self.leftChild = None self.rightChild = None # Insert a left node to a tree def insertLeft(self, newNode): # if there is no left node if self.leftChild == None: self.leftChild == BinaryTree(newNode) # if there is an existing left node # adding the existing node to the node we are adding else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t
true
f0d0c2f1b869c22f0d16a4b26ddd8ff489623903
aRToLoMiay/Special-Course
/Основные инструкции/errors.py
852
4.34375
4
# -*- coding: utf-8 -*- # Программа для вычисления положения мяча при вертикальном движении # с использованием функции # Упражнение 1. Ошибки с двоеточиями, отступами и т.п. def y(t): v0 = 5 # Начальная скорость g = 9.81 # Ускорение свободного падения return v0*t - 0.5*g*t**2 t = 0.6 # Время print y(t) t = 0.9 print y(t) # при "def y(t)" - SyntaxError: invalid syntax # без отступа перед "v0 = 5" - IndentationError: expected an indented block # "v0 = 5" с тремя пробелами - IndentationError: unexpected indent # "yt)" - SyntaxError # "y()" - TypeError # "print y()" - TypeError: y() takes exactly 1 argument (0 given)
false
030139068d2f3eafd4e60f3e3bfabf374a174e30
akjalbani/Test_Python
/Misc/Tuple/xycoordinates.py
499
4.15625
4
""" what are the Mouse Coordinates? """ ## practical example to show tuples ## x,y cordinates stored as tuple, once created can not be changed. ## use python IDLE to test this code. ## 08/06/2020 import tkinter def mouse_click(event): # retrieve XY coords as a tuple coords = root.winfo_pointerxy() print('coords: {}'.format(coords)) print('X: {}'.format(coords[0])) print('Y: {}'.format(coords[1])) root = tkinter.Tk() root.bind('<Button>', mouse_click) root.mainloop()
true
e6d26f45c62d5a0b943c6c43e712fe04dc9307d1
akjalbani/Test_Python
/Misc/Network/dictionary_examples.py
2,039
4.5
4
# let us have list like this devices = ['router1', 'juniper', '12.2'] print(devices) ############### Another way to print values ######################### for device in devices: print(device) #If we build on this example and convert the list device to a dictionary, it would look like this: devices = {'hostname': 'router1', 'vendor': 'juniper', 'os': '12.1'} print(devices) ###########Print only keys################################################# for device in devices: print(device) # this will print keys ###############Print only values ############################################# for v in devices.values(): print(v) ##############print key and value############################################## for device in devices: print(device,devices[device]) # print key and value ##### OR####print key and value############################################### for k,v in devices.items(): print(k,v) ############################################ ############################## ### access any desired value pass the key print("host name: "+ devices['hostname']) print("host name: "+ devices['vendor']) print("host name: "+ devices['os']) ######################################################################### ## how to get keys print(devices.keys()) # how to get values print(devices.values()) ################################################################## ## How to add new value - key and value- this will add as a last item in the dictionary devices['location'] = "room2.31" print(devices) ################################################################ ## create new empty dictionary and add items to it student = {} student["id"] = 100232 student["name"] = "Michael" student["class"] = "python" student["year"] = 2020 print(student) ################################################################ # dictionary built in functions print(dir(dict)) ############################################################### # how to delete item # pop() key to delete particualr key and value student.pop('id') print(student)
true
29900772d1df82995e52988be2eba8303b1457fd
akjalbani/Test_Python
/Misc/Turtle_examples/shape2.py
288
4.15625
4
# Turtle graphics- turtle will draw angle from 0-360 (15 deg) # tested in repl.it # Type- collection and modified import turtle turtle = turtle.Turtle() for angle in range(0, 360, 15): turtle.setheading(angle) turtle.forward(100) turtle.write(angle) turtle.backward(100)
true
255724b8bd84e1a0dbd793d35eec9d935fb480f5
susankorgen/cygnet-software
/Python100DaysClass2021/py/CoffeeMachineOOP/coffee_maker.py
2,064
4.15625
4
# Instructor code. # Except: Student refactored the self.resources structure and added get_resources. class CoffeeMaker: """Models the machine that makes the coffee""" def __init__(self): self.resources = { "water": { "amount": 500, "units": "ml", }, "milk": { "amount": 200, "units": "ml", }, "coffee": { "amount": 100, "units": "g", }, } def report(self): """Prints a report of all resources.""" for item in self.resources: drink = self.resources[item] print(f"{item.title()}: {drink['amount']}{drink['units']}") def is_resource_sufficient(self, drink): """Returns True when order can be made, False if ingredients are insufficient.""" can_make = True for item in drink.ingredients: if drink.ingredients[item] > self.resources[item]['amount']: print(f"Sorry, there is not enough {item} to make {drink.name}.") can_make = False return can_make def make_coffee(self, order): """Deducts the required ingredients from the resources.""" for item in order.ingredients: self.resources[item]['amount'] -= order.ingredients[item] print(f"Here is your {order.name} ☕. Enjoy!") # Student added. def get_resources(self): """ Prompt for and process an amount of refill of each resource. Silently convert bad input to zero. :rtype: None """ print("Before refill:") self.report() for item in self.resources: units = self.resources[item]['units'] added = input(f"Add {item} ({units}): ").strip() try: adding = int(added) except ValueError: adding = 0 self.resources[item]['amount'] += adding print("After refill:") self.report()
true
84541b7ceb0b56ad10f0fede67d7c32823d09814
ianmanalo1026/Projects
/Biginners/Guess the number (Project1).py
2,015
4.15625
4
import random class Game: """Player will guess the random Number""" def __init__(self): self.name = None self.number = None self.random_number = None self.indicator = None def generateNumber(self): self.random_number = random.randint(1,5) return self.random_number def enterNumber(self): self.number = input("Enter Number:") while type(self.number) is not int: try: self.number = int(self.number) except ValueError: self.number = input("Enter a valid Number:") return self.number def start(self): self.indicator = list() self.name = input("Your Name: ") self.random_number = self.generateNumber() print(f"Hi {self.name}") print("Start the game! You have 3 attempts to guess the number!") print("Guess the Number from 1 - 5") self.enterNumber() while len(self.indicator) <= 1: if self.number < self.random_number: self.indicator.append(self.number) print("higher") self.enterNumber() if self.number > self.random_number: self.indicator.append(self.number) print("lower") self.enterNumber() elif int(self.number) == int(self.random_number): print("You got it!") print(f"The random number is {self.random_number}") x = input("Would you like to play again? (yes or no): ") if x == "yes": self.start() else: print(f"Thanks for playing {self.name}") break print(f"The random number is {self.random_number}") x = input("Would you like to play again? (yes or no): ") if x == "yes": self.start() else: print(f"Thanks for playing {self.name}") x = Game() x.start()
true
488421439b7188696f4e4d7f33dcc682e1bb3ef9
120Davies/Intro-Python-I
/src/13_file_io.py
1,074
4.375
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" with open('foo.txt') as f: # Using with is more brief than opening and closing separately. read_data = f.read() print(read_data) print(f.closed) # To show the file closed after printing # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain with open('bar.txt', 'w') as f: f.write("This is the first line of bar.txt.\n") f.write("Their wives and children will mourn as Jeremiah.\n") f.write("This is the last line of bar.txt.") with open('bar.txt') as f: print(f.read())
true
845883db9a28eb311b552650748ce4037f0ccb21
RocioPuente/KalAcademyPython
/HW3/Palindrome.py
353
4.1875
4
def reverse(number): rev=0 while number > 0: rev = (10*rev)+number%10 number//=10 return rev #print(reverse (number)) def isPalindrome(number): if number == reverse(number): return ("The number is a Palindrome") else: return ("The number is not a Palindrome") #print (isPalindrome(number))
true
427d378903744e1d5e6b11fffcd1833e4a4e1465
fannifulmer/exam-basics
/oddavg/odd_avg.py
520
4.15625
4
# Create a function called `odd_average` that takes a list of numbers as parameter # and returns the average value of the odd numbers in the list # Create basic unit tests for it with at least 3 different test cases def odd_average(numbers): new_list = [] try: for number in range(len(numbers)): if numbers[number] % 2 != 0: new_list.append(numbers[number]) return sum(new_list) / len(new_list) except ZeroDivisionError: return None odd_average([2, 3, 4])
true
c9314fef90c6104045e9fc0ddb376f8b70304c5d
nipunramk/Introduction-to-Computer-Science-Course
/Video19Code/video19.py
1,490
4.1875
4
def create_board(n, m): """Creates a two dimensional n (rows) x m (columns) board filled with zeros 4 x 5 board 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 x 2 board 0 0 0 0 0 0 >>> create_board(4, 5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> create_board(3, 2) [[0, 0], [0, 0], [0, 0]] """ if n == 0 or m == 0: raise IndexError("dimensions cannot both be zero") if n < 0 or m < 0: raise IndexError("dimensions cannot be negative") board = [] rows = [0] * m for i in range(n): board.append(rows) return board def invert(x): """A special invert function that will return 1/x, except in the case that we pass in x = 0, in which case we return 1 """ try: return 1 / x except ZeroDivisionError as e: print(e) return 1 class RangeIterable: """Implements the __iter__ method, making objects of the class iterable""" def __init__(self, start, end): self.start = start self.end = end def __iter__(self): return RangeIterator(self.start, self.end) class RangeIterator: """Implements both __iter__ and __next__ methods, making objects of this class function as both iterables and iterators """ def __init__(self, start, end): self.start = start self.end = end self.current = start def __next__(self): if self.current == self.end: self.current = self.start raise StopIteration result = self.current self.current = self.current + 1 return result def __iter__(self): return self
true
4d1423ccc90971c23c833e73bbdc3374da797e0d
hannahpaxton/calculator-2
/arithmetic.py
2,463
4.1875
4
"""Functions for common math operations.""" def add(num1, num2): """Return the sum of the two inputs.""" # define a variable "sum" # set this variable as the sum of num1, num2. sum = num1+num2 # return sum sum_nums = num1 + num2 return sum_nums def subtract(num1, num2): """Return the second number subtracted from the first.""" #def variable for subtract #set subtract variable to find difference between two numbers #return subtract variable difference = num1 - num2 return difference def multiply(num1, num2): """Multiply the two inputs together.""" #define variable for result #save result of num1 multiplied by num2 #return result product = num1 * num2 return product def divide(num1, num2): """Divide the first input by the second and return the result.""" #define function for divide #add quotient variable that divides num1 and num2 #return quotient quotient = num1/num2 return quotient def square(num1): """Return the square of the input.""" #define variable for square #save result of squaring to the variable #return result [squared] squared = num1 ** 2 return squared def cube(num1): """Return the cube of the input.""" #define variable for a cube #take num1 to the third power #return the cube variable is_cubed = num1 ** 3 return is_cubed def power(num1, num2): """Raise num1 to the power of num2 and return the value.""" #define variable for result #save result of num1 raised to num2 into result #return result exponent_result = num1 ** num2 return exponent_result def mod(num1, num2): """Return the remainder of num1 / num2.""" #define remainder variable #capturn remainder when num1 / num2 #return remainder variable remainder = num1 % num2 return remainder # define function add_mult with 3 parameters # add num1 and num2, multiply the result with num3 # return the final result def add_mult(num1, num2, num3): """ Return the sum of num 1 + num2 multiplied by num3""" equation = (num1 + num2) * num3 return equation #define function add_cubes with 2 parameters #define vaiable that takes the cubes of num1 and num2 and adds them together #return the sum of the cubes save in that variable def add_cubes(num1, num2) : """ Return the sum of cubes.""" sum_cubes = (num1**3) + (num2**3) return sum_cubes
true
b072e29a8a8f7ef5256c727290fe2a5c9fb949f5
ArpitaDas2607/MyFirst
/exp25.py
2,222
4.3125
4
def break_words(stuff): '''This function will, break up words for us.''' words = stuff.split(' ') return words #Trial 1: #print words stuff = "Now this looks weird, it\'s blue and green and all in between" statements = break_words(stuff) print statements #-----------------------------------------------------------------------------# def sort_words(words): '''This will sort words''' return sorted(words) #Trial 2: wordsNew = "Expeliarimus" trial = sort_words(wordsNew) print trial #-----------------------------------------------------------------------------# def print_first_word(words): '''Prints the first word after popping it off''' word = words.pop(0) return word #Trial 3: #Note that an argument for pop is always a list which can be created from a sentence by split(' ') #aList = [123, 'xyz','zara','abc'] print statements firstWord = print_first_word(statements) print firstWord #-----------------------------------------------------------------------------# def print_last_word(words): '''Prints last word after popping it off''' word = words.pop(-1) print word #Trial 4: print statements LastWord = print_last_word(statements) print LastWord #-----------------------------------------------------------------------------# def sort_sentence(sentence): '''Takes in a full sentence and returns the sorted words''' words = break_words(sentence) return sort_words(words) #Trial 5: Break = sort_sentence("I am Das") print Break #-----------------------------------------------------------------------------# def print_first_and_last(sentence): '''Prints the first and last words of the sentence''' words = break_words(sentence) a = print_first_word(words) b = print_last_word(words) return a,b #Trial 6: A,B = print_first_and_last("I am Das too") print A print B #-----------------------------------------------------------------------------# def print_first_and_last_sorted(sentence): '''Sorts the words then prints the first and last one ''' words = sort_sentence(sentence) a = print_first_word(words) b = print_last_word(words) #Trial 7: A,B = print_first_and_last("I am Das as well") print A print B
true
771482ef77c84b1daf7d50d8fce7d4d0aabf94ce
Anthima/Hack-CP-DSA
/Leetcode/BinarySearch/solution.py
877
4.125
4
# RECURSIVE BINARY SEARCH. class Solution: def binarySearch(self,arr,start,end,target): if(start <= end): # FINDING THE MIDDLE ELEMENT. mid = start+((end-start)//2) # CHECKING WHETHER THE MIDDLE ELEMENT IS EQUAL TO THE TARGET. if(arr[mid] == target): return mid # CHECKING WHETHER THE MIDDLE ELEMENT IS LESSER THAN THE TARGET. elif(arr[mid] < target): return self.binarySearch(arr,mid+1,end,target) # CHECKING WHETHER THE MIDDLE ELEMENT IS GREATER THAN THE TARGET. elif(arr[mid] > target): return self.binarySearch(arr,start,mid-1,target) return -1 def search(self, nums: List[int], target: int) -> int: return self.binarySearch(nums,0,len(nums)-1,target)
true
9687ded4776870f4a119959b99ef6bb5dda412ba
Anthima/Hack-CP-DSA
/Leetcode/Valid Mountain Array/solution.py
596
4.3125
4
def validMountainArray(arr): i = 0 # to check whether values of array are in increasing order while i < len(arr) and i+1 < len(arr) and arr[i] < arr[i+1]: i += 1 # i == 0 means there's no increasing sequence # i+1 >= len(arr) means the whole array is in increasing order if i == 0 or i + 1 >= len(arr): return False # to check whether values of array are in decreasing order while(i < len(arr) and i+1 < len(arr)): if arr[i] <= arr[i+1]: return False i += 1 return True print(validMountainArray([0, 3, 2, 1]))
true
1eb14c2eb2e8174f6e5e759daaa32afba5bc9612
rowand7906/cti110
/M3HW1_AgeClassifier_DanteRowan.py
421
4.34375
4
#Age Classifier #June 14, 2017 #CTI 110 M3HW1 - Age Classifier #Dante' Rowan # Get the age of the person age = int(input('Enter the age of the person: ')) # Calculate the age of the person. # Determine what age the person is if 1: print('Person is an infant.') elif 1 > 13: print('Person is a child.') if 13 > 20: print('Person is a teenager.') if 20: print('Person is an adult.')
true
2da8a1ca5b0ee01c712e682cdeef21c8b5f836bf
diesears/E01a-Control-Structues
/main10.py
2,414
4.3125
4
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') #making the greetings text appear colors = ['red','orange','yellow','green','blue','violet','purple'] #outlines the possible responses play_again = '' #enabling the play again feature for more responses best_count = sys.maxsize #no limit on how many times to play # the biggest number while (play_again != 'n' and play_again != 'no'): #establishing possible negative answers to playing again match_color = random.choice(colors) #allows the computer to insert a random answer from the given choices count = 0 #establishes where the computer should start counting the attempts color = '' #sets the area for a response while (color != match_color): #establishes the condtion that the response must match the correct answer color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line color = color.lower().strip() #this allows answers in upper and lower case and with spaces before or after count += 1 #establishes that after this attempt the total attempts will be 1 if (color == match_color): #the condition for which to print correct print('Correct!') # what will be printed with a correst response else: #establishing the other possible answers print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #what will be printed for an incorrect response an a counter to count how many total responses print('\nYou guessed it in {0} tries!'.format(count)) #printing to inform the reader how many tries it took them to guess correctly if (count < best_count): #establishing a specific condition for the computer to react to, when its the readers best guess print('This was your best guess so far!') # displaying the fact that this was their closest guess best_count = count #changing this new best score to reflect the overall best score play_again = input("\nWould you like to play again? ").lower().strip() #displaying the question if the reader wants to play again with a chance for input print('Thanks for playing!') #shows the final line that thanks the reader for playing
true
3d34e2eada50e5d5f166e5c6bfdd30cc576c5c1e
abhishekpn/Know-your-future-age-
/age in 2090.py
1,087
4.15625
4
print('AGE CALCULATOR MACHINE') print("1.You can calculate what is your age will be in any paricular year \n" "2.You can calculate when you will be 100 years old ") curr_year = 2020 value = str(input("Enter your Age OR Year of birth: ")) if len(value)<=2: print(f"This is your present age {value}") count = 100 - int(value) count = count + curr_year print(f"You will be 100 years old in year {count}") elif len(value)>3: print(f"Your current age is {curr_year - int(value)}") count = int(value) + 100 print(f"You will be 100 years old in {count}") elif int(value) >= 100: print("You are already 100 years old") else: print("Please check your input again ") interestedYear = int(input("Enter the year you want too know your age: ")) if len(value)<=2: year = interestedYear - curr_year year = year + int(value) print(f"You will be {year} years old in {interestedYear} ") elif len(value)>3: year = interestedYear - int(value) print(f"You will be {year} years old in {interestedYear} ")
false
a4933426e475c8d8d34bc7ea7ca00f9706836202
stanwar-bhupendra/LetsLearnGit
/snum.py
411
4.1875
4
#python program to find smallest number among three numbers #taking input from user num1 = int(input("Enter 1st number: ")) num2 = int(input("Enter 2nd number: ")) num3 = int(input("Enter 3rd number: ")) if(num1 <= num2) and (num1 <= num3): snum = num1 elif(num2 <=num1) and (num2 <=num3): snum = num2 else: snum = num3 print("The smallest number among ", num1,",", num2,",", num3 ,"is :", snum)
true
773b41d9f6a9ad8133fda4c9954c35ca45dece2d
patrickbeeson/python-classes
/python_3/homework/Data_as_structured_objects/src/coconuts.py
1,034
4.15625
4
""" API for coconut tracking """ class Coconut(object): """ A coconut object """ def __init__(self, coconut_type, coconut_weight): """ Coconuts have type and weight attributes """ self.coconut_type = coconut_type self.coconut_weight = coconut_weight class Inventory(object): """ An inventory object for managing Coconuts. """ coconuts = [] def add_coconut(self, coconut): """ Add a coconut to inventory. Raise AttributeError if object isn't a coconut. """ if isinstance(coconut, Coconut): self.coconuts.append(coconut) else: raise AttributeError('Only coconuts can be added to inventory.') def total_weight(self): """ Calculate the total weight of coconuts in inventory. """ weight = 0 for coconut in self.coconuts: weight += coconut.coconut_weight return weight
true
30cfd0f856263b7889e535e9bea19fd645616ef9
patrickbeeson/python-classes
/python_1/homework/secret_code.py
870
4.59375
5
#!/usr/local/bin/python3 """ This program takes user input, and encodes it using the following cipher: Each character of the string becomes the character whose ordinal value is 1 higher. Then, the output of the program will be the reverse of the contructed string. """ # Get the user input as a string user_input = str(input('Enter the message to be obfuscated: ')) # Create our list of letters from the string letter_list = list(user_input) # Create our empty changed letter list changed_letter_list = [] # Loop through the letters in the list for letter in letter_list: # Advance the ordinal number for each letter by one changed_letter_ord = ord(letter) + 1 # Add our changed letters to the changed letter list changed_letter_list += chr(changed_letter_ord) # Print a reversed changed letter list print(''.join(reversed(changed_letter_list)))
true
81de86c9e5ae59d686bb8155ea4a75fd8c26e84e
dinodre1342/CP1404_Practicals
/Prac5/week5_demo3.py
802
4.28125
4
def subject(subject_code, subject_name): """ This is a function for printing subject code and name. :param subject_code: This is the JCU unique code for each subject :param subject_name: This is the associated name matching the code :return: A string message displaying both code and name """ string_msg = "This subject {} refers to {}".format (subject_code, subject_name) print(string_msg) return string_msg def main(): #print(subject()) #print (subject("3400", "New Subject")) #print (subject("4000")) #print (subject(subject_name="abc")) print (subject.__name__) print (subject.__doc__) print (subject.__str__) print (subject.__dict__) #print(subject("","").__doc__) #print subject ("1404", "Intro to programming") main()
true
267424da731e2162e11a87f8e1ba38c671e04dbd
ronaldobrisa/projetos-python
/TUPLAS.py
1,584
4.28125
4
#lanche = tupla() lista[] dicionário{} #TUPLAS EM PYTHON SÃO IMUTÁVEIS #lanche = ('hamburguer', 'pizza', 'suco', 'pudim') #Fatiamento de tuplas #print(f'Eu gosto de, ', lanche[:2]) #print(f'Eu gosto de, ', lanche[-2]) #print(f'Eu gosto de, ', lanche[-2:]) #for comida in lanche: #print(f'Eu gosto de {comida}') #print(f'Comi bastante hj!!!') #Mostra quantos itens tenho na tupla #print(len(lanche)) #Contador de posições da tupla usando for e range #for cont in range(0, len(lanche)): #print(cont) #Contador de posições da tupla mostrando strings usando for e range #for cont in range(0, len(lanche)): #print(f'Eu gosto de',lanche[cont]) #Mostrar a string na tupla e posição #for cont in range(0, len(lanche)): #print(f'Eu gosto de {lanche[cont]}, na posição {cont}') #Mostrar a string na tupla e posição utilizando o método Enumerate e 2 variáveis #for pos, comida in enumerate(lanche): #print(f'Eu gosto de {comida}, na posição {pos}') #Utilizando método Sorted para organizar os elementos da tupla alfabeticamente #print(sorted(lanche)) #Junção de tuplas em ordem crescente a = (2, 4, 6) b = (3, 7, 2, 10) c = a + b #print(sorted(c)) #Método para contar quantas vezes o respectivo número aparece na tupla #print(c.count(4)) #Método index mostra em que posição está o respectivo número na tupla #print(c) #print(f'posicão {c.index(7)}') ##Método index mostra em que posição está o respectivo número na tupla a partir da posição definida #print(c) número | posição #print(f'posicão {c.index(7, 1)}')
false
91b5a6c3d5e2e6e9efea43f259386b8633ced137
tomasztuleja/exercises
/practisepythonorg/ex2_1.py
324
4.1875
4
#!/usr/bin/env python # http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html inp = int(input("Type an Integer: ")) test = inp % 2 testfour = inp % 4 if test == 0: print("It's an even number!") if testfour == 0: print("It's also a multiple of 4!") else: print("It's an odd number!")
true
f303128e8b5a7d3071d49a026d95fbb8b3c3595b
ryokugyu/Algorithms
/bubble_sort/bubbleSort-Python/bubbleSort.py
419
4.21875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Oct 7 15:33:03 2018 @author: ryokugyu """ def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]>alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp alist = [54,26,93,17,77,31,44,55,20] bubbleSort(alist) print(alist)
false
3ce1a459cb6ffcbc9630c5944134b68c71c2d4ba
Manjunath823/Assessment_challenge
/Challenge_3/nested_dictionary.py
844
4.34375
4
def nested_key(object_dict, field): """ Input can be nested dict and a key, the function will return value for that key """ keys_found = [] for key, value in object_dict.items(): if key == field: keys_found.append(value) elif isinstance(value, dict): #to check whether the value is key for nested dictionary out = nested_key(value, field) for each_out in out: keys_found.append(each_out) elif isinstance(value, list): for item in value: if isinstance(item, dict): more_results = nested_key(item, field) for another_result in more_results: keys_found.append(another_result) return keys_found #Example usage nested_key(object, key)
true
41c79387bae3ed9d3a045bfc672eda6b899d7bde
PeterM358/python_OOP
/SOLID LAB/02_OCP/animal.py
1,532
4.25
4
# class Animal: # def __init__(self, species): # self.species = species # # def get_species(self): # return self.species # # # def animal_sound(animals: list): # for animal in animals: # if animal.species == 'cat': # print('meow') # elif animal.species == 'dog': # print('woof-woof') # # # animals = [Animal('cat'), Animal('dog')] # animal_sound(animals) from abc import abstractmethod, ABC class Animal(ABC): @abstractmethod def get_sound(self): pass class Cat(Animal): sound = 'meow' def get_sound(self): return self.sound class Dog(Animal): sound = 'woof-woof' def get_sound(self): return self.sound class Dragon(Animal): sound = 'roar' def get_sound(self): return self.sound class Donkey(Animal): sound = 'I am a Donkey' def get_sound(self): return self.sound def animal_sound(animals: list): for animal in animals: print(animal.get_sound()) animals = [Dog(), Cat(), Dragon(), Donkey()] animal_sound(animals) # animals = [Animal('cat'), Animal('dog')] # animal_sound(animals) ## добавете ново животно и рефакторирайте кода да работи без да се налага да се правят промени по него ## при добавяне на нови животни # animals = [Animal('cat'), Animal('dog'), Animal('chicken')]
false
1480e4f71cc8b0bc2b27f113937ba4b1cafe8cfb
saif93/simulatedAnnealingPython
/LocalSearch.py
2,948
4.125
4
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" implementation of Simulated Annealing in Python Date: Oct 22, 2016 7:31:55 PM Programmed By: Muhammad Saif ul islam """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" import math import random from copy import deepcopy from Tour import Tour from City import city class LocalSearch: temp = 10000 coolingRate = 0.003 def __init__(self): self.cities = deepcopy(city.cities) def acceptanceProbability(self,energy, newEnergy, temperature): # If the new solution is better, accept it if (newEnergy < energy): return 1.0 # // If the new solution is worse, calculate an acceptance probability return math.exp((energy - newEnergy) / temperature) def simulatedAnnealing(self): currentSolution = Tour() currentSolution.generateIndividual() print("Initial solution distance: " , currentSolution.getDistance()) print("Initil path:",currentSolution.getTour()) # // Set as current best best = deepcopy(Tour(currentSolution.getTour())) # // Loop until system has cooled while (self.temp > 1) : # // Create new neighbour tour newSolution = deepcopy(Tour(currentSolution.getTour())) # // Get a random positions in the tour random.randrange(0,19,1) tourPos1 = random.randrange(0,newSolution.tourSize(),1) tourPos2 = random.randrange(0,newSolution.tourSize(),1) # // Get the cities at selected positions in the tour citySwap1 = newSolution.getCity(tourPos1) citySwap2 = newSolution.getCity(tourPos2) # // Swap them newSolution.setCity(tourPos2, citySwap1); newSolution.setCity(tourPos1, citySwap2); # // Get energy of solutions currentEnergy = currentSolution.getDistance() neighbourEnergy = newSolution.getDistance() # // Decide if we should accept the neighbour if (self.acceptanceProbability(currentEnergy, neighbourEnergy, self.temp) >= random.randint(1,19)) : currentSolution = deepcopy(Tour(newSolution.getTour())) # // Keep track of the best solution found if (currentSolution.getDistance() < best.getDistance()) : best = deepcopy(Tour(currentSolution.getTour())) # // Cool system self.temp *= 1- self.coolingRate print("\n\nFinal solution distance: " , best.getDistance()) print("Final path: " , best.getTour()) """ Testing """ initializeCities = city() localSearch = LocalSearch() localSearch.simulatedAnnealing()
true
43b0f70793519b645bb599955d56b52a2c801c5b
BrenoSDev/PythonStart
/Introdução a Programação com Python/EX07,6.py
724
4.125
4
#Programa que lê três strings e imprime o resultado da substituição da primeira, dos caracteres da segunda pelos da terceira print('Digite três strings e nós substituiremos os caracteres da segunda pelos da terceira na primeira!') string1 = list(input('String 1: ')) string2 = ' ' string3 = '' while len(string2) != len(string3): print('As string 2 e 3 devem conter o mesmo número de letras!') string2 = list(input('String 2: ')) string3 = list(input('String 3: ')) resultado = string1[:] contador = 0 for letra in string2: while letra in resultado: posicao = resultado.index(letra) resultado[posicao] = string3[contador] contador += 1 print('Resultado: %s'%(''.join(resultado)))
false
25a8ce3074fb682a23763f3e350e20484753a9bd
BrenoSDev/PythonStart
/Treinos Py/T6.py
1,009
4.15625
4
#Validação de informações nome = input('Nome: ') while len(nome) <= 3: print('\033[31mERRO! O nome deve possuir mais de 3 caracteres!\033[m') nome = input('Nome: ') idade = input('Idade: ') while int(idade) < 0 or int(idade) > 150: print('\033[31mERRO! Digite uma idade entre 0 e 150 anos:\033[m') idade = input('Idade: ') salário = input('Salário: ') while float(salário) < 0: print('\033[31mERRO! O salário não pode ser negativo!\033[m') salário = input('Salário: ') sexo = input('Sexo(M/F): ').upper() while sexo[0] != 'M' and sexo[0] != 'F': print('\033[31mERRO! Digite apenas M ou F no sexo!\033[m') sexo = input('Sexo(M/F): ').upper() estado_civil = input('Estado civil(S/C/V/D): ').upper() while estado_civil[0] != 'S' and estado_civil[0] != 'C' and estado_civil[0] != 'V' and estado_civil[0] != 'D': print('\033[31mERRO! Digite um estado civil válido!\033[m') estado_civil = input('Estado civil(S/C/V/D): ').upper() print('Dados cadastrados com sucesso!')
false
31d9dc0b6c3e23b9c7dbee6a63139df021b69b27
SarwarSaif/Python-Problems
/Hackerank-Problems/Calendar Module.py
842
4.28125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 2 14:20:23 2018 @author: majaa """ import calendar if __name__ == '__main__': user_input = input().split() m = int(user_input[0]) d = int(user_input[1]) y = int(user_input[2]) print(list(calendar.day_name)[calendar.weekday(y, m, d)].upper()) #first calendar.weekday(y,m,d) returns the number of the day e.g: returns 6 for sunday #calendar.day_name returns the days name in an array #list(calendar.day_name) returns ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] #then we get list(calendar.day_name)[6] we get the day name in 6th index #then turn them into upper case letters by apply ".upper()" at the end #print(calendar.weekday(y, m, d)) #print(list(calendar.day_name)[calendar.weekday(y, m, d)])
true