blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
7b73a9dde0dccdaf19434419c4ce16387f099588 | hyrdbyrd/ctf-route | /public/tasks-content/code.python.py | 124 | 3.53125 | 4 | def encrypt(text):
key = len(text)
res = []
for i in text:
res.append(ord(i) + (ord(i) % key))
key += 1
return res
|
a3dd8e793dba43fdc1f0c05044e9751e46daf6ed | joanamcsp/leetcode-python | /perfect_number.py | 392 | 3.5625 | 4 | import math
class Solution:
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
divisors = [div for div in range(1,int(math.ceil(math.sqrt(num)))) if num % div == 0]
divisors.extend([num // div for div in divisors if num // div < num])
return sum(divisors) == num
|
d1a1cdab267d500a7ff27780a56f13f548a29a6b | VeraMendes/lambdata_DS8 | /lambdata_veramendes/functions.py | 462 | 3.875 | 4 | """
utility functions
"""
import pandas as pd
import numpy as np
TEST_DF = pd.DataFrame([1,2,3,4,5,6])
def five_mult(x):
"""multiplying a number by 5 function"""
return 5 * x
def tri_recursion(k):
"""recursion of a value"""
if(k>0):
result = k + tri_recursion(k-1)
# print(result)
else:
result = 0
return result
def sum_two_numbers(a,b):
"""sum two numbers"""
return a + b
|
427707409b4897dea8ae9fd913944ac23a2feb03 | russjohnson09/sentential-logic | /sentential.py | 3,123 | 4.15625 | 4 | #!/usr/bin/env python
"""
Main Methods
-----------------------------------
The following are all of the methods
needed to apply logic rules and
confirm that a Hilbert style proof is correct.
Arguments given to each method are the line
number of the statement and any line numbers
needed to check for validity.
----
"""
import sys
import re
from syntax import Grammar
def file_to_list_of_parsed(nameoffile):
"""
Takes a file and returns a list of parsed lines.
This can then be used to verify the proof.
"""
a = Grammar()
b = a.syntax()
file1 = open(nameoffile,'r')
parsed = []
for line in file1:
parsed.append(b.parseString(line))
return parsed
def pr(line_number):
return True
def ei(line_number1, line_number2):
dict1 = {}
compare1 = parsed[int(line_number1) - 1].expr[2]
compare2 = parsed[int(line_number2) - 1].expr
for i in range(len(compare1)):
try:
if not compare1[i].islower():
if not compare1[i] == compare2[i]:
return False
else:
if compare1[i] in dict1:
if not dict1[compare1[i]] == compare2[i]:
return False
else:
dict1[compare1[i]] = compare2[i]
except:
return False
return True
def simp(line1, line2):
str1 = ''.join(list(parsed[int(line2) - 1].expr))
str2 = ''.join(list(parsed[int(line1) - 1].expr))
lst1 = str2.split('*')
return str1 in lst1
def mp(line1, line2, line3):
lst1 = list(parsed[int(line3)-1].expr)
lst2 = list(parsed[int(line2)-1].expr)
str1 = ''.join(lst2) + '->' + ''.join(lst1)
str2 = ''.join(list(parsed[int(line1)-1].expr))
return str1 == str2
def eg(line1, line2):
"The inverse of ei."
return ei(line2, line1)
def conj(line1, line2, line3):
str1 = ''.join(list(parsed[int(line1)-1].expr))
str1 += '*' + ''.join(list(parsed[int(line2)-1].expr))
str2 = ''.join(list(parsed[int(line3)-1].expr))
return str1 == str2
def ui(line_number1, line_number2):
dict1 = {}
compare1 = parsed[int(line_number1) - 1].expr[1]
compare2 = parsed[int(line_number2) - 1].expr
for i in range(len(compare1)):
try:
if not compare1[i].islower():
if not compare1[i] == compare2[i]:
return False
else:
if compare1[i] in dict1:
if not dict1[compare1[i]] == compare2[i]:
return False
else:
dict1[compare1[i]] = compare2[i]
except:
return False
return True
def verify(nameoffile):
global parsed
parsed = file_to_list_of_parsed(nameoffile)
for line in parsed:
if not line.reason[0] == 'Pr':
str1 = str(line.reason[0].lower())
str1 += '(*'
args = line.reason[1:] + list(line.linenumber)
str1 += str(args)
str1 += ')'
print eval(str1)
verify('quacker2.txt')
|
b733f8bd4a9d664973423240f106c8d252cdf13b | Adi7290/Python_Projects | /chschs.py | 6,228 | 3.6875 | 4 | Python 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> for i in range(0,100):
if i%2==1:
print(i)
elif i%2 ==0:
pass
i=i+1
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> for i in range(0,100):
if i%(2,3,5,7,9)==0:
pass
elif i%(2,3,5,7,9)==1:
print(i)
i+=1
Traceback (most recent call last):
File "<pyshell#35>", line 2, in <module>
if i%(2,3,5,7,9)==0:
TypeError: unsupported operand type(s) for %: 'int' and 'tuple'
>>> for i in range(0,100):
if i%2,3,5,7==0:
SyntaxError: invalid syntax
>>> for i in range(0,100):
if i%2==0 and i%3==0 and i%5==0 and i %7==0:
pass
elif i%2==1 and i%3==1 and i%5==1 and i%7==1:
print(i)
i+=1
1
>>> for i in range(0,1000):
if i%2==0 and i%3==0 and i%5==0 and i%7==0:
print(i)
i+=1
0
210
420
630
840
>>> for i in range(0,1000):
if i % i ==0:
print(i)
elif i%i==1:
pass
i+=1
Traceback (most recent call last):
File "<pyshell#57>", line 2, in <module>
if i % i ==0:
ZeroDivisionError: integer division or modulo by zero
>>> for i in range(2,150):
if i%i ==0
SyntaxError: invalid syntax
>>> for i in range(2,150):
if i%i ==0:
print(i)
elif i%i ==1:
pass
i+=1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
>>> for i in range(2,150):
if i%i ==0:
pass
elif i%i ==1:
print(i)
i+=1
>>>
>>>
>>>
>>>
>>> for i in range(0,100):
if i%1==0 and i%i==0:
print(i)
elif i%2==0:
pass
Traceback (most recent call last):
File "<pyshell#77>", line 2, in <module>
if i%1==0 and i%i==0:
ZeroDivisionError: integer division or modulo by zero
>>>
KeyboardInterrupt
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
if i%5==0 and i%7==0:
pass
elif:
SyntaxError: invalid syntax
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
if i%5==0 and i%7==0:
pass
elif:
SyntaxError: invalid syntax
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
elif i%5==0 and i%7==0:
pass
elif:
SyntaxError: invalid syntax
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
if i%5==0 and i%7==0:
pass
else:
print(i)
i+=1
1
2
3
4
5
7
8
9
10
11
13
14
15
16
17
19
20
21
22
23
25
26
27
28
29
31
32
33
34
35
37
38
39
40
41
43
44
45
46
47
49
50
51
52
53
55
56
57
58
59
61
62
63
64
65
67
68
69
70
71
73
74
75
76
77
79
80
81
82
83
85
86
87
88
89
91
92
93
94
95
97
98
99
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
if i%5==0 and i%7==0:
pass
else i%3==1 and i%2 ==1:
if i%5==1 and i%7==1:
print(i)
i+=1
SyntaxError: invalid syntax
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
if i%5==0 and i%7==0:
pass
elif i%3==1 and i%2 ==1:
if i%5==1 and i%7==1:
print(i)
i+=1
SyntaxError: expected an indented block
>>>
>>> for i in range(0,100):
if i%3==0 and i%2 ==0:
if i%5==0 and i%7==0:
pass
elif i%3==1 and i%2 ==1:
if i%5==1 and i%7==1:
print(i)
i+=1
1
>>> for i in range(0,100):
if i//2 ==0:
pass
elif i//2==1:
print(i)
i+=1
2
3
>>>
>>>
>>> for i in range(2,101):
if i%2==0:
elif i%3==0:
SyntaxError: invalid syntax
>>> for i in range(2,101):
if i%1==True and i%i == True:
print(i)
elif i%2==True:
elif i%3==True:
SyntaxError: invalid syntax
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> for i in range(0,100):
if i%2 and 3 and 5 and 7 ==0:
print(i)
>>> if i%2 and 3 and 5 and 7==0:
print('h')
>>>
>>> a = 1
>>> b=2
>>> c=3
>>> d=4
>>> a,b,c,d
(1, 2, 3, 4)
>>> a,b,c,d==0
(1, 2, 3, False)
>>> a and b and c and d ==0
False
>>> a and b==0
False
>>> c and d ==0
False
>>> a and c ==0
False
>>> a = i%2==0
>>> b = i%3==0
>>> c = i%5==0
>>> d = i%7==0
>>> for i in range(2,101):
if a and b and c and d ==True:
pass
elif a and b and c and d ==False:
print(i)
i+=1
>>> a and b and c and d
False
>>> for i in range(2,101):
a = i%2==0
>>> b = i%3==0
>>> c = i%5==0
>>> d = i%7==0
SyntaxError: invalid syntax
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> for i in range(2,101):
if i %2 and i%3 and i%5 and i%7==0:
pass
elif i %2 and i%3 and i%5 and i%7==1:
print(i)
i+=1
29
43
71
>>> for i in range(0,100):
if i%2 or i%3 or i %5 or i%7==0:
print(i)
elif i%2 or i%3 or i%5 or i%7 ==1:
pass
i+=1
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
91
92
93
94
95
96
97
98
99
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
KeyboardInterrupt
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> |
5c5199249efa2ba277218ed47e4ae2554a0bbf7e | Adi7290/Python_Projects | /improvise_2numeric_arithmetic.py | 660 | 4.21875 | 4 | #Write a program to enter two integers and then perform all arithmetic operators on them
num1 = int(input('Enter the first number please : \t '))
num2 = int(input('Enter the second number please :\t'))
print(f'''the addittion of {num1} and {num2} will be :\t {num1+num2}\n
the subtraction of {num1} and {num2} will be :\t {num1-num2}\n
the multiplication of {num1} and {num2} will be :\t {num1*num2}\n
the division of {num1} and {num2} will be :\t {num1/num2}\n
the power of {num1} and {num2} will be :\t {num1**num2}\n
the modulus of {num1} and {num2} will be :\t {num1%num2}\n
the floor division of {num1} and {num2} will be :\t {num1//num2}\n''')
|
4cc7aabb1e5e2b48cc90c607acce1b67f9fac93d | Adi7290/Python_Projects | /Herons formula.py | 350 | 4.28125 | 4 | #Write a program to calculate the area of triangle using herons formula
a= float(input("Enter the first side :\t"))
b= float(input("Enter the second side :\t"))
c= float(input("Enter the third side :\t"))
print(f"Side1 ={a}\t,Side2 = {b}\t,Side3={c}")
s = (a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**0.5
print(f"Semi = {s}, and the area = {area}")
|
ea0b627a1ee97b93acd9087b18e36c3fa5d10b4d | Adi7290/Python_Projects | /singlequantity_grocery.py | 942 | 4.1875 | 4 | '''Write a program to prepare a grocery bill , for that enter the name of items , quantity in which it is
purchased and its price per unit the display the bill in the following format
*************BILL***************
item name item quantity item price
********************************
total amount to be paid :
*********************************'''
name = input('Enter the name of item purchased :\t')
quantity = int(input('Enter the quantity of the item :\t'))
amount = int(input('Enter the amount of the item :\t'))
item_price = quantity * amount
print('*****************BILL****************')
print(f'Item Name\t Item Quantity\t Item Price')
print(f'{name}\t\t {quantity}\t\t {item_price}')
print('************************************')
print(f'Price per unit is \t \t {amount}')
print('************************************')
print(f'Total amount :\t\t{item_price}')
print('************************************')
|
4303d8cef8cb2db91a035f228e311f265873c29c | Adi7290/Python_Projects | /sum_arithmetic.py | 210 | 3.875 | 4 | """Write a program to sum the series 1+1/2+....1/n"""
number = int(input('Enter the number :\t'))
sum1=0
for i in range(1,number+1):
a = 1.0/i
sum1=sum1+a
print(f'The sum of 1+1/2...1n is {sum1}') |
2b786c15f95d48b9e59555d2557cc497d922d948 | Adi7290/Python_Projects | /Armstrong_number.py | 534 | 4.40625 | 4 | """Write a program to find whether the given number is an Armstrong Number or not
Hint:An armstrong number of three digit is an integer such that the sum of the cubes of its digits is equal
to the number itself.For example 371 is the armstrong number since 3**3+7**3+1**3"""
num = int(input('Enter the number to check if its an Armstrong number or not :\t'))
orig = num
sm =0
while num>0:
sm = sm+(num%10)*(num%10)* (num%10)
num =num//10
if orig == sm:
print('Armstrong')
else:
print('Not Armstrong')
|
57aef9d462a85029bc3e2bd58909ee7267d5f7d1 | turamant/ToolKit | /PyQt_ToolKit/PushButton/pushbutton_1.py | 1,582 | 3.578125 | 4 | """
PushButton часто используется, чтобы заставить программу делать что-то,
когда пользователю просто нужно нажать кнопку. Этот
может начинать загрузку или удалять файл.
"""
import sys
from PyQt5.QtWidgets import QWidget, QGridLayout, QPushButton, QApplication
""" -= SIGNALS -=
Одна из общих функций кнопки - это нажатие пользователем и выполнение связанного действия.
Это делается путем подключения сигнала нажатия кнопки к соответствующей функции:
"""
class Window(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QGridLayout()
self.setLayout(layout)
button = QPushButton("Нажми сюда")
button.setToolTip("This ToolTip simply displays text.")
button.clicked.connect(self.on_button_clicked)
layout.addWidget(button, 0, 0)
button = QPushButton("выход")
button.clicked.connect(self.exit_window)
layout.addWidget(button, 0, 1)
self.show()
def on_button_clicked(self):
print("Кнопка была нажата. Я функция - СЛОТ")
def exit_window(self):
sys.exit(app.exec_())
if __name__=='__main__':
app = QApplication(sys.argv)
screen = Window()
sys.exit(app.exec_()) |
0c111ad94df47ec95d63a25d1f2f208994da4894 | Mariano92m/commonTecInfo2016 | /EjerciciosdeFunciones/EjerR-Func.py | 381 | 3.6875 | 4 | def prime (x):
prim=True
res=1
for y in range (2, x-1):
if x%y==0:
prim=False
if (prim==True):
for y in range (1, x+1):
res= res * y
print res
else:
for y in range (1, x):
if y < 1000:
if x%y==0:
print y
Seg=(raw_input("Desea ingresar otro numero? S/N ")).upper()
if Seg == "S":
x=int(input("Ingrese el numero que desea evaluar "))
prime (x) |
bbde6653d2ecfc5f88b88fdd486cb9b7f3c2f7b7 | Mariano92m/commonTecInfo2016 | /EjerciciosdeFunciones/EjerM-Func.py | 178 | 3.921875 | 4 | def rango(L1,L2,x):
if(L1<=x and x<=L2):
print("Se encuentra dentro del rango")
elif(L1>x):
print("Se encuentra a la izquierda")
else:
print("Se encuentra a la derecha") |
ce600e5d9e467ece05d83bc117e4c0b71f001c53 | Mariano92m/commonTecInfo2016 | /Ejercicios de Estructuras Secuenciales/S1.py | 166 | 3.703125 | 4 | print ("Situacion 1")
Nac = int (input("Fecha de Nacimiento:"))
Fut = int (input("Fecha a Futuro:"))
resultado = Fut - Nac
print ("Tu edad en esa Fecha:", resultado) |
bc1882e40e3063c0c24e2fcc8ad1f6e7862c6301 | Mariano92m/commonTecInfo2016 | /Examen Juegos/ElCaminoDelGigante.py | 1,857 | 3.90625 | 4 | print ("*********************************************************************")
print (" El camino del gigante designed by /commonTec: real game engineering/")
print ("*********************************************************************")
print(" ")
print(" ")
print ("Bienvenido a El camino del gigante!")
print ("El juego que todos estaban esperando")
print("") #Espacio
print(" ")
#Introduccion
print("""
Tu objetivo es que el gigante llegue a su Caverna.
Supongamos que se llama Bob.
Tienes 3 intentos lanzando el dado para sumar pasos al gigante.
\nEmpecemos...""")
print(" ")
print ("\nBob necesita dar 20 pasos para llegar a su caverna, si Bob da mas de 20 pasos cae a un precipicio")
print(" ")
#Variables
import random
pasos = random.randint(1,20)
tiradas = random.randint(1,3)
llegada = 20
print(" ")
#Pasos realizados y faltantes
print (("-El Gigante ha caminado %s pasos-")%(pasos))
restante = (20 - (pasos))
print (("\nAun le quedan %s pasos para llegar a la caverna")%(restante))
intentos = 1
#Mientras los intentos sean menores o iguales a 3
while intentos <= 3:
dado = input("Lanzar dado? s/n:\n>:")
#Si el dado se lanza...
if dado == "s":
tDado = random.randint(1,6)
print(("\nEl dado ha caido en %s")%(tDado))
pasos+=tDado
print (("\nAhora Bob ha hecho %s pasos")%(pasos))
restante-=tDado
print (("Y restan %s pasos para llegar")%(restante))
intentos += 1
#Precipicio
elif pasos > llegada:
dado == "x"
print ("\n Lo sentimos: has superado la cantidad de pasos. \nCaiste al precipicio!")
intentos = 4
#En el caso de que se gane...
if pasos == llegada:
intentos = 4
print("\nHas llevado a Bob a la caverna!\n Ganaste!")
#Si el Dado no se Lanza...
else:
break
print ("\nBob no lo ha conseguido!\n - GAME OVER - ")
|
d72c45554eb24913e774a7ce1bf716428bc089d2 | Mariano92m/commonTecInfo2016 | /Ejercicios de Estructuras Repetitivas/R1.py | 812 | 3.953125 | 4 | sIni=0;
transaccion=True
while transaccion==True:
print("----------------------0---------------------")
print("Bienvenido señor!")
print("Si desea realizar un deposito presione 1")
print("Si desea realizar un retiro presione 2")
pedido=int(input("Presione uno de los numeros y luego enter: "))
if(pedido==1):
aDep=int(input("Cuanto desea depositar? "))
sIni=sIni+aDep
elif(pedido==2):
aRet=int(input("Cuanto desea retirar? "))
if(aRet>sIni):
print("No puede retirar ese monto por que no tiene los fondos necesarios")
else:
sIni=sIni-aRet
else:
print("El numero ingresado es incorrecto");
print("Si desea continuar con la transaccion pulse 1, sino puse 2, y luego enter: ")
aux=int(input("aux= "))
if(aux==1):
transaccion=True
elif(aux==2):
transaccion=False
print(sIni) |
438bbaf5e4ab15eaeb4dc8cfa320bc2efff2c699 | Mariano92m/commonTecInfo2016 | /Ejercicios de Estructuras Condicionales/C2.py | 315 | 3.984375 | 4 | v1=int(input("Agrega un valor: "));
v2=int(input("Agrega un valor: "));
v3=int(input("Agrega un valor: "));
promedio=(v1+v2+v3)/3
if(v1>promedio):
print("%s es mayor que el promedio"%(v1));
if(v2>promedio):
print("%s es mayor que el promedio"%(v2));
if(v3>promedio):
print("%s es mayor que el promedio"%(v3));
|
9d73cbb02966e689c21fa90b5afa888b190c2456 | Mariano92m/commonTecInfo2016 | /EjerciciosdeFunciones/EjerI-Func.py | 176 | 3.65625 | 4 | def tipo(k):
sum=0
for x in range (1,k-1):
if (k%x==0):
sum=sum+x
if sum==k:
return ("perfecto")
elif sum < k:
return ("deficiente")
else:
return ("abundante")
|
5d3eaa8f3c83e461a73884e67a4eafacf24044d8 | kamyu104/GoogleCodeJam-2016 | /Round 1A/rank-and-file.py | 774 | 3.578125 | 4 | # Copyright (c) 2016 kamyu. All rights reserved.
#
# Google Code Jam 2016 Round 1A - Problem B. Rank and File
# https://code.google.com/codejam/contest/4304486/dashboard#s=p1
#
# Time: O(N^2)
# Space: O(N^2), at most N^2 numbers in the Counter
#
from collections import Counter
def rank_and_file():
N = input()
cnt = Counter()
for _ in xrange(2 * N - 1):
cnt += Counter(list(raw_input().strip().split()))
file = []
for k, v in cnt.iteritems():
# The count of the missing number must be odd.
if v % 2 == 1:
file.append(k)
# The order of the missing numbers must be sorted.
file.sort(key=int)
return " ".join(file)
for case in xrange(input()):
print 'Case #%d: %s' % (case+1, rank_and_file())
|
bfd09acba86e48a9aca78e9c2fb7ad9b5f63dd32 | Dami-Lapite/guess-the-song | /guessTheSong.py | 2,297 | 3.5 | 4 | import random
import os
import pygame
import tkinter as tk
from tkinter.filedialog import askdirectory
def prompt(count, playTime, answer):
if count == 3 :
prompt_text = input("No more music \n\nType a for answer \n\nType q for quit\n\n")
if prompt_text == "a":
print("\n..............................\n")
print("The correct answer was",answer)
print("\n..............................\n")
return True
else:
prompt_text = input("Type m for more \n\nType a for answer \n\nType q for quit\n\n")
if prompt_text == "m":
pygame.mixer.music.unpause()
while pygame.mixer.music.get_pos() < playTime:
continue
pygame.mixer.music.pause()
return False
elif prompt_text == "a":
print("\n..............................\n")
print("The correct answer was",answer)
print("\n..............................\n")
return True
else :
return True
def main():
pygame.mixer.init()
root = tk.Tk()
root.withdraw()
directory = askdirectory()
os.chdir(directory)
list_dir = os.listdir(directory)
list_dir.sort()
list_of_songs = []
for files in list_dir:
if files.endswith(".mp3"):
list_of_songs.append(files)
another_track = True
score = 0
while another_track:
try:
random_song_index = random.randint(0, len(list_of_songs)-1)
pygame.mixer.music.stop()
pygame.mixer.init()
pygame.mixer.music.load(list_of_songs[random_song_index])
pygame.mixer.music.play()
while pygame.mixer.music.get_pos() < 3000:
continue
pygame.mixer.music.pause()
done = False
count = 1
playTime = 8000
while not done:
done = prompt(count, playTime, list_of_songs[int(random_song_index)])
count += 1
playTime = 15000
another_round = input("would you like another round ? (y/n) ")
if another_round == "n":
break
except pygame.error:
continue
if __name__ == "__main__":
main()
|
023270d8f656b3949d6d95c8e3c423a2f94f66de | phuang7008/machine_learning | /Calculate_LR.py | 1,643 | 3.5 | 4 | #!/usr/bin/python
from statistics import mean
import numpy as np
import random
#xs = np.array([1,2,3,4,5,6], dtype=np.float64)
#ys = np.array([5,4,6,5,6,7], dtype=np.float64)
# here we are going to generate a random dataset for future usage
def create_dataset(num, variance, step=2, correlation=False):
val = 1
y = []
for i in range(num):
yy = val + random.randrange(-variance, variance)
y.append(yy)
if correlation and correlation=='pos':
val+=step
elif correlation and correlation == 'neg':
val-=step
x = [i for i in range(len(y))]
return np.array(x, dtype=np.float64), np.array(y, dtype=np.float64)
# calculate the line parameters
def slope_and_intercept(x, y):
m = ( (mean(x) * mean(y) - mean(x*y) ) /
(mean(x) * mean(x) - mean(x*x)) )
b = mean(y) - m * mean(x)
return m, b
# get some random data
xs, ys = create_dataset(40, 20, 2, 'pos')
print("x values are"); print(xs)
print("y values are"); print(ys)
m, b = slope_and_intercept(xs, ys)
print(m, b)
regression_line = [ m*x + b for x in xs]
# now need to calculate the R-square (coefficient of determination)
def square_error(y_orig, y_line):
return sum((y_orig - y_line)**2)
def coefficient_of_determination(y_orig, y_line):
y_mean_line = [mean(y_orig) for y in y_orig]
square_error_regression = square_error(y_orig, y_line)
square_error_y_mean = square_error(y_orig, y_mean_line)
return 1 - (square_error_regression / square_error_y_mean)
cod = coefficient_of_determination(ys, regression_line)
print("COD is %f" % cod)
|
816ca748495fb1b1f8dac3444233b19329738dcf | neuronalX/esn-lm | /esnlm/readouts/logistic.py | 5,460 | 3.515625 | 4 | """ This module defines the different nodes used to construct
hierarchical language models"""
import numpy as np
from esnlm.utils import softmax
from esnlm.optimization import newton_raphson, gradient, hessian
class LogisticRegression:
""" Class for the multivariate logistiv regression.
Parameters
----------
input_dim : an integer corresponding to the number of features in input.
output_dim : an integer corresponding to the number of classes.
Notes
-----
The model is trained by minimizing a cross-entropy function. The target
can be binary (one-hot) vectors or have continuous value. This allows to use the
LOgisticRegression node as a component of a Mixture of Experts (MoE) model.
"""
def __init__(self, input_dim, output_dim, verbose=True):
self.input_dim = input_dim
self.output_dim = output_dim
self.verbose = verbose
self.params = 3*(-1 + 2*np.random.rand(input_dim, output_dim))/np.sqrt(input_dim)
def py_given_x(self, x):
""" Returns the conditional probability of y given x
Parameters
----------
x : array of shape nb_samples*input_dim
Returns
-------
y : array of shape nb_samples*output_dim with class probability components
"""
return softmax(np.dot(x, self.params))
def log_likelihood(self, x, y):
""" Compute the log-likelihood of the data {x,y} according to the current
parameters of the model.
Parameters
----------
x : array of shape nb_samples*input_dim
y : array of shape nb_samples*output_dim with one-hot row components
Returns
-------
ll : the log-likelihood
"""
post = self.py_given_x(x)
lik = np.prod(post**y, axis=1)
return np.sum(np.log(lik+1e-7))
def sample_y_given_x(self, x):
""" Generate of sample for each row of x according to P(Y|X=x).
Parameters
----------
x : array of shape nb_samples*input_dim
Returns
-------
y : array of shape nb_samples*output_dim with one-hot row vectors
"""
post = self.py_given_x(x)
y = np.array([np.random.multinomial(1, post[i, :]) for i in range(x.shape[0])])
return y
def fit(self, x, y, method='Newton-Raphson', max_iter=20):
""" Learn the parameters of the model, i.e. self.params.
Parameters
----------
x : array of shape nb_samples*nb_features
y : array of shape nb_samples*output_dim
method : string indicating the type of optimization
- 'Newton-Raphson'
nb_iter : the maximum number of iterations
Returns
-------
params : the matrix of parameters
Examples
--------
>>> from esnlm.nodes import LogisticRegression
>>> x = np.array([[1., 0.],[0., 1]]
>>> y = np.array([[0., 1.],[1., 0]]
>>> params = LogisticRegression(2,2).fit(x, y)
"""
if type(y) == type([]):
y = np.eye(self.output_dim)[y]
def _objective_function(params):
py_given_x = softmax(np.dot(x, params.reshape(self.params.shape)))
lik = np.prod(py_given_x**y, axis=1)
return np.sum(np.log(lik+1e-7))
params = np.array(self.params)
old_value = _objective_function(params)
if method == 'Newton-Raphson':
print "... Newton-Raphson:",
for i in range(max_iter):
if self.verbose == True:
print i,
post = softmax(np.dot(x, params))
grad = gradient(x, y, post, np.ones((y.shape[0], )))
hess = hessian(x, y, post, np.ones((y.shape[0], )))
params = newton_raphson(grad, hess, params, _objective_function)
new_value = _objective_function(params)
if new_value < old_value + 1:
break
old_value = new_value
self.params = params.reshape(self.params.shape)
if self.verbose == True:
print "The End."
else:
from scipy.optimize import minimize
def obj(params):
return -_objective_function(params)
def grd(params):
post = softmax(np.dot(x, params.reshape(self.params.shape)))
return -gradient(x, y, post, np.ones((y.shape[0], ))).squeeze()
def hsn(params):
post = softmax(np.dot(x, params.reshape(self.params.shape)))
return -hessian(x, y, post, np.ones((y.shape[0], )))
params = params.reshape(params.size)
res = minimize(obj, params,jac=grd, hess=hsn, method=method,
options={'maxiter':100, 'xtol': 1e-4, 'disp': True})
params = res.x
self.params = params.reshape(self.params.shape)
return params
|
b45c2f73e4c932c428e95e963b5b50a93cc5f80a | Realdo-Justino/infosatc-lp-avaliativo-01 | /exercicio-18.py | 114 | 3.640625 | 4 | volume=float(input("Insira um valor em metros cubicos "))
litros=volume*1000
print("O valor em litros é",litros) |
d26f22245aa20f0fdfaf0bb1900fa1f5a9e759d2 | dcxufpb/unidade-1-exercicio-09-python-antonia-exe | /cupom.py | 2,611 | 3.5 | 4 | # coding: utf-8
def isEmpty(value: str) -> bool:
return (value == None) or (len(value) == value.count(" "))
class Loja:
def __init__(self, nome_loja, logradouro, numero, complemento, bairro,
municipio, estado, cep, telefone, observacao, cnpj,
inscricao_estadual):
self.nome_loja = nome_loja
self.logradouro = logradouro
self.numero = numero
self.complemento = complemento
self.bairro = bairro
self.municipio = municipio
self.estado = estado
self.cep = cep
self.telefone = telefone
self.observacao = observacao
self.cnpj = cnpj
self.inscricao_estadual = inscricao_estadual
def dados_loja(self):
if (isEmpty(self.nome_loja)):
raise Exception("O campo nome da loja é obrigatório")
if (isEmpty(self.logradouro)):
raise Exception("O campo logradouro do endereço é obrigatório")
numero = int()
try:
numero = int(self.numero)
except Exception:
numero = 0
if numero <= 0:
numero = "s/n"
if (isEmpty(self.municipio)):
raise Exception("O campo município do endereço é obrigatório")
if (isEmpty(self.estado)):
raise Exception("O campo estado do endereço é obrigatório")
if (isEmpty(self.cnpj)):
raise Exception("O campo CNPJ da loja é obrigatório")
if (isEmpty(self.inscricao_estadual)):
raise Exception(
"O campo inscrição estadual da loja é obrigatório")
linha2 = f"{self.logradouro}, {numero}"
if not isEmpty(self.complemento):
linha2 += f" {self.complemento}"
linha3 = str()
if not isEmpty(self.bairro):
linha3 += f"{self.bairro} - "
linha3 += f"{self.municipio} - {self.estado}"
linha4 = str()
if not isEmpty(self.cep):
linha4 = f"CEP:{self.cep}"
if not isEmpty(self.telefone):
if not isEmpty(linha4):
linha4 += " "
linha4 += f"Tel {self.telefone}"
if not isEmpty(linha4):
linha4 += "\n"
linha5 = str()
if not isEmpty(self.observacao):
linha5 += f"{self.observacao}"
output = f"{self.nome_loja}\n"
output += f"{linha2}\n"
output += f"{linha3}\n"
output += f"{linha4}"
output += f"{linha5}\n"
output += f"CNPJ: {self.cnpj}\n"
output += f"IE: {self.inscricao_estadual}"
return output
|
5b972c19cb57573030b07f0d87949d4647b6c3bc | jeremysen/Python_Trip_Project | /Software/filter_suitable_service.py | 2,115 | 3.5625 | 4 | # -*- coding: utf-8 -*-
'''
@Description: This file is used to generate suitable service for customer
@Author: Shanyue
@Time: 2019-10-02
'''
import pandas as pd
def add_range_air(price,air_down,air_up):
'''
Add range for air line
:param price: price in df
:param air_down: air_down
:param air_up: air_up
:return: whether in range
'''
price = int(price)
if(price<=(int)(air_up) and price>=(int)(air_down)):
return 1
else:
return 0
def get_suitable_hotel(city, mode):
'''
Get suitable hotel based on mode
:param city: city
:param mode: mode of customer
:return: hotel series
'''
hotel = pd.read_csv("dataset/hotel_data.csv")
hotel_city = hotel[(hotel["city"]==city) & (hotel["rate"] == "Excellent ")]
if(len(hotel_city) == 0):
hotel_city = hotel[(hotel["city"]==city) & (hotel["rate"] == "Very good ")]
hotel_city = hotel_city.sort_values(by="price", ascending=True).reset_index(drop=True)
if(mode=="Economy"):
return list(hotel_city.iloc[0])[2], list(hotel_city.iloc[0])[6]
else:
return list(hotel_city.iloc[60])[2], list(hotel_city.iloc[60])[6]
def get_suitable_airline(city, air_down, air_up):
'''
Get suitable airline
:param city: city
:param air_down: air_down
:param air_up: air_up
:return: airline series
'''
airline = pd.read_excel("dataset/airline_data.xlsx")
airline_city = airline[(airline["ArrivalAirport"].str.contains(city))]
airline_city = airline_city[~airline_city["Price"].isna()]
airline_city["Price"] = airline_city["Price"].astype(int)
airline_city["price_within"] = airline_city["Price"].apply(lambda x:add_range_air(x,air_down,air_up))
airline_city = airline_city[airline_city["price_within"] == 1]
airline_city = airline_city.sort_values(by="Price", ascending=True).reset_index(drop=True)
return list(airline_city.iloc[0])[5], list(airline_city.iloc[0])[10], list(airline_city.iloc[0])
if(__name__=="__main__"):
suitable_hotel, hotel_price = get_suitable_hotel("Adelaide")
|
52999cf0bd784008f72c1b7469a5833acdb40749 | gladguang/python-study | /study/笔记_python函数基础.py | 2,667 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#**************************** 函数 *************************
'''
我们知道圆的面积计算公式为:
S = πr2
当代码出现有规律的重复的时候,你就需要当心了,每次写3.14 * x * x不仅很麻烦,
而且,如果要把3.14改成3.14159265359的时候,得全部替换。
有了函数,我们就不再每次写s = 3.14 * x * x,而是写成更有意义的函数调用s = area_of_circle(x),
而函数area_of_circle本身只需要写一次,就可以多次调用。
基本上所有的高级语言都支持函数,Python也不例外。Python不但能非常灵活地定义函数,
而且本身内置了很多有用的函数,可以直接调用。'''
# abs() 求绝对值函数 max()返回最大值函数
'''
练习
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程 ax^2+bx+c=0ax
2
+bx+c=0 的两个解。
提示:
一元二次方程的求根公式为:
计算平方根可以调用math.sqrt()函数:
>>> import math
>>> math.sqrt(2)
1.4142135623730951
'''
"""
import math
def quadratic(a, b, c):
if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)):
raise TypeError('bad operand type')
d = b**2 - 4*a*c # 数字和字母相乘需要‘ * ’,和数学还是有差别的
if a == 0: # ‘ == ’在Python中是等于而‘ = ’是赋值,已踩坑
print('该方程没有意义')
elif d < 0: # 小于零后是负数式子就不成立,所以无解
print('该方程无解')
elif d == 0:
x = -b/(2*a) #
print(f'该方程的两个解为:x1=x2={x:.1f}')
else:
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)
print(f'该方程的两个解为:x1={x1:.1f} x2={x2:.1f}')
"""
# 廖雪峰py进度 https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888 2021.08.25
#************************************ 递归函数 ***************************************
"""card = '''---------------------- 信息卡 ----------------------
姓名:文逸轩 ---
年龄:12 ---
籍贯:江西 ---
出生日期:2008 ---
------------------------------------------------------'''
print(card)"""
|
836a7d1ef29a0c1bf1e530af5ffaffa8921a659b | gladguang/python-study | /study/7for_in循环.py | 1,579 | 3.640625 | 4 | # 计算1加到100之和
sum = 0 # 先初始化变量sum
for a in range(1,101): # range(1,101)取大于等于1小于101的整数 ,即循环取1到10整数
sum += a # sum += a 等价于 sum = sum + a
print(sum) # 打印和
'''
range(stop): 0~stop-1
range(start,stop): start~stop-1
range(start,stop,step): start~stop step(步长)
'''
# 求1到100之间偶数之和
sum = 0 # 先初始化变量sum
for a in range(2,101,2): # range(2,101,2)取从2开始加2一直到100的和
sum += a # sum += a 等价于 sum = sum + a
print(sum) # 打印和
# 求1到100之间奇数之和
sum = 0 # 先初始化变量sum
for a in range(1,101,2): # range(1,101,2)取从1开始加2一直到99的和
sum += a # sum += a 等价于 sum = sum + a
print(sum) # 打印和
# 有1,2,3,4四个数字,求这四个数字能生成多少个互不相同且无重复数字的三位数
i = 0
for x in range(1,5):
for y in range(1,5):
for z in range(1,5):
if (x!=y) and (y!=z) and (z!=x):
i += 1
if i%4:
print("%d%d%d" % (x, y, z), end=" | ")
else:
print("%d%d%d" % (x, y, z))
# 打印9*9乘法表
for i in range(1,10):
for j in range(1,i+1):
print('%d * %d = %d\t' %(i,j,i*j),end='')
print()
|
56518fed8c3d23112f342a9e64337de4188da23e | razerboot/DataStrcutures-and-Algorithms | /python/sort_stack.py | 252 | 3.6875 | 4 |
stack = []
def is_empty(stack):
return len(stack)==0
def last(stack):
if is_empty(stack):
return False
return stack[-1]
def pop(stack):
if is_empty(stack):
return False
return stack.pop(-1)
def sort(stack):
|
eae0408ff5aa53a85d3e80e67443aaa30823a625 | razerboot/DataStrcutures-and-Algorithms | /python/k_small_sorted_matrix.py | 1,415 | 3.640625 | 4 | # finding kth smallest element in row wise and column wise sorted matrix
# complexity of k*(m+n) where m is row length and n is column length
def adjust(matrix,x,y):
n=len(matrix)
m=len(matrix[x])
while(x<n and y<m):
minx,miny = x,y
leftx,lefty=x+1,y
rightx,righty=x,y+1
if leftx<n and lefty<len(matrix[leftx]) and matrix[leftx][lefty]<matrix[minx][miny]:
minx,miny=leftx,lefty
if righty<len(matrix[x]) and rightx<n and matrix[rightx][righty]<matrix[minx][miny]:
minx,miny = rightx,righty
if (minx,miny) == (x,y):
break
else:
matrix[x][y],matrix[minx][miny]=matrix[minx][miny],matrix[x][y]
x,y = minx,miny
def matrix_pop(matrix):
n=len(matrix)
m=len(matrix[n-1])
if n==1 and m==1:
return matrix[0].pop()
while matrix[n-1]==[]:
matrix.pop()
n=len(matrix)
last = matrix[n-1].pop()
first=matrix[0][0]
matrix[0][0]=last
adjust(matrix,0,0)
return first
def k_matrix_pop(matrix,k):
for i in xrange(k-1):
matrix_pop(matrix)
return matrix_pop(matrix)
matrix=[]
n,m = map(int,raw_input().split())
for a0 in xrange(n):
row=list(map(int,raw_input().split()))
matrix.append(row)
print k_matrix_pop(matrix,25)
print matrix
'''
# input
5 5
1 3 5 7 9
6 8 11 13 15
10 21 25 27 29
12 22 26 29 30
13 23 31 34 37
''' |
2b8d249fbfa4d7edc6b4b1c466a31768418146a5 | razerboot/DataStrcutures-and-Algorithms | /python/practice_llist_1.py | 1,097 | 3.953125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class llist:
def __init__(self):
self.head = None
def is_empty(self):
return self.head==None
def add_node(self,data):
temp = Node(data)
temp.next = self.head
self.head = temp
def detect_loop(self):
slow = self.head
fast = self.head.next
# detect loop
while(fast and fast.next):
if self==fast:
break
slow = slow.next
fast =fast.next.next
# move slow pointer from start and fast at meeting point with same speed till they meet which is the loop point
#here we are checking slow!=fast.next bcoz both fast and slow will meet one step earlier instead of m since we intialized fast at one step ahead
#of slow for not breaking the first loop at first step itself
if slow==fast:
slow = self.head
while(slow!=fast.next):
slow = slow.next
fast = fast.next
fast.next = None |
fe0de4706937c31a0bb80b395dd15aa7d19241f3 | razerboot/DataStrcutures-and-Algorithms | /python/count_sort.py | 515 | 3.65625 | 4 | def count_sort(arr):
a = arr[min(arr)]
b = arr[max(arr)]
arr1 = {}
# creating a count array
for i in range(a,b):
if arr[i]<=b and arr[i]>=a:
if arr[i] in arr1:
arr1[str(i)] += 1
else:
arr1[str(i)] = 1
return arr1
#modifying count array
def adding(arr,i):
if i==0:
return arr[0]
arr[i] = arr[i]+adding(arr,i-1)
return arr
for i in range(arr):
index = arr1[str(arr[i])]
if i!=index:
arr1
|
192ed0c3f624ef44e4be6a588c8fe8b4b7c8967e | razerboot/DataStrcutures-and-Algorithms | /python/max_heap_sort.py | 1,406 | 3.8125 | 4 | import math
def max_heapify(arr,i,N):
largest = i
left = 2*i
right = 2*i+1
if left<=N and arr[left]>arr[largest]:
largest = left
if right<=N and arr[right]>arr[largest]:
largest=right
if i!=largest:
arr[i],arr[largest]=arr[largest],arr[i]
max_heapify(arr,largest,N)
def get_height(arr):
N = len(arr)-1
return math.ceil(math.log(N+1,2))
def build_maxheap(arr,N):
i = N/2
while(i>0):
max_heapify(arr,i,N)
i -=1
def insert_to_heap(arr,key,N):
arr.append(key)
N += 1
i = N
p = N/2
while(p>=1 and arr[i]>arr[p]):
arr[i],arr[p]=arr[p],arr[i]
i /= 2
p /= 2
def extract_max(arr):
N = len(arr)-1
#use heapify
arr[1],arr[N] = arr[N],arr[1]
value = arr.pop()
max_heapify(arr,1,N-1)
return value
def find_max():
return arr[1]
def heap_sort(arr,N):
build_maxheap(arr,N)
i=N
while(i>1):
arr[1],arr[i]=arr[i],arr[1]
max_heapify(arr,1,i-1)
i -= 1
#use build_maxheap once
#use heapify
arr =[0]
n = int(raw_input())
arr1= map(int,raw_input().strip().split())
arr.extend(arr1)
print get_height(arr)
build_maxheap(arr,n)
print arr
print get_height(arr)
print extract_max(arr)
print arr
print get_height(arr)
print extract_max(arr)
print arr
print get_height(arr)
insert_to_heap(arr,200,len(arr)-1)
print arr
|
c3ef17c89a84060229e21c19f3c923f783e1d17f | razerboot/DataStrcutures-and-Algorithms | /python/bs_tree.py | 5,099 | 3.703125 | 4 | class Node():
def __init__(self,key):
self.left = None
self.right = None
self.val = key
class BST():
def __init__(self):
self.head=None
def insert(self,head,key):
if key>head.val:
if head.right==None:
head.right=Node(key)
else:
self.insert(head.right,key)
elif key<head.val:
if head.left==None:
head.left=Node(key)
else:
self.insert(head.left, key)
return
def inorder_succ(self,node):
succ = None
if node.right==None:
succ = self.inorder_succ_null(self.head,node,succ)
else:
succ = self.find_min(node.right)
return succ
def inorder_succ_null(self,head,node,succ):
if head==None:
return None
while(head!=None):
if node.val>head.val:
head = head.right
elif node.val<head.val:
succ = head
head=head.left
else:
break
return succ
def find_min(self,head):
if head is None:
return
while(head.left!=None):
head = head.left
return head
def lca(self,key1,key2,head):
if head==None:
return None
if key1<head.val and key2<head.val:
return self.lca(key1,key2,head.left)
elif key1>head.val and key2>head.val:
return self.lca(key1,key2,head.right)
else:
return head
def traverse_inorder(self,head,arr):
if head==None:
return
self.traverse_inorder(head.left,arr)
arr.append(head.val)
self.traverse_inorder(head.right,arr)
return
# checking whether a bt is a bst or not #application of dfs inorder
def check_bst(self,head,prev):
if head==None:
return True
if not self.check_bst(head.left,prev):
return False
if head.val<prev[0]:
return False
prev[0] = head.val
if not self.check_bst(head.right,prev):
return False
return True
#returning kth element using in order traversal
def return_k(self,head,k,c):
if head==None:
return None
left = self.return_k(head.left,k,c)
if left:
return left
c[0]+=1
if k==c[0]:
return head.val
right=self.return_k(head.right,k,c)
if right:
return right
#swap wrongly inserted elements
def swap(self,head,arr,prev):
if head==None:
return
if len(arr)>2:
return
self.swap(head.left,arr,prev)
if prev[0].val>head.val:
if arr==[]:
arr.append(prev[0])
arr.append(head)
else:
arr.append(head)
prev[0] = head
self.swap(head.right,arr,prev)
return
def delete(self,head,key):
if key>head.val:
head.right=self.delete(head.right, key)
elif key<head.val:
head.left = self.delete(head.left, key)
else:
if head.left==None:
temp = head.right
head=None
return temp
elif head.right==None:
temp=head.left
head=None
return temp
temp = self.inorder_succ(head)
head.val = temp.val
head.right = self.delete(head.right,temp.val)
return head
b_tree = BST()
b_tree.head=Node(14)
b_tree.insert(b_tree.head,8)
b_tree.insert(b_tree.head,21)
b_tree.insert(b_tree.head,4)
b_tree.insert(b_tree.head,11)
b_tree.insert(b_tree.head,17)
b_tree.insert(b_tree.head,25)
b_tree.insert(b_tree.head,2)
b_tree.insert(b_tree.head,6)
b_tree.insert(b_tree.head,9)
b_tree.insert(b_tree.head,13)
b_tree.insert(b_tree.head,15)
b_tree.insert(b_tree.head,19)
b_tree.insert(b_tree.head,23)
b_tree.insert(b_tree.head,1)
b_tree.insert(b_tree.head,3)
b_tree.insert(b_tree.head,5)
b_tree.insert(b_tree.head,7)
b_tree.insert(b_tree.head,10)
b_tree.insert(b_tree.head,12)
b_tree.insert(b_tree.head,16)
b_tree.insert(b_tree.head,18)
b_tree.insert(b_tree.head,20)
b_tree.insert(b_tree.head,22)
b_tree.insert(b_tree.head,24)
b_tree.insert(b_tree.head,26)
b_tree.head.left.val,b_tree.head.left.left.right.right.val = b_tree.head.left.left.right.right.val,b_tree.head.left.val
arr=[]
b_tree.traverse_inorder(b_tree.head,arr)
print arr
#print b_tree.find_min(b_tree.head).val
#b_tree.delete(b_tree.head,1)
print b_tree.check_bst(b_tree.head,[-422234245])
#print b_tree.lca(10,8,b_tree.head).val
#print b_tree.return_k(b_tree.head,21,[0])
#temp = Node(-24346321)
#arr = []
#b_tree.swap(b_tree.head,arr,[temp])
#if len(arr)==2:
# arr[0].val,arr[1].val = arr[1].val,arr[0].val
#elif len(arr)==3:
# arr[0].val, arr[2].val = arr[2].val, arr[0].val
#arr=[]
#b_tree.traverse_inorder(b_tree.head,arr)
#print arr
#print arr[0].val
#print arr[1].val
#print arr[2].val
|
9290cc0f2726d048b125d78b6b8bc83a11f97d74 | R-aryan/Basics-Data-Structures-And-Algorithms | /Arrays/Anagram_Check.py | 731 | 4.0625 | 4 | '''
Problem - Given two strings s1 and s2, check if both the strings are anagrams of each other.
An anagram of a string is another string that contains same characters,
only the order of characters can be different.
For example, “abcd” and “dabc” are anagram of each other.
'''
from collections import Counter
def check_anagram(first_string,second_string):
d1=Counter(first_string)
d2= Counter(second_string)
# print(d1)
# print(d2)
if d1==d2:
#print('Are anagrams')
return True
else:
return False
s1= (input("Enter first string \n")).lower()
s2= (input("Enter second string \n")).lower()
if check_anagram(s1,s2):
print('True')
else:
print('False') |
08a84913a2e0a9de0789aeb099a6ffc7a2b94f7a | R-aryan/Basics-Data-Structures-And-Algorithms | /stacks and Queues/dqueue.py | 862 | 3.71875 | 4 | class Dqueue(object):
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def addFront(self,num):
self.items.append(num)
print("{} Added at front successfully..!".format(num))
def addRear(self,num):
self.items.insert(0,num)
print("{} Added at rear successfully..!".format(num))
def removeFront(self):
r= self.items.pop()
print('Successfully popped from front...!!'+str(r))
def removeRear(self):
r= self.items.pop(0)
print("Successfuly removed from rear..!!"+str(r))
def size(self):
l= len(self.items)
print("Length of Deque is "+ str(l))
d=Dqueue()
d.addFront(12)
d.addRear(45)
d.addFront(89)
d.addFront(78)
d.addFront(42)
d.addRear(890)
d.size()
d.removeFront()
d.removeRear()
d.size()
|
0e9880512bebfff94a020bf37ea1adedbad5d70d | Hollow667/Python-Crash-Course | /Lastname_greet.py | 195 | 3.84375 | 4 | pretty = "*"
name = input("Enter your name: ")
school = input("What school do you go to?")
print(pretty *70)
print("\tHi, " + name + ", " + school + " is a great school")
print(pretty *70) |
85a6612754425c4b01800d97166616c6fcb296e4 | byronlara5/python_analyzing_data | /module_1/three.py | 1,490 | 4.09375 | 4 | import pandas as pd
file = '/home/byron_lara/PycharmProjects/analyzing_data/venv/module_1/cars.csv'
# Creating DataFrame with the Cars file
df = pd.read_csv(file)
# List of headers for the CSV File
headers = [
"Symboling","Normalized-losses","Make","Fuel-type","Aspiration","Num-of-doors","Body-style",
"Drive-wheels","Engine-location","Wheel-base","Length","Width","Height","Curb-weight","Engine-type",
"Num-of-cylinders","Engine-size","Fuel-system","Bore","Stroke","Compression-ratio","HP","Peak-rpm",
"City-mpg","Highway-mpg","Price"
]
# Assigning the headers
df.columns = headers
# Dropping missing values in the column Price
# axis=0 drops the entire row, axis=1 drops the entire column
df.dropna(subset=["Price"], axis=0)
# Saving the dataset (We do this in order to add the new header to the file
df.to_csv("cars_new.csv", index=False)
"""
We can also read and save to other file formats, like this:
(pd meaning: pandas, df meaning: dataframe)
Data Formate | Read | Save |
=========================================================
CSV pd.read_csv() df.to_csv()
JSON pd.read_json() df.to_json()
EXCEL pd.read_excel() df.to_excel()
HDF pd.read_hdf() df.to_hdf()
SQL pd.read_sql() df.to_sql()
=========================================================
""" |
94d50aa6f1e74abbd70d07494e2b3df47fb1bc20 | amyq7526110/python | /python1/while.py | 1,899 | 3.515625 | 4 | #!/usr/bin/env python3
import os
import readline
a=os.popen('echo 1').readline()
print(a)
os.system('ls')
# 循环概述
# • 一组被重复执行的语句称之为循环体,能否继续重复,
# 决定循环的终止条件
# • Python中的循环有while循环和for循环
# • 循环次数未知的情况下,建议采用while循环
# • 循环次数可以预知的情况下,建议采用for循环
# while循环语法结构
# • 当需要语句不断的重复执行时,可以使用while循环
# while expression:
# while_suite
# 语句while_suite会被连续不断的循环执行,直到表达
# 式的值变成0或False
a=1
while a <= 20 :
print(a,end=' ')
a += 1
#
print()
a=1
while a <= 20:
print(a,end=' ')
a += 2
# 循环语句进阶
#
# break语句
# break语句可以结束当前循环然后跳转到下条语句
# 写程序的时候,应尽量避免重复的代码,在这种情况
# 下可以使用while-break结构
name = input('username=')
while name !='tom':
name = input('username=')
while True:
name = input('username=')
if name == 'tom':
break
# continue语句
# • 当遇到continue语句时,程序会终止当前循环,并忽
# 略剩余的语句,然后回到循环的顶端
# • 如果仍然满足循环条件,循环体内语句继续执行,否
# 则退出循环
num=0
while num < 20:
num += 1
if num % 2 == 0:
continue
print(num,end=' ')
print()
# else语句
# • python中的while语句也支持else子句
# • else子句只在循环完成后执行
# • break语句也会跳过else块
sum10 = 0
i = 1
while i <= 10:
sum10 += i
i += 1
else:
print(sum10)
# 死循环
# 条件永远满足的循环叫做死循环
# 使用break可以退出死循环
# else永远不执行
|
74bd3483814ac5ccf695c5df2fe7fee7a826ee7e | amyq7526110/python | /python1/xvlist.py | 1,414 | 4 | 4 | #!/usr/bin/env python3
# 序列
# 序列类型操作符
# 序列操作符 作用
# seq[ind] 获得下标为ind的元素
# seq[ind1:ind2] 获得下标从ind1到ind2间的元素集合
# seq * expr 序列重复expr次
# seq1 + seq2 连接序列seq1和seq2
# obj in seq 判断obj元素是否包含在seq中
# obj not in seq 判断obj元素是否不包含在seq中
# 内建函数
# 函 数 含 义
# list(iter) 把可迭代对象转换为列表
# str(obj) 把obj对象转换成字符串
# tuple(iter) 把一个可迭代对象转换成一个元组对象
print(list('abc'))
print(list(range(10)))
print(list([1,2,3]))
# print(list(132)) # 报错
print(str(100))
print(str(True))
print(tuple(range(10)))
print(tuple('abc'))
# 内建函数(续1)
# len(seq):返回seq的长度
# max(iter,key=None):返回iter中的最大值
# enumerate:接受一个可迭代对象作为参数,返回一
# 个enumerate对象
print(enumerate('abc'))
# 内建函数(续2)
# reversed(seq):接受一个序列作为参数,返回一个以
# 逆序访问的迭代器
# sorted(iter):接受一个可迭代对象作为参数,返回
# 一个有序的列表
print(reversed([1,2,3]))
for i in reversed([1,2,3]):
print(i,end='')
print()
print(sorted('abecd'))
print(sorted([1,4,3,7,6,8]))
print(sorted((1,10,8,5,9)))
|
163314ac51a6e2c90fddc5a9da703cd00391aa27 | amyq7526110/python | /python6/zb4.py | 1,094 | 3.53125 | 4 | #!/usr/bin/env python3
import os
import time
start = time.time()
print('Start...')
pid = os.fork()
if pid:
print('in parent..')
print(os.waitpid(-1,1)) # 挂起
time.sleep(20)
else:
print('in child')
time.sleep(10)
end = time.time()
print(end - start)
# 使用轮询解决zombie问题
# • 父进程通过os.wait()来得到子进程是否终止的信息
# • 在子进程终止和父进程调用wait()之间的这段时间,
# 子进程被称为zombie(僵尸)进程
# • 如果子进程还没有终止,父进程先退出了,那么子进
# 程会持续工作。系统自动将子进程的父进程设置为
# init进程,init将来负责清理僵尸进程使用轮询解决zombie问题(续1)
# • python可以使用waitpid()来处理子进程
# • waitpid()接受两个参数,第一个参数设置为-1,表示
# 与wait()函数相同;第二参数如果设置为0表示挂起父
# 进程,直到子程序退出,设置为1表示不挂起父进程
# • waitpid()的返回值:如果子进程尚未结束则返回0,
# 否则返回子进程的PID
|
0e206114f148e603d7e0a233aa46fa3e6bfca7d0 | amyq7526110/python | /python1/else.py | 266 | 3.765625 | 4 | #!/usr/bin/env python3
# else语句
# • python中的while语句也支持else子句
# • else子句只在循环完成后执行
# • break语句也会跳过else块
sum10 = 0
i = 1
while i <= 10:
sum10 += i
i += 1
else:
print(sum10)
|
6c135e2c9a64ba6083c31ea591caaf1974ba6a0b | amyq7526110/python | /python4/toy.factory4.py | 2,322 | 3.5625 | 4 | #!/usr/bin/env python3
# 构造器方法
# • 当实例化类的对象是,构造器方法默认自动调用
# • 实例本身作为第一个参数,传递给self
class BearToy:
def __init__(self,name,size,color):
"实例化自动调用"
self.name = name # 绑定属性到self 上整个类可以引用
self.size = size
self.color = color
# 创建子类(续1)
#• 创建子类只需要在圆括号中写明从哪个父类继承即可
# 继承
# • 继承描述了基类的属性如何“遗传”给派生类
# • 子类可以继承它的基类的任何属性,不管是数据属性
# 还是方法
class NewBear(BearToy): #
"父子类有同名方法,子类对象继承子类方法"
def __init__(self,name,size,color,date):
super(NewBear, self).__init__(name,size,color)
self.date = date
def run(self):
print('我能爬!')
# 创建子类
# • 当类之间有显著的不同,并且较小的类是较大的类所
# 需要的组件时组合表现得很好;但当设计“相同的类
# 但有一些不同的功能”时,派生就是一个更加合理的
# 选择了
# • OOP 的更强大方面之一是能够使用一个已经定义好
# 的类,扩展它或者对其进行修改,而不会影响系统中
# 使用现存类的其它代码片段
# • OOD(面向对象设计)允许类特征在子孙类或子类中进行继承
# 其他绑定方法
# • 类中定义的方法需要绑定在具体的实例,由实例调用
# • 实例方法需要明确调用
def sing(self):
print('I am %s, lalala' % self.name)
if __name__ == '__main__':
big = NewBear('雄大','Large','Brown','2018-10') # 将会调用__init__ 方法,big传递给self
big.run()
print(big.date)
print(big.name)
# 组合应用
# • 两个类明显不同
# • 一个类是另一个类的组件
# 知
# 识
# 讲
# 解
# classManufacture:
# def__init__(self, phone, email):
# self.phone= phone2numeric(
# self.email= email
#
# classBearToy:
# def__init__(self, size, color, phone, email):
# self.size= sizeCentralDir
# self.color= color_content(
# self.vendor= Manufacture(phone, email)
|
b4590355111ceb038ccf9732c54cf66e4e83fee8 | amyq7526110/python | /python4/jingtff.py | 451 | 4.03125 | 4 | #!/usr/bin/env python3
class Date:
def __init__(self,year,month,date):
self.year = year
self.month = month
self.date = date
@staticmethod
def is_date_valid(string_date):
year,month,date = map(int,string_date.split('-'))
return 1 <= date <=21 and 1 <= month <= 12 and year <= 3999
if __name__ == '__main__':
print(Date.is_date_valid('2018-05-04'))
print(Date.is_date_valid('2018-22-04'))
|
1ddc769f2b667a16f412974597748cf09b7c1832 | amyq7526110/python | /python1/fibs.py | 302 | 3.75 | 4 | #!/usr/bin/env python3
def fib(x):
fibo = [0,1 ]
for i in range(x-2):
fibo.append(fibo[-1]+fibo[-2])
print(fibo)
#fibs(10)
#febo(6)
#febo(10)
print(__name__) # 保存模块名
# 当模块直接执行是__name__的值为__name__
#
if __name__ == '__mian__':
fib(10)
|
34a8045d00851db70682202a13250056e1c691f6 | MoonRaccoon/CS101 | /while_loops.py | 95 | 3.625 | 4 | def print_numbers(a):
while(x != a):
x = 0
x = x + 1
print x
|
5ae1dd1fb039661776c36210caee4d8a191ef53d | MoonRaccoon/CS101 | /range.py | 586 | 3.71875 | 4 | def bigger(a, b):
if a > b:
return a
else:
return b
def smaller(a, b):
if a < b:
return a
else:
return b
def biggest(a, b, c):
return bigger(a, bigger(b, c))
def smallest(a, b, c):
if biggest(a, b, c) == a:
med = smaller(b, c)
return med
if biggest(a, b, c) == b:
med = smaller(a,c)
return med
if biggest(a, b, c) == c:
med = smaller(a,b)
return med
def set_range(a, b, c):
maximum = biggest(a, b, c)
minimum = smallest(a, b ,c)
return maximum - minimum
|
4e406529eac6ea82a9ea111bd67afcbe5ca2bd69 | Viniuau/meus-scripts | /math.py | 900 | 4.09375 | 4 | print("Digita um número ae meu consagrado")
x = int(input("Número 1 é esse: "))
y = int(input("Número 2 é esse: "))
print("Prontinho, agora escolhe o que tu quer fazer com eles")
print("1 - Somar")
print("2 - Subtração")
print("3 - Multiplicação")
print("4 - Divisão")
escolha = int(input("Seu comando: "))
while(escolha > 0):
if (escolha == 1):
print("A soma dá", x+y, "meu amiguinho")
escolha = 0
elif (escolha == 2):
print("A subtração dá", x-y, "meu amiguinho")
escolha = 0
elif(escolha == 3):
print("A multiplicação dá", x*y, "meu amiguinho")
escolha = 0
elif(escolha == 4):
print("A divisão dá", x/y, "meu amiguinho")
escolha = 0
else:
print("opora tu digitou o número errado")
break
else:
print("Valeu por usar meu script para suas fórmulas matemágicas kek flw flw")
|
503700558831bf7513fc8987bb669f0e17d144c0 | deepika7007/bootcamp_day2 | /Day 2 .py | 1,301 | 4.1875 | 4 | #Day 2 string practice
# print a value
print("30 days 30 hour challenge")
print('30 days Bootcamp')
#Assigning string to Variable
Hours="Thirty"
print(Hours)
#Indexing using String
Days="Thirty days"
print(Days[0])
print(Days[3])
#Print particular character from certin text
Challenge="I will win"
print(challenge[7:10])
#print the length of the character
Challenge="I will win"
print(len(Challenge))
#convert String into lower character
Challenge="I Will win"
print(Challenge.lower())
#String concatenation - joining two strings
A="30 days"
B="30 hours"
C = A+B
print(C)
#Adding space during Concatenation
A="30days"
B="30hours"
C=A+" "+B
print(C)
#Casefold() - Usage
text="Thirty Days and Thirty Hours"
x=text.casefold()
print(x)
#capitalize() usage
text="Thirty Days and Thirty Hours"
x=text.capitalize()
print(x)
#find()
text="Thirty Days and Thirty Hours"
x=text.find()
print(x)
#isalpha()
text="Thirty Days and Thirty Hours"
x=text.isalpha()
print(x)
#isalnum()
text="Thirty Days and Thirty Hours"
x=text.isalnum()
print(x)
Result:
30 days 30 hour challenge
30 days Bootcamp
Thirty
T
r
win
10
i will win
30 days30 hours
30days 30hours
thirty days and thirty hours
Thirty days and thirty hours
-1
False
False
** Process exited - Return Code: 0 **
Press Enter to exit terminal
|
5571025882b22c9211572e657dd38b1a9ecdfa74 | martinkozon/Martin_Kozon-Year-12-Computer-Science | /Python/extra_sum_of_two.py | 342 | 4.1875 | 4 | #Program which will add two numbers together
#User has to input two numbers - number1 and number2
number1 = int(input("Number a: "))
number2 = int(input("Number b: "))
#add numbers number1 and number2 together and print it out
print(number1 + number2)
#TEST DATA
#Input 1, 17 -> output 18
#Input 2, 5 -> output 7
#Input 66, 33 -> output 99 |
fa98a79e66cd7e8575c857dabad5877c3b78cd87 | martinkozon/Martin_Kozon-Year-12-Computer-Science | /Python/06_input-validation.py | 816 | 4.25 | 4 | #User has to input a number between 1 and 10
#eg. if user inputs 3, the result will be as follows: 3 -> 3*1=3, 3*2=6, 3*3=9
#ask a user to input a number
number = int(input("Input number between 1 and 10: "))
#if the input number is 99 than exit the program
if number == 99:
exit()
# end if
#if the number isn't the one we want, the user will have to submit it again
while number < 1 or number > 10:
print("Number needs to be BETWEEN 1 and 10")
number = int(input("Input number between 1 and 10: "))
# end while
#times table running in a for loop with a range of 12
for count in range(12):
table = (count+1) * number #multiply count by the inputted number
print(str(count + 1) + " * " + str(number) + " = " + str(table)) #print out a result
# end for
# 27.9.19 EDIT - updated variable naming |
1165adb6c5f681f38ee8fc21eda598f9ace811fe | martinkozon/Martin_Kozon-Year-12-Computer-Science | /Python/Python Prep and Worksheet practice/CarPark.py | 812 | 3.96875 | 4 | carPark = [
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
]
#always ask the user for input
while True:
row = int(input("Row location (1 to 10): ")) - 1 # -1 because arrays start from 0
position = int(input("Position (1 to 6): ")) - 1
#user input validation, if it's incorrect that user has to submit again
if (row > -1) and (row < 11) and (position > -1) and (position < 7):
#if there's a car parked already, user will have to submit again
if carPark[row][position] == 1:
print("You can't park there...")
else:
carPark[row][position] = 1
print("You've parked in a row " + str(row + 1))
print(carPark[row])
else:
print("Submit again...") |
726a2e884e1ea29daf0c322c6c9d7051e0735a1a | martinkozon/Martin_Kozon-Year-12-Computer-Science | /Python/pass_by_reference_or_value.py | 204 | 3.578125 | 4 | def proc1(x, y):
x = x - 2
y = 0
print(x, y) #result is 6,0
#end procedure
#main program
m = 8
n = 10
proc1(m ,n)
print(m, n) #result is 8,10
#by val: x - immutable
#by ref: y - mutable
|
5453ba2f4a55d71966633f1e2236982b4177e7ae | MyHealthyHair/Week7 | /guests.py | 114 | 3.71875 | 4 | name = input("enter your name: ")
filename = 'guest.txt'
with open(filename, 'w') as f:
f.write(name)
|
a0a908c5a23b2a5f2c73753fb526d3c006076b7a | RF0606/CISC327_PROJECT | /qa327/app.py | 13,484 | 3.640625 | 4 | import csv
import time
import re
status = False
user_name = ''
user_email = ''
user_password = ''
balance = -1
accFile = open('accounts.csv', 'r+')
ticketFile = open('tickets.csv', 'r+')
accReader = csv.reader(accFile)
ticketReader = csv.reader(ticketFile)
location_arg = open('frontend_locations.txt', 'r').readline()
tranFile = open(location_arg+'_transactions.csv', 'a+', newline='')
tranWriter = csv.writer(tranFile)
def main():
print('Welcome the Queens ticket trade machine')
R1()
def R1():
if status:
print('your balance:', balance) # print out the user's balance
input1 = input('type your choice:\nsell buy update logout\n')
if input1 == 'sell': # user wants to go to sell session
R4()
elif input1 == 'buy': # user wants to go to buy session
R5()
elif input1 == 'update': # user wants to go to update session
R6()
elif input1 == 'logout': # user wants to go to logout session
R7()
else: # user enters other invalid commands
print('invalid command')
R1()
if not status:
input1 = input('type your choice:\nregister login exit\n')
if input1 == 'register': # user wants to go to register session
R2()
elif input1 == 'login': # user wants to go to login session
R3()
elif input1 == 'exit': # user wants to go to exit session
R8()
else: # user enters other invalid commands
print('invalid command')
R1()
def R2():
# R2 will be the register session, which will allow user to register their account
print('register session started successfully')
try: # if inputs are missing, call R2 again
register_email, register_name, register_password, register_password2 = input('please enter your email, user '
'name, password and confirm your '
'password:\n').split(',')
except:
#optin to exit
print('please retype\nthe number of inputs should be 4 or exit')
exitOrNot = input('do you want to exit register session(type exit to leave):')
if exitOrNot == 'exit':
R1()
R2()
# do the testing for user inputs, and outputs warning if there is any error. finally, go back to R1
if not (check_register_email(register_email) and check_exits_email(register_email) and check_register_name(
register_name) and check_register_password(register_password) and check_register_password2(
register_password, register_password2)):
R1()
tranWriter.writerow(['registration', register_name, register_email, register_password,
3000]) # write registration information into file
tranFile.flush()
print('account registered')
R1()
def R3():
print('login session started successfully')
try: # if inputs are missing, call R3 again
login_email, login_password = input('please type your email and password:\n').split(',')
except:
print('please retype\nthe number of inputs should be 2')
R1()
if not (check_register_email(login_email) and check_register_password(login_password)):
R1() # check the format of inputs. return R1 if there is anything invalid
for i in accReader: # go over every user info to check login
if not i:
continue
if login_email == i[0] and login_password == i[2]:
global status, user_name, user_email, user_password, balance
# set global value to be the user info if login succeeded
user_name = i[1]
user_email = i[0]
user_password = i[2]
balance = i[3]
status = True
print('account logged in')
R1()
# return R1 if failed
print('login failed')
R1()
def R4():
print('selling session started successfully')
try: # if inputs are missing, call R4 again
ticket_name, price, quantity, date = input('please type ticket name, price, quantity, date:\n').split(',')
except:
print('please retype\nthe number of inputs should be 4')
R1()
if not (check_ticket_name(ticket_name) and check_price(price) and check_quantity_sell(quantity) and check_date(
date)):
R1() # check the format of inputs. return R1 if there is anything invalid
price = eval(price)
price = round(price, 2)
# write the transaction
tranWriter.writerow(['selling', user_email, ticket_name, price, quantity])
tranFile.flush()
print('selling transaction was created successfully')
R1()
def R5():
print('buying session started successfully')
try: # if inputs are missing, call R5 again
ticket_name, quantity = input('please type ticket name, quantity:\n').split(',')
except:
print('please retype\nthe number of inputs should be 2')
R1()
if not (check_ticket_name(ticket_name)):
R1() # check the format of inputs. return R1 if there is anything invalid
count = 0
for i in ticketReader: # go over every ticket to check if exists
if not i:
continue
if ticket_name == i[0]:
price = i[1]
aval_quantity = i[2]
count += 1
if count == 0:
print('the ticket does not exist')
R1()
if not (check_quantity_buy(price, quantity, aval_quantity)):
R1() # check the format of inputs. return R1 if there is anything invalid
price = eval(price)
price = round(price, 2)
# write the transaction
tranWriter.writerow(['buying', user_email, ticket_name, price, quantity])
tranFile.flush()
print('buying transaction was created successfully')
R1()
def R6():
print('updating session started successfully')
try: # if inputs are missing, call R6 again
ticket_name, price, quantity, date = input('please type ticket name, price, quantity, date:\n').split(',')
except:
print('please retype\nthe number of inputs should be 4')
R1()
if not (check_ticket_name(ticket_name) and check_price(price) and check_quantity_sell(quantity) and check_date(
date)):
R1() # check the format of inputs. return R1 if there is anything invalid
count = 0
for i in ticketReader: # go over every ticket to check if exists
if not i:
continue
if ticket_name == i[0] and user_email == i[3]:
count += 1
if count == 0:
print('the ticket does not exist')
R1()
price = eval(price)
price = round(price, 2)
# write the transaction
tranWriter.writerow(['updating', user_email, ticket_name, price, quantity])
tranFile.flush()
print('updating transaction was created successfully')
R1()
def R7():
global status, user_name, user_email, user_password, balance
if status: # user already logged in
print("logout successfully")
user_name = ''
user_email = ''
user_password = ''
balance = -1
status = False
else: # user has not logged in
print("you are not login\nplease enter login")
def R8():
print('exit')
# close three resource files
accFile.close()
ticketFile.close()
tranFile.close()
exit(0)
'''
this function will check the ticket name format
'''
def check_ticket_name(ticket_name):
if not (ticket_name.replace(' ','').isalnum()):
print('transaction was created unsuccessfully\nplease retype\nticket name should be '
'alphanumeric-only')
return False
if ticket_name[0].isspace() or ticket_name[len(ticket_name) - 1].isspace():
print('transaction was created unsuccessfully\nplease retype\nspace allowed only if it is not the '
'first or the last character')
return False
elif len(ticket_name) > 60:
print('transaction was created unsuccessfully\nplease retype\nthe ticket name should be no longer '
'than 60 characters')
return False
return True
'''
this function will check the price valid
'''
def check_price(price):
if not (price.isdigit()):
print('transaction was created unsuccessfully\nplease retype\nthe ticket price should be numeric')
return False
price = eval(price)
if not (10 <= price <= 100):
print('transaction was created unsuccessfully\nplease retype\nthe ticket price should be of range ['
'10, 100]')
return False
return True
'''
this function will check the quantity valid when selling
'''
def check_quantity_sell(quantity):
quantity = eval(quantity)
if not (isinstance(quantity, int)):
print('transaction was created unsuccessfully\nplease retype\nthe ticket quantity should be an '
'integer')
return False
if not (0 < quantity <= 100):
print('transaction was created unsuccessfully\nplease retype\nthe quantity of the tickets has to be '
'more than 0, and less than or equal to 100')
return False
return True
'''
this function will check date format
'''
def check_date(date):
try:
time.strptime(date, "%Y%m%d")
return True
except:
print('transaction was created unsuccessfully\nplease retype\ndate must be given in the format '
'YYYYMMDD')
return False
'''
this function will check the quantity valid when buying
'''
def check_quantity_buy(price, quantity, aval_quantity):
price = eval(price)
quantity = eval(quantity)
aval_quantity = eval(aval_quantity)
if not (isinstance(quantity, int)):
print('transaction was created unsuccessfully\nplease retype\nthe ticket quantity should be an '
'integer')
return False
if not (0 < quantity <= aval_quantity):
print('transaction was created unsuccessfully\nplease retype\nthe quantity of the tickets has to be '
'more than 0, and less than or equal to the available quantity')
return False
elif not (float(balance) >= price * quantity * 1.35 * 1.05):
print('transaction was created unsuccessfully\nplease retype\nyour balance is insufficient')
return False
return True
'''
this function will take an string of user email as input, and True or False as output
it will check if the format of email is correct
'''
def check_register_email(register_email):
# if the format of input email is not as follows, return false
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", register_email) is None:
print("email format is incorrect\n")
return False
return True
'''
this function will take an string of user email as input, and True or False as output
it will check if the email is already exits
'''
def check_exits_email(register_email):
accReader = csv.reader(open('accounts.csv', 'r')) # read the file
# if input email already exits, return False
for i in accReader:
if not i:
continue
elif register_email == i[0]:
print("account exits\n")
return False
return True
'''
this function will take an string of user name as input, and True or False as output
it will check if the format of user name is correct
'''
def check_register_name(register_name):
# name can only be alphanumerical
if not (register_name.isalnum() or ' ' in register_name):
print('user name format is incorrect (User name should be alphanumeric-only)\n')
return False
# space allowed only if it's not the first and last character
if (register_name[0] == ' ' or register_name[len(register_name) - 1] == ' '):
print('user name format is incorrect (Space allowed only if it is not the first or the last character)\n')
return False
# length of name should be longer than 2 and shorter than 20
elif len(register_name) >= 20 or len(register_name) <= 2 :
print('user name format is incorrect (User name should be longer than 2 and shorter that 20 characters)\n')
return False
return True
'''
this function will take an string of user password as input, and True or False as output
it will check if the format of user password is correct
'''
def check_register_password(register_password):
# if the format of input password is not as follows, return false
# at least one upper and one lower case with special characters, minimum 6 in length
#pattern = r'^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)^.{6,}$'
pattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*[-+_!@#$%^&*., ?])^.{6,}$'
# Compile the ReGex
res = re.compile(pattern)
if re.search(res, register_password):
return True
print('password format is incorrect\n')
return False
'''
this function will take two string of user password as input, and True or False as output
it will check if two input are the same
'''
def check_register_password2(register_password, register_password2):
if register_password == register_password2:
return True
print("two password doesn't match, please confirm your password\n")
return False
if __name__ == "__main__":
main()
|
f51967bcf553fce95358287bbbec086d9551f58f | KUMAWAT55/Monk-Code | /Hackerrank/Python/Integer-comes-in-all-sizes.py | 270 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(raw_input())
b=int(raw_input())
c=int(raw_input())
d=int(raw_input())
if 1<=a<=1000:
if 1<=b<=1000:
if 1<=c<=1000:
if 1<=d<=1000:
print pow(a,b)+pow(c,d)
|
d6e2926f246dc78f660d0f156d763e4a4202aa3d | KUMAWAT55/Monk-Code | /Hackerrank/Python/Loops.py | 200 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
#input converting to integer
n=int(raw_input())
if 1<=n<=20:
i=0
while i<n:
print i*i
i=i+1
|
4f2cac94170db764aa3dacd2ca2dc11671fc0c7d | KUMAWAT55/Monk-Code | /Hackerrank/Algorithms/A_Very_Big_Sum.py | 167 | 3.515625 | 4 | #----------> PYTHON 3 <----------
import sys
sum=0
n = int(input().strip())
arr = input().strip().split(' ')
for i in range(0,n):
sum=sum+int(arr[i])
print (sum)
|
e0c5f15e87b35d74bd3256cc70124ecb3cca737d | KUMAWAT55/Monk-Code | /HackerEarth/Basic-Programming/Palindromic String.py | 148 | 3.609375 | 4 | n=raw_input()
if 1<=len(n)<=100:
c=''.join(reversed(n))
if n==c:
print "YES"
else:
print "NO"
|
ec26668740975b3d929b8114eaa5bd9845582967 | JohntyR/Day18_Turtle | /newmain.py | 557 | 3.71875 | 4 | import turtle as t
from shape import Shape
from random import randint
screen = t.Screen()
timmy = t.Turtle()
screen.colormode(255)
timmy.shape("turtle")
timmy.color("dark magenta")
timmy.pensize(10)
timmy.speed("fastest")
timmy.penup()
def gen_random_colour():
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
return (r, g, b)
for i in range(10):
timmy.setposition(-300, 300 - (i * 45))
for j in range(10):
timmy.color(gen_random_colour())
timmy.dot()
timmy.forward(45)
screen.exitonclick() |
15e022eb2fbc2d17ee9dd7787a5c301d43dbb89a | GitLeeRepo/PythonNotes | /basics/sort_ex1.py | 777 | 4.59375 | 5 | #!/usr/bin/python3
# Examples of using the sorted() function
# example function to be used as key by sorted function
def sortbylen(x):
return len(x)
# List to sort, first alphabetically, then by length
a = [ 'ccc', 'aaaa', 'd', 'bb']
# Orig list
print(a)
# Sorted ascending alphabetic
print(sorted(a))
# sorted decending alphabetc
print(sorted(a, reverse=True))
# use the len() function to sort by length
print(sorted(a, key=len))
# use my own custom sort key function
print(sorted(a, key=sortbylen))
# use my custom sort key function reversed
print(sorted(a, key=sortbylen, reverse=True))
# Orig list still unchanged
print(a)
# but the sort() method will change the underlying list
# unlike the sorted function call which creates a new one
a.sort()
print(a)
|
8da7f3ba63ae287850cb95fdaf6991da36855947 | GitLeeRepo/PythonNotes | /basics/python_sandbox01.py | 1,833 | 4.1875 | 4 | #!/usr/bin/python3
# Just a sandbox app to explore different Python features and techniques for learning purposes
import sys
def hello(showPrompt=True):
s = "Hello World!"
print (s)
#using slice syntax below
print (s[:5]) #Hello
print (s[6:-1]) #World
print (s[1:8]) #ello wo
print (s[1:-4]) #ello wo - same result indexing from right
if len(sys.argv) > 1:
print ("Command line args: " + str(sys.argv[1:])) #print the command line args if they exists
if showPrompt:
name = input ("Name?")
print ("Hello " + name)
print ("Hello", name) #both valid, 2nd adds its own space
else:
print ("Input not selected (pass True on hello() method call to display input prompt)")
def listDemos():
list1 = [1, 2, 3]
print(list1)
list2 = [4, 5, 6]
list3 = list1 + list2 #adds list2 to the end of list1
print(list3)
list4 = list2 + list1 #adds list1 to the end of list2
print(list4)
print("List pointer:")
list1Pointer = list1 #they point to same location
list1[0] = "1b"
print(list1)
print(list1Pointer)
print("List copy")
list1Copy = list1[:] #makes a copy, two different lists
list1[0] = 1
print(list1)
print(list1Copy)
def menuChoices():
print ("Choose:")
print ("1 - call hello (demo strings and argv command lines)")
print ("2 - list demo")
print ("d - display menu choices")
print ("x - exit program")
def main():
menuChoices()
select = input("Selection: ")
while select != "x":
if select == "1":
hello(False) #hello() without arg will use the default specified in parameter def
elif select == "2":
listDemos()
elif select == "d":
menuChoices()
select = input("Selection: ")
main()
|
867fcd25f4325f61306ee3c2540981fa3d8653d2 | GitLeeRepo/PythonNotes | /basics/tuples_ex1.py | 280 | 3.796875 | 4 | #!/usr/bin/python3
person = ( 'Bill', 'Jones', '(999)999-9999' )
single = ( 'justone', ) # note the trailing comma
# assign to individual variables
first_name, last_name, phone = person
print(person)
print(first_name, last_name, phone)
print(single) # tuple with one element
|
1ab70f1a5c8b75a9a72c42b72a9e5121fe6d8f0b | gatinueta/FranksRepo | /python/chess.py | 358 | 3.703125 | 4 | class Board:
def __init__(self):
self.b = [ [None] * 8 for i in range(8) ]
def set(self, c, piece):
self.b[c.col][c.row] = piece
def __str__(self):
s = ''
for col in self.b:
for row in col:
s += str(self.b[col][row])
s += "\n"
return s
b = Board()
print(str(b))
|
6e6841ad28295804712aa997f1486ecdf2f0db4e | gatinueta/FranksRepo | /python/bodyguards.py | 342 | 3.53125 | 4 | import fileinput
import re
for line in fileinput.input():
line = '.' + line + '.'
ms = re.finditer('[A-Z]{3}[a-z][A-Z]{3}', line)
for m in ms:
# print(m.group())
print(line[m.start()-1:m.end()+1])
if not line[m.start()-1].isupper() and not line[m.end()].isupper():
print(' : ', m.group())
|
ae0ea94137c2b1c80943742de3edcee0685099b9 | PoroTomato99/Python_Crash_Course | /palindrome.py | 249 | 3.78125 | 4 | message = "abc123"
a = ""
reversed_a = ""
for c in message:
print(f"this is => {c}")
a = a + c
print(f"this is a => {a}")
reversed_a = c + reversed_a
print(f"this is reversed_a => {reversed_a}")
print(a)
print(reversed_a)
|
fcda0d855c24a95ba0b1c667a5d40b536742eafd | xueyinjun/Learn-Python-The-Hard-Way | /ex31.py | 1,030 | 3.859375 | 4 | #encoding =utf-8
print ("You enter a dark room with two doors. Do you go through door #1 or door #2")
door = input(">")
if door == "1":
print("There's a agin bear here eating a cheese cake.What do you do")
print("1. Take the cake")
print("2.Scream at the beat")
bear = input(">")
if bear=="1":
print("The bear eats your face off. Good job!")
elif bear =="2":
print("The bear eats your legs off. Good job!")
else:
print("Well doing %s id probably better. Bear runs away" %(bear))
elif door =="2":
print("You stare into the endless abyss at Cthuhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacker clothespins")
print("3.Understanding revolvers yelling melodies")
insanity =input(">")
if insanity =="1 " or insanity =="2":
print("Your body survives powered by a mind of jello.Good job!")
else:
print("The insanity rots your eyes into a pool of muck Good job!")
else:
print("You stumble around and fall on a knife and die. Good job!")
|
40d301b151cbc2b146c2e880539c8aa38e70a3ab | ecastillob/project-euler | /001 - 050/46.py | 1,251 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
"""
# In[2]:
def es_primo_simple(N):
es = True
extremo = (N // 2)+1
for i in range(3, extremo, 2):
if N % i == 0:
es = False
break
return es
# In[3]:
N = 10000
primos = (2,) + tuple(i for i in range(3, N+1, 2) if es_primo_simple(i))
s = set(primos)
len(primos), primos[:10]
# In[4]:
contador = 0
resultado = -1
for i in range(3, N, 2):
if i in s:
continue
es = False
print(i, end="\t")
valor = 0
for p in primos:
for b in range(1, p):
valor = p + 2*(b**2)
if valor >= i:
break
if valor == i:
es = True
contador += 1
#print(i, "\t", f"{p} + 2x({b}**2)")
break
if not es:
print("\n----")
resultado = i
break
resultado # 5777
|
0ffe4f4ec06484dd0cfeecee9158c693c5ce24ce | ecastillob/project-euler | /101 - 150/104.py | 1,159 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Problem [104](https://projecteuler.net/problem=104): Pandigital Fibonacci ends
# The Fibonacci sequence is defined by the recurrence relation:
#
# $$ F_n = F_{n−1} + F_{n−2}, \mathrm{where} \ F_1 = 1 \ \mathrm{and} \ F_2 = 1. $$
#
# It turns out that $F_{541}$, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And $F_{2749}$, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital.
#
# Given that $F_k$ is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find $k$.
# In[1]:
s = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}
s
# In[ ]:
%%time
a = 0
b = 1
k = 1
inicio, final = "", ""
while not (s.issubset(inicio) and s.issubset(final)):
print(k, end="\t")
b = b + a
a = b - a
valor = str(a)
inicio, final = valor[:9], valor[-9:]
k += 1
print("")
"""
329468
CPU times: user 2h 25min 32s, sys: 44.6 s, total: 2h 26min 17s
Wall time: 2h 29min 54s
""
|
26a820a4654a0ae290874fb48bff92f22ebbfbf6 | ecastillob/project-euler | /001 - 050/12.py | 4,012 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
def get_divisores(N):
divisores = []
for i in range(1,N+1):
if N%i==0:
divisores.append(i)
return divisores
# In[6]:
get_divisores(28)
# In[12]:
N = 7
suma = int(N*(N+1)/2)
suma
# In[18]:
def get_cantidad_divisores(N):
divisores = 0
for i in range(1,N+1):
if N%i==0:
divisores += 1
return divisores
# In[19]:
get_cantidad_divisores(28)
# In[16]:
N = 0
while True:
N += 1
suma = int(N*(N+1)/2)
divisores = get_divisores(suma)
print (suma, divisores)
if len(divisores) > 5:
break
suma
# In[21]:
N = 0
while True:
N += 1
suma = int(N*(N+1)/2)
if get_cantidad_divisores(suma) > 500:
break
suma
"""
#include <stdio.h>
#include <time.h>
int get_cantidad_divisores(int N){
int divisores = 0;
int i;
for (i=1; i<N+1; i++){
if (N%i==0)
divisores++;
}
return divisores;
}
int main(){
time_t start,end;
double dif;
time (&start);
int N = 0;
// 5 : 28, 0 seg.
// 300 : 2162160, 7 seg.
// 350 : 17907120, 175 seg.
int suma = 0;
while (1){
N++;
suma = (N*(N+1))/2;
if (get_cantidad_divisores(suma) > 5)
break;
}
printf("\n %d", suma);
time (&end);
dif = difftime (end,start);
printf ("\nYour calculations took %.2lf seconds to run.\n", dif );
}
"""
"""
#include <stdio.h>
#include <time.h>
int get_cantidad_divisores(int N){
int divisores = 0;
int i;
int extremo = (N/2) + 1;
if (N%2 == 0){
for (i=1; i<=extremo; i++){
if (N%i==0){
divisores++;
}
}
}
else{
for (i=1; i<=extremo; i+=2){
if (N%i==0){
divisores++;
}
}
}
return divisores;
}
int main(){
time_t start,end;
double dif;
/*
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
*/
time_t t;
//struct tm;
time (&start);
// divisores : tiempo
// 5 : 28, 0 seg.
/*
N = 7
suma = 28
*/
// 200 :
/*
LIMITE = 200
N = 2015
suma = 2031120
Your calculations took 4.00 seconds to run.
*/
/*
LIMITE = 250
N = 2079
suma = 2162160
Your calculations took 5.00 seconds to run.
*/
/* N = 5984
suma = 17907120
Your calculations took 175.00 seconds to run.
LIMITE = 350
N = 5984
suma = 17907120
Your calculations took 100.00 seconds to run.
*/
/*
LIMITE = 400
N = 5984
suma = 17907120
Your calculations took 99.00 seconds to run.
*/
/*
LIMITE = 500
N = 12375
divisores = 576
suma = 76576500 // este numero es la respuesta
Your calculations took 553.00 seconds to run.
*/
int N = 0;
int suma = 0;
int divisores = 0;
const int LIMITE = 500;
while (divisores <= LIMITE){
N++;
suma = (N*(N+1))/2;
divisores = get_cantidad_divisores(suma);
if (N % 1000 == 0){
t = time(NULL);
struct tm tm = *localtime(&t);
printf("\n %d-%d-%d %d:%d:%d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("\n N = %d", N);
printf("\n divisores = %d", divisores);
printf("\n suma = %d", suma);
printf("\n");
}
}
printf("\n LIMITE = %d", LIMITE);
printf("\n N = %d", N);
printf("\n divisores = %d", divisores);
printf("\n suma = %d", suma);
printf("\n");
time (&end);
dif = difftime (end,start);
printf ("\nYour calculations took %.2lf seconds to run.\n", dif );
}
""" |
66d407d714258a6aceea8e800a10ba5994af040a | ecastillob/project-euler | /101 - 150/112.py | 1,846 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number;
for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred,
but just over half of the numbers below one-thousand (525) are bouncy.
In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common
and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.
"""
# In[1]:
def arriba(N):
valor = -1
actual = -1
for n_str in str(N):
actual = int(n_str)
if actual < valor:
return False
valor = actual
return True
# In[2]:
def abajo(N):
valor = 10
actual = 10
for n_str in str(N):
actual = int(n_str)
if actual > valor:
return False
valor = actual
return True
# In[3]:
def es_bouncy(N):
return not (arriba(N) or abajo(N))
# In[4]:
arriba(134468), abajo(66420), es_bouncy(155349)
# In[5]:
def contar_bouncies(RATIO_LIMITE):
contador = 0
ratio = 0
i = 100
while (ratio != RATIO_LIMITE):
if es_bouncy(i):
contador += 1
ratio = contador / i
i += 1
return [contador, i - 1, ratio]
# In[6]:
contar_bouncies(0.5) # [269, 538, 0.5]
# In[7]:
contar_bouncies(0.9) # [19602, 21780, 0.9]
# In[8]:
contar_bouncies(0.99) # [1571130, 1587000, 0.99]
|
3e99069ad82eed7cd473865c13af5584f2ce9467 | ecastillob/project-euler | /051 - 100/56.py | 552 | 3.5 | 4 | """
A googol ($10^{100}$) is a massive number: one followed by one-hundred zeros;
$100^{100}$ is almost unimaginably large: one followed by two-hundred zeros. <br>
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, $a^b$, where a, b < 100, what is the maximum digital sum?
"""
maximo = 0
for a in range(1, 100):
for b in range(1, 100):
n = pow(a, b)
suma = sum([int(c) for c in str(n)])
if maximo < suma:
maximo = suma
maximo # 972
|
86b37e269f4b6d38ba7c04312c37446a5d690a4f | Qausain/PIAIC-Q-1 | /PIAIC 8 If else statements.py | 229 | 3.9375 | 4 | #If statements
a= 100
b= 200
if a<b:
print("a is less than b")
print("Hello A")
print("Hello B")
print("Help python")
if b<a:
print("b is less than a") # this block will not be executed
print("Pakistan")
|
3e08723fb5d96d9bb3570cf0157fdf7da1d38428 | liujieliewang/Python | /fibs.py | 164 | 3.796875 | 4 | #Python 3.5.2
fibs = [0,1]
n = input("请输入求第几位数:")
n = int(n)
for i in range(n-1):
fibs.append(fibs[-1]+fibs[-2])
print(fibs)
print(fibs[-1])
|
28083881cf61c01eecd51f82f8162052ca533e07 | shivanand217/some-useful-scripts | /email_crawler.py | 400 | 3.609375 | 4 | import requests
import re
#url = str(input('Enter a URL: '))
url = 'https://blog.anudeep2011.com/20-by-25/'
website = requests.get(url)
html = website.text
links = re.findall('"((html|ftp)s?://.*?)"', html)
emails = re.findall('([\w\.,]+@[\w\.,]+\.\w+)', html) # list
print(len(emails))
print("\n Found {} links".format(len(links)))
for email in emails:
print(email)
|
0daa2d8b4bcf20bc8ebc25b059e62ef920065d5f | al0fayz/python-playgrounds | /fundamental/14-class.py | 467 | 3.875 | 4 | #example class in python
class siswa:
#this like constructor in other programming
def __init__(self, name, city):
#this like this in other language
self.name = name
self.city = city
#create object
siswa_object = siswa("bento", "Jakarta")
print(siswa_object.name)
print(siswa_object.city)
#modify object
siswa_object.name = "alfa code"
print(siswa_object.name)
#delete properties
del siswa_object.city
#delete object
del siswa_object |
9bb69fee060d1b2704b37388080cc2488b447c0c | al0fayz/python-playgrounds | /mysql/4-select.py | 584 | 3.5 | 4 | import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="python_example"
)
con = db.cursor()
con.execute("SELECT * FROM customers")
myresult = con.fetchall()
for x in myresult:
print(x)
print("==========================================")
# select column
con.execute("SELECT name, address FROM customers")
myresult = con.fetchall()
for x in myresult:
print(x)
print("==========================================")
#get 1 row
con.execute("SELECT * FROM customers")
myresult = con.fetchone()
print(myresult) |
6a442bcbc6464c0e325b859b78633111ae48a649 | al0fayz/python-playgrounds | /fundamental/1-variabel.py | 1,045 | 4.3125 | 4 | #example variabel in python
x = 5
y = 2
kalimat = "hello world"
kalimat1 = 'hai all!'
print(x)
print(y)
print(kalimat)
print(kalimat1)
a , b , c = 1, 2, 3
text1, text2, text3 = "apa", "kabar", "indonesia?"
print(a, b, c)
print(text1, text2, text3)
result1 = result2 = result3 = 80
print(result1, result2, result3)
print("your weight is" , result1) #integer
print("i like " + text3) #string
#example global variabel
# this is a global variabel
name = "alfa"
def test():
# i can call variabel global inside function
print("my name is " + name)
#call function
test()
# global variabel can call inside or outside function
# example local varibel
def coba():
address = "jakarta" #this is local variabel you can call on outside func
print(address)
# if you want set global varibel inside function you can add global
#ex :
global bahasa #you must defined first , you can't insert value directly
bahasa = "indonesia"
print(bahasa)
coba()
# i try call variabel global
print("my language is "+ bahasa)
|
cfcbe016443d6a8fa6bd958d56d8e49705269b81 | al0fayz/python-playgrounds | /fundamental/6-tuples.py | 726 | 4.3125 | 4 | #contoh tuples
"""
tuples bersifat ordered, tidak bisa berubah, dan dapat duplicate
"""
contoh = ("satu", "dua", "tiga", "tiga")
print(contoh)
#acces tuples
print(contoh[0])
print(contoh[-1])
print(contoh[1:4])
#loop tuples
for x in contoh:
print(x)
#check if exist
if "satu" in contoh:
print("yes exist")
#length of tuples
print(len(contoh))
#kita tidak bisa menghapus element atau menambahkan element pada tuples
# tapi kita bisa delete tuples
del contoh #delete tuples
#join tuples
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
#tuples constructor untuk membuat tuples
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple) |
2eca24e3b6f7fa52f1e1ab9bd8fd20f6d2e46e3d | aaryanredkar/prog4everybody | /project10.py | 158 | 4.25 | 4 |
number = int(input("print number:"))
for i in range(2,number+1,2):
print(i,"is even")
for i in range( 1,number+1,2):
print (i, "is odd number")
|
7643854c54690814e2744e3cd80bc02ec02770e1 | aaryanredkar/prog4everybody | /L1C2_Fibonacci.py | 229 | 4.28125 | 4 | Value = int(input("Please enter MaxValue for Fibonacci sequence : "))
print ("The fibonacci sequence <=",Value, "is: ")
a, b = 0, 1
temp = 0
print ("0 ")
while (b <= Value):
print (b)
temp = a+b
a = b
b = temp
|
2dc3ba209e1100f597f27cc5d1315b4fc3685da5 | aaryanredkar/prog4everybody | /week 8/assign.8-1.py | 277 | 3.578125 | 4 | fname = raw_input("Enter file name: ")
fh = open(fname)
dic = dict()
for line in fh:
words = line.split()
for word in words:
if word not in dic:
dic[word] = 1
else:
dic[word] += 1
print dic
|
d3ac42b901175baf2807d756b15f868b39127910 | aaryanredkar/prog4everybody | /turtlehexagon.py | 307 | 3.953125 | 4 |
from turtle import *
setup()
x = 0
# Use your own value
y = 0
# Use your own value
length = int(input("What is the length:"))
def hexagon (size_length):
#penup()
pendown ()
forward(size_length)
right (60)
goto (x, y)
for _ in range (6):
hexagon (length)
exitonclick ()
|
920758fd9645d01fbdd33081223eb1e7601945f0 | aaryanredkar/prog4everybody | /project 8.py | 209 | 3.890625 | 4 |
age = int(input("Enter age:")
password = 12music12
if age <18:
print = ("You are a minor")
if age >= 18:
input("Enter password:")
password
if
elif sum<= 79:
|
2ff8327e1670af39e6ba1a6f2e7af471982cfe5c | aaryanredkar/prog4everybody | /userdev3.py | 167 | 4.21875 | 4 | n = int(input("Give me the highest number to print all the digits divided by three:"))
for number in range(1,n + 1):
if number % 3 == 0:
print(number)
|
3ef7c91a7f379e5b8f4f328c0e79a9238d6bce08 | aaryanredkar/prog4everybody | /project 2.py | 327 | 4.3125 | 4 | first_name = input("Please enter your first name: ")
last_name = input("Please enter your last name: ")
full_name = first_name +" " +last_name
print("Your first name is:" + first_name)
print("Your last name is:" + last_name)
print ("Your complete name is ", full_name)
print("Your name is",len(full_name) ,"characters long")
|
5c5352f4e10a55c33a50dd66527cf91fc5a86c80 | aaryanredkar/prog4everybody | /L1C7_Game.py | 734 | 3.984375 | 4 | import random
guessesLeft = 15
userName = input("Please enter your Name :")
number = random.randint(1, 1000)
print("Hello", userName, "I'm thinking of a number between 0 and 1000.")
while guessesLeft > 0:
print("You have", guessesLeft, "guesses left")
guess = int(input("Guess a number : "))
guessesLeft = guessesLeft - 1
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
elif guess == number:
print("Good job,",userName,"! You guessed my number in",(15-guessesLeft),"guesses!")
break
if guessesLeft == 0:
print("Sorry. The number I was thinking of was", number)
break
print("Have a Nice Day...")
|
cc1b8fc6d0f4e662d71b70d165ab884599af0b16 | aaryanredkar/prog4everybody | /challenge.py | 242 | 4.03125 | 4 | n = int(input("Enter the Nth number divisibleby 3"))
count= 1
i=1
while(True):
if(i%3==0):
if count==n:
print(n,"number divisibe l by 3 is:",i)
break
else:
count= count + 1
i = i +1
|
9f70df178dfbe74702e47c2c0725a6ac74674080 | aaryanredkar/prog4everybody | /week 8/8-2.py | 424 | 3.578125 | 4 | fname = raw_input("Enter file name: ")
fh = open(fname)
dic = dict()
for line in fh:
if line.startswith('From'):
t=line.split()
email = t[1]
if email not in dic:
dic[email] = 1
else:
dic[email] +=1
bigcount = None
bigemail = None
for email,count in dic.items():
if bigcount is None or count > bigcount:
bigemail = email
bigcount = count
print bigemail, bigcount
|
073db0007183aa65c945b3f27b8772260f405922 | aaryanredkar/prog4everybody | /nameentnormal.py | 153 | 4.125 | 4 | name = input("Please enter your name: ")
print("Hello, "+name + "!")
print("Let me print you name %s times. " %len(name))
for i in name:
print (name)
|
8973346ceee21cfc1423ab6426fb167d9151cb5d | Daniel-Fingerson/Shrimp-Code | /Shrimp-Master/sensor.py | 2,669 | 3.578125 | 4 | # Module: sensor.py
import random
import time
from log import log
from LTC2448 import read
import spidev
from bokeh.plotting import figure
class Sensor:
""" A sensor object handles the following tasks:
- Reading the mcp sensor data
- Logging the data
- Plotting the data with Bokeh
Args:
name (str): What the sensor is reading
unit (str): What the sensor's unit should be
index (int): Index for corresponding MCP sensor
(set to -1 to spoof data)
adjust (lambda): A function that adjusts the 0-1023 input value
to unit value.
color (str): The color of the graph
initialVal (float): What is the first data point (useful for spoofing)
Example:
Sensor("Oxygen", "mg/l", 1, lambda x: x * 12.5, "red")
Sensor("Nitrogen", "mg/l", 2)
Todo:
Using inheritance to make Sensor, SensorLog, SensorBokeh.
"""
def __init__(self, name, unit, index, adjust=lambda x: x,
color="green", initialVal=0):
self.name = name
self.unit = unit
self.index = index
self.datum = initialVal
self.lastLog = time.time() - 60
self.adjust = adjust
# Plot Config
self.plot = figure(plot_width=800, plot_height=400,
title=name)
self.plot.x_range.follow = "end"
self.plot.x_range.follow_interval = 100
self.plot.x_range.range_padding = 0
self.plot.yaxis.axis_label = unit
self.plot.xaxis.axis_label = "steps"
r = self.plot.line([], [], color=color, line_width=2)
self.ds = r.data_source
def getData(self):
"""Reads and logs the data from via the mcp library.
It also has to option to spoof data for demo purposes.
Set sensor index to -1 to do so"""
if self.index < 0:
self.datum = self.spoofData()
else:
self.datum = read() #LTC2448; implemented by Daniel Fingerson
self.datum = self.adjust(self.datum)
self.logData()
return self.datum
def updatePlot(self, step):
"""Updates the Bokeh plot"""
self.ds.data['x'].append(step)
self.ds.data['y'].append(self.getData())
self.ds.trigger('data', self.ds.data, self.ds.data)
def spoofData(self):
"""Creates random data for demoing purposes"""
return self.datum + random.uniform(.1, -.1)
def logData(self):
"""Logs the data every minute"""
if time.time() - self.lastLog > 59:
self.lastLog = time.time()
log(str(self.datum), self.name + ".log")
|
eafcad4e44d090ddae3e7d70b1c721d6aa245936 | adambemski/book_think_in_python | /official_solutions/unstable_sort.py | 1,692 | 4 | 4 | """Moduł zawiera przykładowy kod powiązany z książką:
Myśl w języku Python! Wydanie drugie
Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
Licencja: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
import random
def sort_by_length(words):
"""Sortuje listę słów w odwrotnej kolejności według długości.
Jest to wersja zawarta w książce stabilna w tym sensie, że słowa
o tej samej długości pojawiają się w tej samej kolejności.
words: lista łańcuchów
Zwraca: lista łańcuchów
"""
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res
def sort_by_length_random(words):
"""Sortuje listę słów w odwrotnej kolejności według długości.
Jest to rozwiązanie ćwiczenia niestabilne w tym sensie, że
jeśli dwa słowa mają identyczną długość, ich kolejność na
liście wyjściowej jest losowa.
Działanie polega na rozszerzaniu listy krotek za pomocą kolumny
liczb losowych. Gdy w pierwszej kolumnie występuje wynik,
o kolejności listy wyjściowej decyduje kolumna liczb losowych.
words: lista łańcuchów
Zwraca: lista łańcuchów
"""
t = []
for word in words:
t.append((len(word), random.random(), word))
t.sort(reverse=True)
res = []
for length, _, word in t:
res.append(word)
return res
if __name__ == '__main__':
words = ['John', 'Eric', 'Graham', 'Terry', 'Terry', 'Michael']
t = sort_by_length_random(words)
for x in t:
print(x)
|
7444d3eccfc49c602480ca9af1830ac9ce6aea36 | adambemski/book_think_in_python | /official_solutions/birthday.py | 1,775 | 3.734375 | 4 | """Moduł zawiera przykładowy kod powiązany z książką:
Myśl w języku Python! Wydanie drugie
Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
Licencja: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
import random
def has_duplicates(t):
"""Zwraca wartość True, jeśli w ciągu dowolny element występuje więcej niż raz.
t: list
Zwraca: bool
"""
# utworzenie kopii t w celu uniknięcia modyfikowania parametru
s = t[:]
s.sort()
# sprawdzenie pod kątem sąsiednich elementów, które są równe
for i in range(len(s)-1):
if s[i] == s[i+1]:
return True
return False
def random_bdays(n):
"""Zwraca listę liczb całkowitych z zakresu od 1 do 365 dla długości n.
n: int
Zwraca: lista elementów typu int
"""
t = []
for i in range(n):
bday = random.randint(1, 365)
t.append(bday)
return t
def count_matches(num_students, num_simulations):
"""Generuje przykładowe daty urodzin i określa liczbę duplikatów.
num_students: liczba studentów w grupie
num_samples: liczba grop do symulowania
Zwraca: int
"""
count = 0
for i in range(num_simulations):
t = random_bdays(num_students)
if has_duplicates(t):
count += 1
return count
def main():
"""Uruchamia symulację dat urodzin i wyświetla liczbę zgodności."""
num_students = 23
num_simulations = 1000
count = count_matches(num_students, num_simulations)
print('W wypadku %d symulacji' % num_simulations)
print('z %d studentami' % num_students)
print(' %d symulacji miało co najmniej jedną zgodność.' % count)
if __name__ == '__main__':
main()
|
2c47ae82f1c5cc12c56b24859cb57fd9e4a03b22 | adambemski/book_think_in_python | /official_solutions/pronounce.py | 1,046 | 3.578125 | 4 | """Moduł zawiera przykładowy kod powiązany z książką:
Myśl w języku Python! Wydanie drugie
Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
Licencja: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
def read_dictionary(filename='c06d'):
"""Wczytuje plik i buduje słownik odwzorowujący
każde słowo na łańcuch opisujący jego podstawową wymowę.
Dodatkowe wymowy są dodawane do słownika z liczbą (w nawiasach okrągłych)
na końcu klucza, dlatego klucz drugiej wymowy w wypadku słowa
abdominal to abdominal(2).
filename: łańcuch
Zwraca: odwzorowanie łańcucha na wymowę
"""
d = dict()
fin = open(filename)
for line in fin:
# pominięcie komentarzy
if line[0] == '#': continue
t = line.split()
word = t[0].lower()
pron = ' '.join(t[1:])
d[word] = pron
return d
if __name__ == '__main__':
d = read_dictionary()
for k, v in d.items():
print(k, v)
|
69771e69ce38cd6bc15148c13530adb910e45582 | adambemski/book_think_in_python | /official_solutions/anagram_sets.py | 2,276 | 3.578125 | 4 | """Moduł zawiera przykładowy kod powiązany z książką:
Myśl w języku Python! Wydanie drugie
Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
Licencja: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
def signature(s):
"""Zwraca sygnaturę danego łańcucha.
Sygnatura to łańcuch zawierający wszystkie uporządkowane litery.
s: string
"""
# DO_ZROBIENIA: przebudowa za pomocą sorted()
t = list(s)
t.sort()
t = ''.join(t)
return t
def all_anagrams(filename):
"""Znajduje wszystkie anagramy na liście słów.
filename: nazwa pliku łańcuchów listy słów
Zwraca: odwzorowanie każdego słowa na listę jego anagramów.
"""
d = {}
for line in open(filename):
word = line.strip().lower()
t = signature(word)
# DO_ZROBIENIA: przebudowa za pomocą defaultdict
if t not in d:
d[t] = [word]
else:
d[t].append(word)
return d
def print_anagram_sets(d):
"""Wyświetla zbiory anagramów w d.
d: odwzorowanie słów na listę ich anagramów
"""
for v in d.values():
if len(v) > 1:
print(len(v), v)
def print_anagram_sets_in_order(d):
"""Wyświetla zbiory anagramów w d zgodnie ze zmniejszającą się wielkością.
d: odwzorowanie słów na listę ich anagramów
"""
# utworzenie listy (długość, pary słów)
t = []
for v in d.values():
if len(v) > 1:
t.append((len(v), v))
# sortowanie zgodnie z rosnącą długością
t.sort()
# wyświetlenie posortowanej listy
for x in t:
print(x)
def filter_length(d, n):
"""Wybiera tylko te słowa w d, które zawierają n liter.
d: odwzorowanie słowa na listę anagramów
n: całkowita liczba liter
Zwraca: nowe odwzorowanie słowa na listę anagramów
"""
res = {}
for word, anagrams in d.items():
if len(word) == n:
res[word] = anagrams
return res
if __name__ == '__main__':
anagram_map = all_anagrams('words.txt')
print_anagram_sets_in_order(anagram_map)
eight_letters = filter_length(anagram_map, 8)
print_anagram_sets_in_order(eight_letters)
|
25dc7432ddf8c869b07985676fc8b64b469391ba | adambemski/book_think_in_python | /official_solutions/rotate_pairs.py | 1,019 | 4.03125 | 4 | """Moduł zawiera przykładowy kod powiązany z książką:
Myśl w języku Python! Wydanie drugie
Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
Licencja: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
from rotate import rotate_word
def make_word_dict():
"""Wczytuje słowa w pliku words.txt i zwraca słownik
zawierający słowa jako klucze."""
d = dict()
fin = open('words.txt')
for line in fin:
word = line.strip().lower()
d[word] = None
return d
def rotate_pairs(word, word_dict):
"""Wyświetla wszystkie słowa, które mogą być generowane przez obrót słowa.
word: łańcuch
word_dict: słownik ze słowami jako kluczami
"""
for i in range(1, 14):
rotated = rotate_word(word, i)
if rotated in word_dict:
print(word, i, rotated)
if __name__ == '__main__':
word_dict = make_word_dict()
for word in word_dict:
rotate_pairs(word, word_dict)
|
b377a25068e901361ff9d78c3db9ca8655c0f5b0 | takapy0210/nlp_2020 | /chapter1/ans_08.py | 549 | 3.890625 | 4 | """
与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
英小文字ならば(219 - 文字コード)の文字に置換
その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.
"""
def cipher(text):
ret = ''.join(chr(219-ord(c)) if c.islower() else c for c in text)
return ret
text = 'Never let your memories be greater than your dreams. If you can dream it, you can do it.'
print(cipher(text))
print(cipher(cipher(text)))
|
9a1acec7ad9c2abb154a47e525c1510f2a178dad | takapy0210/nlp_2020 | /chapter1/ans_06.py | 798 | 3.65625 | 4 | """
“paraparaparadise”と”paragraph”に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,
XとYの和集合,積集合,差集合を求めよ.さらに,’se’というbi-gramがXおよびYに含まれるかどうかを調べよ.
"""
def generate_ngrams(text, n_gram=2):
ngrams = zip(*[text[i:] for i in range(n_gram)])
return list(ngrams)
text1 = 'paraparaparadise'
text2 = 'paragraph'
X = generate_ngrams(text1)
Y = generate_ngrams(text2)
print('union: {}'.format(set(X) | set(Y)))
print('intersection: {}'.format(set(X) & set(Y)))
print('diff: {}'.format(set(X) - set(Y)))
print('X include' if 'se' in [''.join(ngram) for ngram in X] else 'X not include')
print('Y include' if 'se' in [''.join(ngram) for ngram in Y] else 'Y not include')
|
d86670a431aaf17b7fbbf662783604b944ae75a5 | takapy0210/nlp_2020 | /chapter1/ans_09.py | 776 | 3.890625 | 4 | """
スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
ただし,長さが4以下の単語は並び替えないこととする.
適当な英語の文(例えば”I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .”)
を与え,その実行結果を確認せよ.
"""
import random
text = 'I couldn’t believe that I could actually understand what I was reading : the phenomenal power of the human mind .'
text_list = text.split()
print(' '.join(i[0] + ''.join(random.sample(i[1:-1], len(i[1:-1]))) + i[-1] if len(i) > 4 else i for i in text_list))
|
8ac7bda5a983d7a9864ed73dd5b7f1e6aa15259c | takapy0210/nlp_2020 | /chapter1/ans_03.py | 423 | 3.625 | 4 | """
“Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”
という文を単語に分解し,各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
"""
text = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
ret = [len(i.strip(',.')) for i in text.split()]
print(ret) |
e42fa8594a78de70dce53c3a2550f7343db7164e | aalex/quessy_alexandre_test | /quessyalexandre/linesoverlap.py | 862 | 3.609375 | 4 | #!/usr/bin/env python
"""
Line overlapping utilities.
"""
def _is_within(value, range_min, range_max):
ret = False
if value >= range_min and value <= range_max:
ret = True
return ret
def linesoverlap(line1, line2):
"""
Checks if two lines on an axis overlap.
"""
if type(line1) != tuple or len(line1) != 2:
raise TypeError('arg 1 must be a 2-element tuple')
if type(line2) != tuple or len(line2) != 2:
raise TypeError('arg 2 must be a 2-element tuple')
min1 = min(*line1)
max1 = max(*line1)
min2 = min(*line2)
max2 = max(*line2)
ret = False
if _is_within(min1, min2, max2):
ret = True
if _is_within(max1, min2, max2):
ret = True
if _is_within(min2, min1, max1):
ret = True
if _is_within(max2, min1, max1):
ret = True
return ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.