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 |
|---|---|---|---|---|---|---|
241f27d852cd7afe98e48478230ee1cd92ebf611 | enzo-mandine/runtrack-python | /jour04/job08/main.py | 700 | 3.828125 | 4 | def defineX(d, posX):
if posX == d:
posX = 1
elif posX == d - 1:
posX = 0
else:
posX += 2
return posX
def printBoard(board):
i = 0
while i < len(board):
print(board[i])
i += 1
def placeQueen(board, posY, posX):
d = len(board)
board[posY][posX] = "X"
posX = defineX(d, posX)
posY += 1
if posX == d or posY == d:
return printBoard(board)
return placeQueen(board, posY, posX)
n = int(input('i: '))
board = [['O' for x in range(n)] for y in range(n)]
if n > 3 and n % 3 == 0:
placeQueen(board, 0, 1)
elif n > 3 and n % 2 != 0:
placeQueen(board, 0, 0)
else:
print('operation impossible')
|
ae89977da0668433e3c01f41c89f216feb9848e1 | GregGamer/python_homework | /Übungsblatt3/U3Bsp6.py | 1,344 | 3.53125 | 4 | """
Gregor Wagner
U3Bsp6.py - Klassen Kreis, Rechtek, Quadrat mit Methoden
Gregor Wagner, 52005240
"""
from cmath import pi as pi
class Kreis:
def __init__(self, radius):
self.radius = radius
def flaeche(self):
f = self.radius * self.radius * pi
return round(f, 2)
def umfang(self):
u = 2 * self.radius * pi
return round(u, 2)
def __str__(self):
return f"Kreis: \t\tFläche: {self.flaeche()}, Umfang: {self.umfang()}"
class Rechteck:
def __init__(self, a, b):
self.a = a
self.b = b
def flaeche(self):
f = self.a * self.b
return round(f, 2)
def umfang(self):
u = 2 * (self.a + self.b)
return round(u, 2)
def __str__(self):
return f"Rechteck: \tFläche: {self.flaeche()}, Umfang: {self.umfang()}"
class Quadrat:
def __init__(self, a):
self.a = a
def flaeche(self):
f = self.a * self.a
return round(f, 2)
def umfang(self):
u = 4 * self.a
return round(u, 2)
def __str__(self):
return f"Quadrat: \tFläche: {self.flaeche()}, Umfang: {self.umfang()}"
def main() :
k1 = Kreis(7.1)
k2 = Kreis(4.8)
r1 = Rechteck(3.1, 7.4)
q1 = Quadrat(6)
print(k1)
print(k2)
print(r1)
print(q1)
if __name__ == "__main__":
main()
|
172cf6da126911110dda329d13e074e642d76bb1 | remote-worker-id/crash-course2-modularisasi | /modularisasi_tahap_1.py | 1,655 | 4.0625 | 4 | '''
Program menghitung luas segitiga = alas * tinggi / 2
'''
print('Menghitung luas segitiga 1 dengan copas')
alas = 6
tinggi = 2
luas_segitiga = alas * tinggi / 2
print(f'Segitiga dengan alas = {alas} dan tinggi = {tinggi} luasnya adalah = {luas_segitiga}')
print('Menghitung luas segitiga 2 dengan copas')
alas = 12
tinggi = 6
luas_segitiga = alas * tinggi / 2
print(f'Segitiga dengan alas = {alas} dan tinggi = {tinggi} luasnya adalah = {luas_segitiga}')
print('\nMenghitung luas segitiga dengan Fungsi')
def hitung_luas_segitiga(alas, tinggi):
luas_segitiga = alas * tinggi / 2
return luas_segitiga
print(f'Luas segitiga 1 dengan fungsi, hasilnya = {hitung_luas_segitiga(6, 2)}')
print(f'Luas segitigas 2 dengan fungsi, hasilnya = {hitung_luas_segitiga(12, 6)}')
print('\nMenghitung luas segitiga dengan fungsi jika alas dan tinggi sudah ditentukan')
alas = 100
tinggi = 20
print(f'Segitiga dengan alas = {alas} dan tinggi = {tinggi} luasnya adalah = {hitung_luas_segitiga(alas, tinggi)}')
# Memanggil fungsi cara kedua
print('\nMemanggil fungsi cara kedua')
def hitung_luas_segitiga2(alas, tinggi):
luas_segitiga = alas * tinggi / 2
print(f'Segitiga dengan alas = {alas} dan tinggi = {tinggi}, Luas segitiga adalah : {luas_segitiga}')
hitung_luas_segitiga2(4, 2)
hitung_luas_segitiga2(8, 2)
print('\nMembuat Output Halo nama, selamat datang! menggunakan fungsi')
# Membuat fungsi dengan output :
# Halo Nurul, selamat datang!
# Halo Lendis, selamat datang!
# Halo Fabri, selamat datang!
# Halo Isa, selamat datang!
def sapa (nama):
print(f'Halo {nama}, selamat datang!')
sapa('Nurul')
sapa('Lendis')
sapa('Fabri')
sapa('Isa')
|
b0f27e95ea3045f77f5caff05b0ca70a2cc6e318 | AndreSlavescu/DMOJ | /Fraction-Action.py | 431 | 3.953125 | 4 | #https://dmoj.ca/problem/ccc02s2
from fractions import Fraction
div = int(input())
num = int(input())
result = div//num
remainder = div - num * result
newfraction = Fraction(remainder, num)
if result * num < div and result != 0 and num < div:
print(str(result)+" "+str(newfraction))
elif num > div:
print(str(Fraction(div, num)))
elif result == 0:
print(str(newfraction)+"/"+str(num))
else:
print(str(result))
|
faba607c88ad0c595e06005d504ec42be76ff056 | AndreSlavescu/DMOJ | /WhoIsInTheMiddle.py | 305 | 3.65625 | 4 | #https://dmoj.ca/problem/ccc07j1
bowl1= int(input())
bowl2 = int(input())
bowl3 = int(input())
if (bowl1 > bowl2 and bowl1 < bowl3) or (bowl1 > bowl3 and bowl1 < bowl2):
print(bowl1)
elif (bowl2 > bowl1 and bowl2 < bowl3) or (bowl2 > bowl3 and bowl2 < bowl1):
print(bowl2)
else:
print(bowl3) |
0fe1d27bae934a01dc7c93e023d1bba924fc780a | AndreSlavescu/DMOJ | /RollTheDice.py | 317 | 3.609375 | 4 | #https://dmoj.ca/problem/ccc06j2
m = int(input())
n = int(input())
total = 0
for i in range(1, m+1):
for j in range(i,n+1):
if i+j == 10:
total = total + 1
if total == 1:
print(f"There is {total} way to get the sum 10.")
else:
print(f"There are {total} ways to get the sum 10.")
|
5077815f19f7bd1d729650704069e64e448cd89c | Souravdg/Python.Session_4.Assignment-4.2 | /Vowel Check.py | 776 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Problem Statement 2:
Write a Python function which takes a character (i.e. a string of length 1) and returns
True if it is a vowel, False otherwise.
"""
def vowelChk(char):
if(char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u'):
return True
else:
return False
# Take user input
char = input("Enter character: ");
# If Invalid input, exit
if (len(char) > 1):
print("string Length must be one")
exit();
else:
# If Invalid input, exit
if (char.isalpha() == False):
print("Invalid entry")
else:
# Invoke function
if (vowelChk(char)):
print(char, "is a vowel.");
else:
print(char, "is not a vowel.");
|
2ff83f165b89c4b0d36166ccdfbdb54974ad17f7 | Gsoin/randomStuff | /phonewithREGEX.py | 165 | 4.0625 | 4 | import re
import sys
phoneNum = input("Please Enter Your Phone Number: ")
regex = r"\w{3}-\w{3}-\w{4}"
lmao = re.search(regex, phoneNum)
print(lmao)
|
a2f4d8df9a88780d1528261d23a387787f3871a5 | angulo4/python | /dni-letra.py | 1,110 | 3.640625 | 4 | def dnil(dni):
# convert DNI to integer before '%'
let = ((int(dni)) % 23)
if let == 0:
return 'T'
elif let == 1:
return 'R'
elif let == 2:
return 'W'
elif let == 3:
return 'A'
elif let == 4:
return 'G'
elif let == 5:
return 'M'
elif let == 6:
return 'Y'
elif let == 7:
return 'F'
elif let == 8:
return 'P'
elif let == 9:
return 'D'
elif let == 10:
return 'X'
elif let == 11:
return 'B'
elif let == 12:
return 'N'
elif let == 13:
return 'J'
elif let == 14:
return 'Z'
elif let == 15:
return 'S'
elif let == 16:
return 'Q'
elif let == 17:
return 'V'
elif let == 18:
return 'H'
elif let == 19:
return 'L'
elif let == 20:
return 'C'
elif let == 21:
return 'K'
elif let == 22:
return 'E'
else:
return 'no se'
# Ask for DNI + adding text
print('La letra de tu DNI es: ' + (dnil(input('Escribe tu DNI sin letra: '))))
|
fb6ac747fcf5d0fc4fc360cdfbb7e146f9e099e4 | sharyar/design-patterns-linkedin | /visitor.py | 1,285 | 4.25 | 4 | class House(object):
def accept(self, visitor):
''' The interface to accept a visitor '''
# Triggers the visiting operation
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
print(self, 'worked on by', hvac_specialist)
# This creates a reference to the HVAC specialist within the house object.
def work_on_electricity(self, electrician):
print(self, 'worked on by', electrician)
def __str__(self) -> str:
return self.__class__.__name__
class Visitor(object):
''' Abstract Visitor '''
def __str__(self) -> str:
'''Simply returns the class name when visitor object is printed'''
return self.__class__.__name__
class HVACSpecialist(Visitor):
# Concrete class fro HVACSpecialist
def visit(self, house):
house.work_on_hvac(self)
# now the visitor has a reference to the house object
class Electrician(Visitor):
'''Concrete visitor: electrician'''
def visit(self, house):
house.work_on_electricity(self)
hvac1 = HVACSpecialist()
elec1 = Electrician()
h1 = House()
# House accepting visitors
h1.accept(hvac1)
h1.accept(elec1)
# The visitors visiting the house.
hvac1.visit(h1)
elec1.visit(h1) |
9e535f3debddcf01e1285c9de932c93b7d886561 | panenming/demo | /process.py | 421 | 3.625 | 4 | '''
python线程池使用
'''
import multiprocessing
import time
def func(msg):
print("msg:",msg)
time.sleep(3)
print("end")
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=3)
for i in range(4):
msg = "hello %d" %(i)
pool.apply_async(func,(msg,))
print("Mark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~")
pool.close()
pool.join()
print("Sub-process(es) done.") |
fb6ef873a4798349dda0d45aacc4ced5f63d65ba | spoorgholi/Python-Mini-projects | /encryption/encryption.py | 3,053 | 3.765625 | 4 | #importing the libraries
import random as rnd
################################################################
#function to get the message from the user
response_type = input('Do you want to input a message or read from the text file? (msg\text) \n')
if response_type == 'msg':
message = input('Input your message and hit enter: \n')
elif response_type == 'txt':
message = open("message.txt", "r").read()
else:
raise ValueError('The response is invalid input (txt or msg)\n')
################################################################
#generate the encryption key
def keygen(message):
key = []
for word in message:
key.append((rnd.randint(0, 128))) #range of asci characters
#write the encrypted text file
file1 = open('key.txt', 'w', encoding = "utf-8")
for i in key:
file1.write(str(i))
file1.write(', ')
file1.close()
return key
################################################################
#function to encrypt the message with xor cipher
def encyption(message, key):
hash_pile = []
enc_message = []
for word in message:
binary = (ord(word))
hash_pile.append(binary)
for i in range(0, len(key)):
enc_message.append(hash_pile[i] ^ key[i])
#print the encrypted message
encrypted = ''.join(chr(characters) for characters in enc_message)
print('Your message is encrypted to : \n', encrypted)
#write the encrypted text file
file2 = open('encrypted.txt', 'w', encoding = "utf-8")
file2.write(encrypted)
file2.close()
return enc_message
################################################################
#function to decrypt the message
def decrypt(enc_message, key):
dec_message = []
for i in range(0, len(key)):
dec_message.append(enc_message[i] ^ key[i])
#print the decrypted message
decrypted = ''.join(chr(characters) for characters in dec_message)
print('Your message is decrypted to : \n', decrypted)
#write the encrypted text file
file3 = open('decrypted.txt', 'w', encoding = "utf-8")
file3.write(decrypted)
file3.close()
return decrypted
################################################################
#generate the key
key = keygen(message)
#encrypt the message with the key
enc_message = encyption(message, key)
################################################################
#ask user for password for the decription
premission = input('Do you want to decrypt the message?(y/n) \n')
if premission == 'n':
exit
elif premission == 'y':
password = input('Enter the user password: \n')
try:
val = int(password)
except ValueError:
print("That's not an int!")
if val == 12345:
dec_message = decrypt(enc_message, key)
else:
print('The password is incorrect please try again \n')
else:
raise ValueError('The character enter is invalid please try again \n')
################################################################
|
226310768c827fd3f8d2d03302563f4e10241e25 | scv119/thehardway | /leetcode/023.swapPairs/swapPairs.py | 987 | 3.75 | 4 | #leetcode: https://leetcode.com/problems/swap-nodes-in-pairs/description/
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# time: O(n), space: O(1)
if head == None or head.next == None:
return head
sentry = pre = ListNode(0)
sentry.next = head
first = head
second = head.next
while first != None and second != None:
tempNext = second.next
pre.next = second
second.next = first
first.next = tempNext
pre = first
if first.next == None:
break
else:
first = pair1.next
second = first.next
return sentry.next
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# time: O(n), space: O(n)
if head == None or head.next == None:
return head
first = head
second = head.next
first.next = self.swapPairs(second.next)
second.next = first
return second
|
9af344d4575cad7e5a4df91d5806417f7d05c141 | scv119/thehardway | /leetcode/010.intersectionLinkedList/interseciontLinkedList.py | 1,032 | 3.703125 | 4 | # leetcode: https://leetcode.com/problems/intersection-of-two-linked-lists/#/description
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
: type headA, headB: ListNode
: rtype: ListNode
"""
# time complexity: O(n) and space complexity is O(1)
n = m = 0
tempA, tempB = headA, headB
while tempA != None:
n += 1
tempA = tempA.next
while tempB != None:
m +=1
tempB = tempB.next
if m > n:
diff = m - n
for i in xrange(diff):
headB = headB.next
else:
diff = n - m
for i in xrange(diff):
headA = headA.next
while headA != None and headB != None:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None
|
9dd9050ffca4e9c67628c713695472613b6ef5bd | mas254/tut | /String methods.py | 349 | 4.125 | 4 | course = "Python for Beginners"
print(len(course))
print(course.upper())
print(course.find("P"))
# You get 0 here as this is the position of P in the string
print(course.find("z"))
# Negative 1 is if not found
print(course.replace("Beginners", "Absolute Beginners"))
print(course)
print("Python" in course)
# All case sensitive
print(course.title()) |
132d54605b7b373f7d8494dce66665cf80cd9373 | mas254/tut | /creating_a_reusable_function.py | 935 | 4.28125 | 4 | message = input('>')
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
print(output)
def emojis(message):
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
return output
message = input('>')
result = emojis(message)
print(result)
# An explanation: add the def at the start. The parameter is what we've called message, which is what
# the user inputs (taken from previous code). You don't include the first or last lines (the ones which
# ask for or print input) into your function). Add return output into the function as the function has to
# return a value, which can then be stored into a separate variable.
message = input('>')
print(emojis(message))
# Can make it shorter like so. |
7a1229b6dafcccfa6877302a07c694eee6d82b4a | mas254/tut | /if statements.py | 995 | 3.953125 | 4 | # if it's hot
# it's a hot day
# drink plenty of water
# otherwise if it's cold
# it's a cold day
# wear warm clothers
# otherwise
# it's a lovely day
is_hot = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
print("Enjoy your day")
is_hot = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
else:
print("It's a cold day")
print("Wear warm clothes")
print("Enjoy your day")
is_hot = False
is_cold = True
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's a lovely day")
print("Enjoy your day")
good = True
if good:
print("10% off!")
print("Price is:")
print(1000000 * 0.1)
else:
print("Uh oh")
print("Price is:")
print(1000000 * 0.2)
price = 1000000
good = True
if good:
down = 0.1 * price
else:
down = 0.2 * price
print(f"Down payment: ${down}") |
cbec22cf9f6d6130b5a038c465391857c462ce30 | Alist07/pyintro | /temp.py | 152 | 3.71875 | 4 | c = -1
factor = 1.8
result = c * 1.8 + 32
print("If its is "+str(c)+" degrees celcius outside, then it is "+str(result)+" degrees fahrenheit outside")
|
f44e664979e4a35608643e72ab9ce4d38041c7f7 | xinhen/AutomaticTestSummarizer | /third.py | 887 | 3.578125 | 4 | import tkinter
from tkinter import *
from gui import window, bottom_frame
global thirdlabel
global thirdbutton
global thirdbutton1
def goback():
thirdbutton.destroy()
thirdbutton1.destroy()
thirdlabel.destroy()
exec(open(r".\fourth.py").read())
def gotosix():
thirdbutton.destroy()
thirdbutton1.destroy()
thirdlabel.destroy()
exec(open(r".\sixth.py").read())
# window = Frame(window)
# window.pack( side = TOP )
# bottom_frame = Frame(window)
# bottom_frame.pack( side = BOTTOM )
var = StringVar()
thirdlabel = Label(window, textvariable=var, fg="red")
var.set("Upload a file:")
thirdlabel.pack()
thirdbutton = tkinter.Button(bottom_frame, text="BROWSE", command=gotosix)
thirdbutton.pack()
thirdbutton1 = tkinter.Button(bottom_frame, text="BACK", command=goback)
thirdbutton1.pack()
# root.mainloop()
|
00c5ee50e9991dc8c5e16ae6bd5ec1b78cf48147 | jiyeon2/coding-test-practice | /leetcode/344_reverse_string.py | 510 | 3.859375 | 4 | # list.reverse() 메서드 사용
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()
# 투포인터 사용(두개의 포인터 이용해 범위 조정하면서 풀이)
class Solution:
def reverseString(self, s: List[str]) -> None:
left = 0 # 배열의 첫번째 요소
right = len(s)-1 # 배열의 마지막 요소
while left < right:
s[left], s[right] = s[right], s[left] # 스왑
left += 1
right -= 1
|
844f4ebb10a44eacaffbb01b459a53463272f39f | ruanyangry/pycse-data_analysis-code | /PYSCE-code/11.py | 563 | 3.6875 | 4 | # _*_ coding: utf-8 _*_
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.sin(3*x)*np.log(x)
x = 0.7
h=1e-7
# analytical derivative 貌似下式是对函数求偏导
dfdx_a = 3*np.cos(3*x)*np.log(x)+np.sin(3*x)/x
# finite difference 有限差分
dfdx_fd = (f(x+h)-f(x))/h
# central difference 中心差分
dfdx_cd = (f(x+h)-f(x-h))/(2*h)
# complex method 复平面方法
dfdx_I = np.imag(f(x+np.complex(0,h))/h)
print(dfdx_a)
print(dfdx_fd)
print(dfdx_cd)
print(dfdx_I)
print('job done')
|
76f1da5bc35d4ba5d777163877369f69d85f39d7 | kellischeuble/cs-module-project-algorithms | /single_number/single_number.py | 862 | 3.890625 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
def single_number(arr):
repeats = list()
for i, num in enumerate(arr):
if not num in arr[i+1:] and not num in repeats:
return num
repeats.append(num)
# First solution:
# Looks like this doesn't work because
# the test randomized it so that they won't always
# be next to each other
# double = True
# i = 0
# while double == True:
# if arr[i] != arr[i+1]:
# double = False
# odd_out = arr[i]
# i += 2
# return odd_out
# TODO:
# Recursive implementation
if __name__ == '__main__':
# Use the main function to test your implementation
arr = [1, 1, 4, 4, 5, 5, 3, 3, 9, 0, 0]
print(f"The odd-number-out is {single_number(arr)}") |
65df669d4c69dc87a639fda570fa464d19b1d325 | 1bm17cs074-ravi/PP-Lab | /fibo.py | 116 | 3.625 | 4 | def fib(n):
if n==0:
return 1
else:
return n*fib(n-1)
n = int(input())
print(fib(n))
|
2b11a6a7cc7072124064b071e3b29e59226e7faa | Hannigan/bipartite | /bipartite_push_relabel.py | 6,339 | 3.71875 | 4 | #!//Library/Frameworks/Python.framework/Versions/2.7/bin/python
from random import shuffle, seed, sample
from sys import argv
class Edge:
def __init__(self, left, right, height=0):
self.left = left
self.right = right
self.order = ""
self.direction = ""
self.capacity = 1
self.flow = 0
self.h = height
def e(self):
self.flow - self.excess
def __str__(self):
return "(" + str(self.left) + ", " + str(self.right) + ") "
# Command line has two arguments: N (number of vertices per side) and
# d (degree).
def create_regular_multigraph(N,d):
# create a list with d of each node on the right side
right_sides = []
for right in range(N):
for i in range(d):
right_sides.append(N + right)
# seed(17)
shuffle(right_sides)
print right_sides
incident = []
for i in range(2 * N):
incident.append([])
i = 0
edges = []
for left in range(N):
for e in range(d):
right = right_sides[i]
edge = Edge(left, right)
edges.append(edge)
incident[left].append(edge)
incident[right].append(edge)
i += 1
degree = (2 * N) * [d] # degree of untaken edges per vertex
return (incident, edges)
def push(u,v,f,cap,e):
delta = min(e[u],cap[u][v] - f[u][v])
print "Pushing " + str(delta) + " units of flow from " + str(u) + " -> " + str(v)
f[u][v] += delta
f[v][u] = -f[u][v]
e[u] -= delta
e[v] += delta
return f,e
def relabel(u,cap,f,h):
neighbors = [v for v in range(len(cap[u])) if cap[u][v] - f[u][v] > 0]
neighbors.sort()
lowest_neighbor = neighbors[0]
for i in neighbors:
if h[i] < h[lowest_neighbor]:
lowest_neighbor = i
print "Relabeling " + str(u) + " from " + str(h[u]) + " to " + str(1+h[lowest_neighbor])
h[u] = 1+h[lowest_neighbor]
steps = len(neighbors)
return h,steps
def findPush(f,cap,e,h,N):
for u in range(len(e)):
if e[u] > 0:
for v in range(2*N+2):
if cap[u][v] - f[u][v] > 0 and h[u] == 1 + h[v]:
return (u,v)
return ("NO PUSH","NO PUSH")
def findRelabl(f,cap,e,h,N):
for u in range(2*N): # don't consider sink and source
#print [ h[u] <= h[v] for v in range(2*N+2) if cap[u][v] - f[u][v] > 0 ]
#print e[u]
if e[u] > 0 and all([ h[u] <= h[v] for v in range(2*N+2) if cap[u][v] - f[u][v] > 0]):
return u
return "NO RELABEL"
def main(doPrint = False):
# Normal approach = 0, THC alternate approach = 1
if len(argv) == 1:
print "Enter N, d:",
params = raw_input().split()
N = int(params[0])
d = int(params[1])
approach = int(params[2])
else:
N = int(argv[1])
d = int(argv[2])
approach = int(argv[3])
print N, d
(incident,edges) = create_regular_multigraph(N,d)
if approach == 0: # Normal Approach
# source is named 2N, sink is named 2N+1
source_capacity = 1
assert source_capacity <= d
f = []
cap = []
for i in range(2*N+2):
f.append((2*N+2)*[0])
cap.append((2*N+2)*[0])
for edge in edges:
print edge.left, edge.right
cap[edge.left][edge.right] += 1
for left in range(N):
cap[-2][left] = source_capacity
for right in range(N,2*N):
cap[right][-1] = source_capacity
#print "\nf[][] = " + str(f)
print "\ncap[][] = " + str(cap)
h = (2*N+2)*[0]
h[-2] = N
#print "\nh[] = " + str(h)
e = (2*N+2)*[0]
#print "\ne[] = " + str(e)
# Initialize Preflow
for i in range(N):
f[-2][i] = cap[-2][i]
f[i][-2] = -cap[-2][i]
e[i] = cap[-2][i]
e[-2] -= cap[-2][i]
if approach == 1: # Alternate THC approach
# source is named 2N, sink is named 2N+1
f = []
cap = []
for i in range(2*N+2):
f.append((2*N+2)*[0])
cap.append((2*N+2)*[0])
for edge in edges:
print edge.left, edge.right
cap[edge.left][edge.right] += 1
f[edge.left][edge.right] += 1
f[edge.right][edge.left] -= 1
for left in range(N):
cap[-2][left] = d
f[-2][left] = d
f[left][-2] = -d
for right in range(N,2*N):
cap[right][-1] = 1
f[right][-1] = 1
f[-1][right] = -1
print "\nf[][] = " + str(f)
print "\ncap[][] = " + str(cap)
h = (2*N+2)*[1]
h[-2] = N
h[-1] = 0
print "\nh[] = " + str(h)
e = (2*N+2)*[0]
e[-2] = -d*N
e[-1] = N
for i in range(N,2*N):
e[i] = d-1
print "\ne[] = " + str(e)
push_steps = 0
relabel_steps = 0
while True:
print ""
(u,v) = findPush(f,cap,e,h,N)
if u != "NO PUSH":
(f,e) = push(u,v,f,cap,e)
if doPrint:
print "f[][] = " + str(f)
print "h[] = " + str(h)
print "e[] = " + str(e)
push_steps += 1
continue
u = findRelabl(f,cap,e,h,N)
if u != "NO RELABEL":
h,steps = relabel(u,cap,f,h)
if doPrint:
print "f[][] = " + str(f)
print "h[] = " + str(h)
print "e[] = " + str(e)
relabel_steps += steps
continue
break
# Print Results
matching = {}
for u in range(N):
for v in range (N,2*N):
if f[u][v] == 1:
matching[u] = v
print "(" + str(u) + ", " + str(v) + ")"
# Check if matching is valid
left = matching.keys()
left.sort()
assert left == range(N)
right = [v for k,v in matching.iteritems()]
right.sort()
assert right == range(N,2*N)
print "\nMatching is valid!\n"
print "Push Steps = " + str(push_steps)
print "Relabel Steps = " + str(relabel_steps)
if __name__ == "__main__":
main()
|
ae70140bf88116bd3b0b37ff5e6d1bdf91d2add1 | archibald1418/hello-people | /calc_sqrt.py | 375 | 4.09375 | 4 | def calc_root(n, limit):
'''Calculate using Babylon. Limit is the number of iterations'''
x1 = 1
for i in range(limit):
x_n_plus_1 = 1/2 * (x1 + (n / x1))
x1 = x_n_plus_1
return x1
n = int(input("Введите основание корня: "))
for i in [10, 100, 1000]: # Test on whether accuracy improves with more iterations
print(calc_root(n, i), '\n')
|
fbd4d0daacc9b3966b28e8bebd05aae4e5810e90 | sabach/restart | /test1.py | 257 | 4 | 4 | counter = 1
while (counter < 5):
count = counter
if count < 2:
counter = counter + 1
else:
print('Less than 2')
if count > 4:
counter = counter + 1
else:
print('Greater than 4')
counter = counter + 1
|
cda3560dfafcb1c358ea0c6ff93477d6e868bb68 | sabach/restart | /script10.py | 540 | 4.375 | 4 | # Write a Python program to guess a number between 1 to 9.
#Note : User is prompted to enter a guess.
#If the user guesses wrong then the prompt appears again
#until the guess is correct, on successful guess,
#user will get a "Well guessed!" message,
#and the program will exit.
from numpy import random
randonly_selected=random.randint(10)
guessed_number=input("Type your number to Guess: ")
while randonly_selected == int(guessed_number):
guessed_number=input("Type your number to Guess: ")
print (randonly_selected, guessed_number) |
bab4919fc4a74ad44e2828e8214d8801e8854ab2 | sabach/restart | /random_text.py | 435 | 3.90625 | 4 | #lista=['a', 'b', 'c','d']
#print(lista)
#for i in lista:
# print(i)
import random
#listb=[]
#n=int(input("insert name: "))
#for I in range (0, n):
# ele=str(input("enter: "))
# listb.append(ele)
# print(listb)
listc=[]
x=int(input("enter number: "))
y=int(input("enter second number: "))
for i in range(x,y):
listc.append(i)
print(i)
if i == 6:
print("hail")
else:
continue
print("this is the list {}".format(listc))
|
a65562f771f2a303f652c05cb16f75f27d3ebefe | shwethav29/ShowMeDatastructure | /merge_sorted_list.py | 1,958 | 4.03125 | 4 | class Node(object):
def __init__(self,value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def append(self,node):
if(self.head == None):
self.head = node
return
else:
current = self.head
while(current.next != None):
current = current.next
current.next = node
def __str__(self):
cur_head = self.head
out_string = ""
while cur_head:
out_string += str(cur_head.value) + " -> "
cur_head = cur_head.next
return out_string
def merge_sorted_lists(l1,l2):
merged_list = None
if(l1.head == None):
return l2
if(l2.head == None):
return l1
small = None
big = None
if(l1.head.value <= l2.head.value):
small = l1.head
big = l2.head
merged_list=l1
else:
small = l2.head
big = l1.head
merged_list = l2
prev = None
while(small != None and big !=None):
if(small.value > big.value):
temp = small
small = big
big = temp
while(small != None and small.value <= big.value):
prev = small
small = small.next
prev.next = big
return merged_list
def reverse_list(list):
cur = list.head
if(cur is None):
return list
prev = None
while(cur.next != None):
temp = cur.next
cur.next = prev
prev = cur
cur = temp
cur.next = prev
list.head = cur
return list
elements1 = [3,6,9]
elements2 = [1,2,3,4]
l1 = LinkedList()
for item in elements1:
l1.append(Node(item))
l2 = LinkedList()
for item in elements2:
l2.append(Node(item))
merged = merge_sorted_lists(l1,l2)
print(merged)
reverse = reverse_list(merged)
print(reverse)
reverse = reverse_list(LinkedList())
print(reverse) |
4658d4dd37d4432ea582bf11f8d3894911e4fab6 | VelizarMitrev/Python-Homework | /Homework3/venv/Exercise1.py | 176 | 4.0625 | 4 | def factorial(num):
if int(num) == 1:
return 1
return factorial(int(num)-1) * int(num)
inpur_number = input("Input a number: ")
print(factorial(inpur_number)) |
713773b1c5d7b50b23270a1ac5f7ca2aa62ac58b | VelizarMitrev/Python-Homework | /Homework1/venv/Exercise6.py | 343 | 4.34375 | 4 | nand = input("Choose a number ")
operator = input("Input + OR * for either computing a number or multiplying it ")
sum = 0
if operator == "+":
for x in range(1, int(nand) + 1):
sum = sum + x
if operator == "*":
sum = 1
for x in range(1, int(nand) + 1):
sum = sum * x
print("The final number is " + str(sum)) |
797e50d61535310dfdb4a6527db3bdcf9004d977 | VelizarMitrev/Python-Homework | /Homework4/venv/Exercise4.py | 417 | 3.96875 | 4 | number_list = [3, 6, 13, 2, 3, 3, 13, 5, 5]
occurences_dictionary = {}
for number in number_list:
if number not in occurences_dictionary:
occurences_dictionary[number] = 1
else:
occurences_dictionary[number] = occurences_dictionary[number] + 1
for number in occurences_dictionary:
print("The number " + str(number) + " is found " + str(occurences_dictionary[number]) + " in the list!")
|
ef91c75a3f4b16b4529a0d6e88db23f78a1bdf38 | VelizarMitrev/Python-Homework | /Homework1/venv/Exercise7.py | 356 | 4.03125 | 4 | import sys
vowels = ['a','o','u','e','i','y'] # I'm including 'y' as a vowel despite that 'y' can be both a vowel and a consonant
vowels_count = 0
print("Type something and I will count the vowels!")
input_text = input()
input_text = list(input_text)
for x in input_text:
if x in vowels:
vowels_count = vowels_count + 1
print(vowels_count) |
b44c3fcdf3aa99d88f9d5a03c7d12cb64e9715d6 | VelizarMitrev/Python-Homework | /Homework2/venv/Exercise10.py | 387 | 4.34375 | 4 | def fibonacci(num): # this is a recursive solution, in this case it's slower but the code is cleaner
if num <= 1:
return num
else:
return(fibonacci(num-1) + fibonacci(num-2))
numbers_sequence = input("Enter how many numbers from the fibonacci sequence you want to print: ")
print("Fibonacci sequence:")
for i in range(int(numbers_sequence)):
print(fibonacci(i)) |
6b48bbaadd59de3f10f2784c195b19ac43e107fd | MadJFish/DataPipeline | /WFQ/nearby_resale/1_get_filtered_distance.py | 2,582 | 3.65625 | 4 | from math import radians, cos, sin, asin, sqrt
import pyspark.sql.functions as sql_functions
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit
from pyspark.sql.types import *
APP_NAME = "get_filtered_distance" # Any unique name works
INPUT_RESALE_FILE = "../resale-flat-prices/cleaned_data/resale_lat_long.csv"
INPUT_SCHOOL_FILE = "../school/cleaned_data/school_lat_long.csv"
OUTPUT_PARENT_FOLDER = "wip_data/1_get_filtered_distance"
def get_distance(school_lat_long, resale_lat_long):
school_array = school_lat_long.strip().split(',')
resale_array = resale_lat_long.strip().split(',')
return haversine(float(school_array[0]),
float(school_array[1]),
float(resale_array[0]),
float(resale_array[1]))
# Reference:
# https://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
# Set up pyspark and geopy
spark = SparkSession.builder.appName(APP_NAME).getOrCreate()
# Set up methods for pyspark dataframe
# Reference: https://towardsdatascience.com/5-ways-to-add-a-new-column-in-a-pyspark-dataframe-4e75c2fd8c08
udf_get_distance = sql_functions.udf(get_distance, FloatType()).asNondeterministic()
# Read input
resale_df = spark.read.csv(INPUT_RESALE_FILE, inferSchema=True, header=True)
school_df = spark.read.csv(INPUT_SCHOOL_FILE, inferSchema=True, header=True)
# Get schools as array
school_row_array = school_df.collect()
# Get resales within 3km and export the results for each school respectively
for school_row in school_row_array:
# Get resales within 3km
resale_distance_df = resale_df \
.withColumn('distance', udf_get_distance(lit(school_row['lat_long']), 'lat_long')) \
.filter("distance BETWEEN 0 AND 3")
# Export to csv
output_folder = '%s/%s' % (OUTPUT_PARENT_FOLDER, school_row['school'])
resale_distance_df \
.coalesce(1) \
.write \
.format('csv') \
.option('header', 'true') \
.save(output_folder)
|
02d3f469da092a1222b12b48327c61da7fc1fea3 | mvargasvega/Learn_Python_Exercise | /ex6.py | 903 | 4.5 | 4 | types_of_people = 10
# a string with embeded variable of types_of_people
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
# assigns a string to y with embeded variables
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
# printing a string with variable y
print(f"I also said: '{y}'")
# assign the boolean value of false to hilarious
hilarious = False
# assigns a string with an empty curly brace, which allows us to print something in
joke_evaluation = "Isn't that joke so funny?! {}"
# prints thet variable joke_evaluation and plugs in False into the two curlry braces
print(joke_evaluation.format(hilarious))
# a variable that stores a string
w = "This is the left side of..."
# a variable that stores a string
e = "a string with a right side."
# Conncatintes two variables that are holding strings
print(w + e)
|
0933d196941665856228eb849dda31babe7876ea | GustavoGomes9/python_basics_review | /ex10.py | 339 | 3.9375 | 4 | # class inheritance
class Mother:
def __init__(self, dna='mother'):
self.dna = dna
def dna_test(self):
return self.dna
m = Mother('mother-alone')
print(m.dna_test())
class Son(Mother):
def __init__(self, dna='Son'):
super().__init__(dna)
s = Son()
print(s.dna_test())
|
cfdecdb930492a6d260018e5196ea1797e8b2196 | NoraVasileva/School-database | /Class_People.py | 1,728 | 3.75 | 4 | class People:
"""
Information about students, users and teachers.
"""
def __init__(self, first_name, last_name, email, password):
"""
Entering attributes.
:param first_name: user's first name
:param last_name: user's last name
:param email: user's e-mail address
:param password: user's password
"""
self.__first_name = first_name
self.__last_name = last_name
self.__email = email
self.__password = password
def set_first_name(self, new_name):
"""
Edit first name attribute.
:param new_name: user's edited first name
"""
self.__first_name = new_name
def get_first_name(self):
"""
Display first name attribute.
"""
return self.__first_name
def set_last_name(self, new_name):
"""
Edit last name attribute.
:param new_name: user's edited last_name
"""
self.__last_name = new_name
def get_last_name(self):
"""
Display last name attribute.
"""
return self.__last_name
def set_email(self, new_email):
"""
Edit e-mail attribute.
:param new_email: user's edited e-mail address
"""
self.__email = new_email
def get_email(self):
"""
Display e-mail attribute.
"""
return self.__email
def set_password(self, new_password):
"""
Edit password attribute.
:param new_password: user's edited password
"""
self.__password = new_password
def get_password(self):
"""
Display password attribute.
"""
return self.__password
|
0c6e56154648a44069f61e114aae97bfce397701 | NoraVasileva/School-database | /Registration_functions.py | 13,136 | 3.875 | 4 | import csv
import os
from print_functions import print_registration, print_reg_1, print_reg_2, print_reg_3
from Class_Student import Student
from Class_Teacher import Teacher
import datetime
import re
def registration():
"""
Registration form with options for students and teachers.
"""
print_registration()
role = input("\nPlease enter a number from 1 to 3:\t").strip()
while role != "1" and role != "2" and role != "3":
print("\n*** Sorry, we don't have this option. ***")
print_registration()
role = input("\nPlease enter a number from 1 to 3:\t").strip()
if role == "1":
student_registration()
elif role == "2":
teacher_registration()
else:
return
def student_registration():
"""
Registration form for students. Entering personal data.
"""
pr = "\n************* REGISTRATION FORM FOR STUDENTS *************"
print(pr)
first_name = input("\nWhat is your first name:\t").strip().capitalize()
while check_name(first_name, 2, 20) and check_language(first_name):
print(f"\n*** Enter your first name again. Wrong length (2-20) or language (en or bg).\
Your first name is {first_name} ***")
first_name = input("\nWhat is your first name:\t").strip().capitalize()
last_name = input("\nWhat is your last name:\t").strip().capitalize()
while check_name(last_name, 5, 20) and check_language(last_name):
print(f"\n*** Enter your last name again. Wrong length (5-20) or language (en or bg).\
Your last name is {last_name} ***")
last_name = input("\nWhat is your last name:\t").strip().capitalize()
email = input("\nEnter your e-mail address:\t").strip()
while check_email(email):
print("\n*** This e-mail address is not recognized. ***")
email = input("\nEnter another e-mail address:\t").strip()
password_1 = input("\nEnter a password (enter at least six characters):\t").strip()
password_2 = input("\nEnter your password again:\t").strip()
while check_new_password(password_1, password_2):
print("\n*** Your password is incorrect. Try again. ***")
password_1 = input("\nEnter a password (enter at least six characters):\t").strip()
password_2 = input("\nEnter your password again:\t").strip()
print("*" * len(pr))
student_reg = Student(
first_name=first_name,
last_name=last_name,
email=email,
password=password_1
)
students_database_for_approval(student_reg)
def students_database_for_approval(student: Student):
"""
Check if the student has already created a registration. If there is no registration, a new one is created.
:param student: object from class Student
"""
students_database = "students_database.csv"
students_database_for_approval = "students_database_for_approval.csv"
list_columns = ["First name", "Last name", "E-mail address", "Password"]
if not os.path.exists(students_database):
os_path_does_not_exists(students_database, list_columns)
if os.path.exists(students_database):
os_path_exists(students_database, student)
if os_path_exists is True:
print_reg_1()
return
if not os.path.exists(students_database_for_approval):
os_path_does_not_exists(students_database_for_approval, list_columns)
if os.path.exists(students_database_for_approval):
os_path_exists(students_database_for_approval, student)
if os_path_exists is True:
print_reg_2()
return
else:
with open(students_database_for_approval, "a") as file:
writer = csv.writer(file, delimiter="\t")
temp_list = [
student.get_first_name(),
student.get_last_name(),
student.get_email(),
student.get_password()
]
writer.writerow([temp_list[0], temp_list[1], temp_list[2], temp_list[3]])
print_reg_3()
def teacher_registration():
"""
Registration form for teachers. Entering personal data.
"""
date_now = datetime.datetime.now()
year_now = int(date_now.year)
pr = "\n************* REGISTRATION FORM FOR TEACHERS *************"
print(pr)
first_name = input("\nWhat is your first name?:\t").strip().capitalize()
while check_name(first_name, 2, 20) and check_language(first_name):
print(f"\n*** Enter your first name again. Wrong length (2-20) or language (en or bg).\
Your first name is {first_name} ***")
first_name = input("\nWhat is your first name?:\t").strip().capitalize()
last_name = input("\nWhat is your last name?:\t").strip().capitalize()
while check_name(last_name, 5, 20) and check_language(last_name):
print(f"\n*** Enter your last name again. Wrong length (5-20) or language (en or bg).\
Your last name is {last_name} ***")
last_name = input("\nWhat is your last name?:\t").strip().capitalize()
date_of_birth = input("\nOn what date were you born? Enter an integer:\t").strip()
month_of_birth = input("\nIn what month were you born? Enter an integer:\t").strip()
year_of_birth = input("\nIn what year were you born? Enter an integer:\t").strip()
while date_check(year_of_birth, month_of_birth, date_of_birth) is False or int(year_of_birth) < (year_now - 75) or\
int(year_of_birth) >= year_now:
print("\n*** Wrong information. Try again. ***")
date_of_birth = input("\nOn what date were you born? Enter an integer:\t").strip()
month_of_birth = input("\nIn what month were you born? Enter an integer:\t").strip()
year_of_birth = input("\nIn what year were you born? Enter an integer:\t").strip()
first_day_of_work = input("\nOn what date did you start working as a teacher? Enter an integer:\t").strip()
first_month_of_work = input("\nIn which month did you start working as a teacher? Enter an integer:\t").strip()
first_year_of_work = input("\nIn what year did you start working as a teacher? Enter an integer:\t").strip()
while date_check(first_year_of_work, first_month_of_work, first_day_of_work) is False or\
int(first_year_of_work) >= year_now or int(first_year_of_work) < (year_now - 57):
print("\n*** Wrong information. Try again. ***")
first_day_of_work = input("\nOn what date did you start working as a teacher? Enter an integer:\t").strip()
first_month_of_work = input("\nIn which month did you start working as a teacher? Enter an integer:\t").strip()
first_year_of_work = input("\nIn what year did you start working as a teacher? Enter an integer:\t").strip()
if int(year_of_birth) < year_now - 75 or int(year_of_birth) > year_now - 18 or \
int(first_year_of_work) < int(year_of_birth) + 16:
print("\n*** We are sorry, but you cannot register on our site. ***\n*** Please contact an administrator. ***")
return
email = input("\nEnter your e-mail address:\t").strip()
while check_email(email):
print("\n*** This e-mail address is not recognized. ***")
email = input("\nEnter another e-mail address:\t").strip()
password_1 = input("\nEnter a password (enter at least six characters):\t").strip()
password_2 = input("\nEnter your password again:\t").strip()
while check_new_password(password_1, password_2):
print("\n*** Your password is incorrect. Try again. ***")
password_1 = input("\nEnter a password (enter at least six characters):\t").strip()
password_2 = input("\nEnter your password again:\t").strip()
print("*" * len(pr))
teacher_reg = Teacher(
first_name=first_name,
last_name=last_name,
email=email,
password=password_1,
group="No study class",
date_of_birth=date_of_birth,
month_of_birth=month_of_birth,
year_of_birth=year_of_birth,
first_day_of_work=first_day_of_work,
first_month_of_work=first_month_of_work,
first_year_of_work=first_year_of_work
)
teachers_database_for_approval(teacher_reg)
def teachers_database_for_approval(teacher: Teacher):
"""
Check if the teacher has already created a registration. If there is no registration, a new one is created.
:param teacher: class Teacher
"""
teachers_database = "teachers_database.csv"
teachers_database_for_approval = "teachers_database_for_approval.csv"
list_columns = [
"First name",
"Last name",
"E-mail address",
"Password",
"Class",
"Birth",
"Work"
]
if not os.path.exists(teachers_database):
os_path_does_not_exists(teachers_database, list_columns)
if os.path.exists(teachers_database):
os_path_exists(teachers_database, teacher)
if os_path_exists is True:
print_reg_1()
return
if not os.path.exists(teachers_database_for_approval):
os_path_does_not_exists(teachers_database_for_approval, list_columns)
if os.path.exists(teachers_database_for_approval):
os_path_exists(teachers_database_for_approval, teacher)
if os_path_exists is True:
print_reg_2()
return
else:
with open(teachers_database_for_approval, "a") as file:
a = teacher.get_first_day_of_work()
b = teacher.get_first_month_of_work()
c = teacher.get_first_year_of_work()
work = f"{a}.{b}.{c}"
d = teacher.get_date_of_birth()
e = teacher.get_month_of_birth()
f = teacher.get_year_of_birth()
birth = f"{d}.{e}.{f}"
writer = csv.writer(file, delimiter="\t")
temp_list = [
teacher.get_first_name(),
teacher.get_last_name(),
teacher.get_email(),
teacher.get_password(),
"No study class",
birth,
work
]
writer.writerow([
temp_list[0],
temp_list[1],
temp_list[2],
temp_list[3],
temp_list[4],
temp_list[5],
temp_list[6]
])
print_reg_3()
def os_path_exists(database, user):
"""
Check if the email address exists in the database upon registration.
:param database: the name of the database
:param user: class Teacher or class Student
:return: Boolean
"""
with open(database, "r") as file:
reader = csv.reader(file, delimiter="\t")
temp_list = []
for row in reader:
if row[2] == user.get_email():
temp_list.append(row[2])
if len(temp_list) == 1:
return True
else:
return False
def os_path_does_not_exists(database, list_of_columns):
"""
Enter the column names in the student database.
:param database: the name of the database
:param list_of_columns: the names of the columns
"""
with open(database, "w") as new_file:
writer = csv.writer(new_file, delimiter="\t")
writer.writerow(list_of_columns)
def check_name(name, min_length_name, max_length_name):
"""
Checking name length, if the name contains numbers and if the name is not empty.
:param name: student's name for registration
:param min_length_name: minimum name length - 2 for first name; 5 for last name
:param max_length_name: maximum name length - 20
:return: Boolean
"""
return name.isspace() or name.isalpha() is False or len(name) > max_length_name or len(name) < min_length_name
def check_email(email):
"""
Checking e-mail address for mistakes.
:param email: user's e-mail address
:return: Boolean
"""
return email.isspace() or email == "" or email.endswith("@") or email.startswith("@") or email.count("@") > 1 or\
email.count("@") == 0
def check_new_password(password_1, password_2):
"""
Checking passwords for mistakes.
:param password_1: user's password
:param password_2: repetition of the user's password
:return: Boolean
"""
return password_1.isspace() or password_1 == "" or len(password_1) < 6 or password_1 != password_2
def date_check(year, month, day):
"""
Verification of date of birth information.
:param year: year of birth
:param month: month of birth
:param day: year of birth
:return: Boolean
"""
try:
datetime.date(int(year), int(month), int(day))
return True
except:
return False
def check_language(text):
if bool(re.search('[а-яА-Я]', text)) and bool(re.search('[A-Za-z]', text)):
return False
if bool(re.search('[а-яА-Я]', text)):
return True
if bool(re.search('[A-Za-z]', text)):
return True
return False
|
cbe1736657addb20e04b2a4e6560247610223bfa | dungkarl/python-tutorial | /OOP/unit4.py | 1,582 | 4.0625 | 4 | """
Inheritance and Creating Subclass
"""
class Employee:
#count_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = self.first + self.last + '@gmail.com'
#Employee.count_emps +=1
def fullname(self):
#return self.first + self.last
return '{}-{}'.format(self.first, self.last)
def apply_raise(self):
self.pay = self.pay * self.raise_amount
class Developer(Employee):
raise_amount = 1.5
def __init__(self, first, last, pay, prog_lang):
super().__init__(first, last, pay)
#Employee.__init__(first, last, pay)
self.prog_lang = prog_lang
class Manager(Employee):
def __init__(self, first, last, pay, employees=None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_emp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
def print_emps(self):
for emp in self.employees:
print("-->", emp.fullname())
dev_1 = Developer('Dung', 'Karl', 10000, 'Python')
dev_2 = Developer('John', 'Doe', 5000, 'Java')
# print(dev_1.email)
# print(dev_1.prog_lang)
# print(dev_2.email)
# #print(help(Developer))
# print(dev_1.pay)
# dev_1.apply_raise()
# print(dev_1.pay)
mng_1 = Manager('Max', 'Karl', 20000)
print(mng_1.fullname())
print(mng_1.email)
mng_1.add_emp(dev_1)
mng_1.add_emp(dev_2)
mng_1.print_emps()
mng_1.remove_emp(dev_1)
print("removed")
mng_1.print_emps()
|
f11a5d001000b57572d9031f2c4a87394a0073d4 | Denriful/python | /Словари/vowels_dict.py | 510 | 3.890625 | 4 | vowels = ["a","e","i","o","u"]
word = "Hitchhiker"
#word = input("Provide a word to search for vowels: ")
found = {}
#found['a']=0
#found['e']=0
#found['i']=0
#found['o']=0
#found['u']=0
for letter in word:
if letter in vowels:
found.setdefault(letter,0)
# if found[letter] not in found:
# found[letter] = 0
# else:
found[letter] += 1
for vowel,value in found.items():
# if value > 0 :
print(vowel,' was found ',value,' times')
|
fa5bb60e3bc6dfc20e358cd97163f08f3f0873f9 | vbrunell/python | /misc/misc.py | 498 | 3.765625 | 4 | #!/usr/bin/python
'''
del
'''
# remove a variable
var = 6
del var
# delete list elems
l = [1,2,3,4,5]
del l[0]
print l
del l[-2:0]
print l
# delete dictionary elems
d = {'a':1,'b':2,'c':3}
del d['b']
print d
print
'''
codecs
The "codecs" module provides support for reading a unicode file.
For writing, use f.write() since print does not fully support unicode.
'''
import codecs
f = codecs.open('../myfile.txt', 'rU', 'utf-8')
for line in f:
# now line is a *unicode* string
print line
|
8c83006938ace2a749581c2d7d36b1583135d3d4 | Saud-01/Phython-Codes | /Alphabets.py | 514 | 3.953125 | 4 | con = True
while True:
alnum = noalphnum = 0
str1 = input("Input your String: ")
str1 = str1.lower()
for count in range(len(str1)):
let = str1[count]
if let < "a" or let > "z":
noalphnum += 1
else:
alnum += 1
print(alnum, "Alphabets in your String")
print(noalphnum, "Non Alphabets in your String")
choice = input("""
Do you want to continue ?(Y/N):""")
if choice == "N":
con = False
break
|
ae40d862a7d184e37434708015af56762eb5f240 | Tinasamayasundaram/pythonguvi | /prime.py | 161 | 3.546875 | 4 | n=int(input())
count=0
for i in range(2,n):
if n % i == 0:
count=count+1
if(count >= 1):
print("no")
else:
print("yes")
|
609485218e5bf74543268de8413d09dbe3117a1a | appinha/adventofcode_2020 | /my_solutions/day_18/main.py | 1,641 | 3.75 | 4 | # Import common core
import sys
sys.path.append('../common_core')
from common_core import ft_core
# Import requirements
import re
input_file = sys.argv[1]
class Nbr(int):
'''
Class for storing numbers from math expressions.
The subtraction method will perform a multiplication instead, in order to
perform multiplications with same precedence as additions (Part One).
The multiplication method will perform an addition instead, in order to
perform additions with more precedence than multiplications.
'''
def __add__(self, x):
return Nbr(int(self) + x)
def __sub__(self, x):
return Nbr(int(self) * x)
def __mul__(self, x):
return Nbr(int(self) + x)
def ft_input_parser(raw_input):
return raw_input
def ft_eval_expr(data, part):
'''
This function applies regex to each line (string) of the input, convertingr
digits to Nbr objects, thus replacing '*' with '-' (in order to perform
multiplications with same precedence as additions), and (for Part Two)
'+' with '*' (in order to perform additions with more precedence than
multiplications), thus applying eval() to the resulting expression.
It returns the sum of all eval() results (for each line in the input).
'''
def regex(line):
if part == 1:
return re.sub(r'(\d+)', r'Nbr(\1)', line).replace('*', '-')
if part == 2:
return re.sub(r'(\d+)', r'Nbr(\1)', line\
).replace('*', '-').replace('+', '*')
return sum(eval(regex(line)) for line in data)
def ft_part1(data):
return ft_eval_expr(data, 1)
def ft_part2(data):
return ft_eval_expr(data, 2)
if __name__ == '__main__':
ft_core(input_file, ft_input_parser, ft_part1, ft_part2)
|
973983a34fdfbb942138bf3ab6ffcdea10f67bfd | appinha/adventofcode_2020 | /my_solutions/day_10/main.py | 1,757 | 3.609375 | 4 | # Import common core
import sys
sys.path.append('../common_core')
from common_core import ft_core
# Import requirements
from numpy import prod
input_file = sys.argv[1]
def ft_input_parser(raw_input):
'''
This function parses the input, converting the given list of strings
(lines from input file) to a list of integers.
'''
data = [int(line) for line in raw_input]
return [0] + sorted(data) + [max(data) + 3]
def ft_part1(data):
'''
This function counts how many deltas between numbers ("jolt difference")
of given sequence are equal to 1 and 3. The return is the product of
these counts.
'''
diffs = [0, 0]
for i in range(1, len(data)):
diff = data[i] - data[i - 1]
if diff == 1:
diffs[0] += 1
if diff == 3:
diffs[1] += 1
print(diffs)
return diffs[0] * diffs[1]
def ft_part2(data):
'''
This function creates a string with the deltas between numbers of given
sequence ("131113113111133"), then splits it on the 3s. The resulting
list of subgroups of ones ([[1], [111], [11], [1111], []]) is pruned and
converted to a list of subgroups' quantity of 1s ([3, 2, 4]), with
length < 2 subgroups being discarded because they don't allow for any
combinations other than the subgroup itself. The quantity of 1s is thus
substituted for the number of possible combinations in each subgroup
([4, 2, 7]). The return is the combination of all subgroup combinations,
i.e. the product of these numbers.
'''
subgroups = ''.join(str(data[i + 1] - data[i]) for i in range(len(data) - 1)).split('3')
qty_ones = [len(ones) for ones in subgroups if len(ones) > 1]
cmbs = [2, 4, 7]
return prod([cmbs[n - 2] for n in qty_ones])
if __name__ == '__main__':
ft_core(input_file, ft_input_parser, ft_part1, ft_part2)
|
35da50ad5c852ae98de19d9982339fa99ef7edf8 | jcasas31-mvm/pytest-example | /exercici1.py | 443 | 3.6875 | 4 | #Function to transform the name and the number to a final and real id
def generate_userid (name, identifier):
letters=""
words=name.split(" ")
for w in words:
letters += w [0].lower()
return str(identifier)+ "_" + letters
#Function maked to do a test for the correct us of the program
def test_generate_userid():
assert generate_userid("Roger España",23) == ("23_re")
#
final = generate_userid("Roger España",23)
print(final)
|
4d45abf36b5a92057e795f5165444c1b6092762f | Saneter/Education | /Assignment7-skeleton.py | 8,101 | 3.734375 | 4 | """
Author: Travis Jarratt
CIS 1600 - Assignment 7
Saint Louis University
A program to analyze test files using the Flesch scale.
Will take two files as inputs and output various results
based on user choices.
"""
from functools import reduce
import os
def num_sentences(textStr):
# This function is complete
# Pass in a string, not a list
sentences = textStr.count('.') + textStr.count('?') + \
textStr.count(':') + textStr.count(';') + \
textStr.count('!')
return sentences
def num_syllables(word_list):
# This function is complete
# Pass in a list of words. This function is complete
# Count the syllables
no_syllables = 0
vowels = "aeiouAEIOU"
for word in word_list:
for vowel in vowels:
no_syllables += word.count(vowel)
for ending in ['es', 'ed', 'e']:
if word.endswith(ending):
no_syllables -= 1
if word.endswith('le'):
no_syllables += 1
return no_syllables
def word_count(word_list):
# This function is complete
return len(word_list)
def grade_level(word_list, word_string):
# Computes Grade level
words = word_count(word_list)
sentences = num_sentences(word_string)
syllables = num_syllables(word_list)
level = int(round(0.39 * (words / sentences) + 11.8 *
(syllables / words) - 15.59))
return level
def flesch_index(word_list, word_string):
# Computes the Flesch Index
words = word_count(word_list)
sentences = num_sentences(word_string)
syllables = num_syllables(word_list)
index = 206.835 - 1.015 * (words / sentences) - \
84.6 * (syllables / words)
return index
def get_word_list_from_string(mystring):
# get rid of special characters by replacing them with spaces
for character in "\n\t.,?:;!":
mystring = mystring.replace(character, " ")
# break the string into words based on the spaces
wordlist = list(map(lambda word: word.strip(), mystring.split(" ")))
# get rid of empty strings. Multiple spaces in a row can cause this.
wordlist = list(filter(lambda word: len(word) > 0, wordlist))
return wordlist
def compare_text(wordstring1, wordstring2, metric):
## returns a value < 0 if chunk 2 is better than chunk1 according to the metric
## returns a value > 0 if chunk1 is better than chunk2 and 0 is they are both equal
val = -99
wordlist1 = get_word_list_from_string(wordstring1)
wordlist2 = get_word_list_from_string(wordstring2)
if metric == "size":
val = len(wordlist1) - len(wordlist2)
elif metric == "density":
# Note: Density is the average letters per word
c1 = len(reduce(lambda a, b: a + b, wordlist1)) / len(wordlist1)
c2 = len(reduce(lambda a, b: a + b, wordlist2)) / len(wordlist2)
val = c1 - c2
# add other metrics here
elif metric == "grade-level":
c1 = grade_level(wordlist1, wordstring1)
c2 = grade_level(wordlist2, wordstring2)
val = c1 - c2
elif metric == "flesch-index":
c1 = flesch_index(wordlist1, wordstring1)
c2 = flesch_index(wordlist2, wordstring2)
val = c1 - c2
return val
def fetch_common_words(word_string1, word_string2):
wordlist1 = get_word_list_from_string(word_string1)
wordlist2 = get_word_list_from_string(word_string2)
set1 = set(wordlist1)
set2 = set(wordlist2)
return set1.intersection(set2)
def fetch_unique_words(word_string1, word_string2):
# should return words that are in chunk 1 but not in chunk 2 and
# those that are in chunk 2 but not in chunk 1
word_list1 = get_word_list_from_string(word_string1)
word_list2 = get_word_list_from_string(word_string2)
word_set1 = set(word_list1)
word_set2 = set(word_list2)
common_set = word_set1 & word_set2
joint_set = word_set1 | word_set2
joint_set.difference_update(common_set)
return joint_set
def get_file_string():
# This function is complete
fname = input("Enter the filename of the file\n")
if not os.path.isfile(fname):
print("Invalid filename")
# return None to indicated this did not work
return None
return open(fname).read()
def run_analysis():
print("Welcome to the text analysis program.")
while True:
print("Here are your options:\n")
print("1. Load text files")
print("2. Compare two pieces of text")
print("3. Fetch words that have occurred in two pieces of text")
print("4. Fetch words that have occurred in only one of two pieces of text")
print("0. Quit")
choice = int(input("Please enter an option: \n"))
if choice == 0:
print("Good bye")
exit()
elif choice == 1:
# get the file data from user
file1_string = get_file_string()
if file1_string is None:
continue # go back and start UI over
file2_string = get_file_string()
if file2_string is None:
continue # go back and start UI over
elif choice == 2: # compare two pieces of text
try:
value = compare_text(file1_string, file2_string, "size")
print("\nFile Comparison")
if value == 0:
print("The files have the same number of words")
elif value > 0:
print("The first file has more words than the second does")
else:
print("The second file has more words than the first does")
value = compare_text(file1_string, file2_string, "density")
if value == 0:
print("The files have the same density")
elif value > 0:
print("The first file has greater density than the second does")
else:
print("The second file has greater density than the first does")
value = compare_text(file1_string, file2_string, "grade-level")
if value == 0:
print("The files have the same grade level")
elif value > 0:
print("The first file has a higher grade level than the second does")
else:
print("The second file has higher grade level than the first does")
value = compare_text(file1_string, file2_string, "flesch-index")
if value == 0:
print("The files have the same Flesch Index level.")
elif value > 0:
print("The second file has a lower Flesch Index level \n"
"and is harder to read than the first.")
else:
print("The first file has a lower Flesch Index level \n"
"and is harder to read than the second.")
except UnboundLocalError:
print("You must enter files before doing this option.\n")
return run_analysis()
print("\n\n")
elif choice == 3:
try:
common_words = fetch_common_words(file1_string, file2_string)
print("\nThe two files have these words in common")
print(common_words)
print("\n\n")
except UnboundLocalError:
print("You must enter files before doing this option.\n")
return run_analysis()
elif choice == 4:
try:
unique_words = fetch_unique_words(file1_string, file2_string)
print("The unique words from both files are:")
for word in unique_words:
print("{}".format(word))
print("\n\n")
except UnboundLocalError:
print("You must enter files before doing this option.\n")
return run_analysis()
else:
pass
return
# main
if __name__ == '__main__':
run_analysis()
|
f95a3729fcc7e2e5476081156a8f1d3a2378eb4d | Saneter/Education | /assignment_5_travis_jarratt.py | 4,287 | 4.15625 | 4 | """
author: Travis Jarratt
CIS 1600 - Assignment 5
Saint Louis University
"""
def get_data():
fileObj = open("./exam-scores.csv")
lines = fileObj.readlines()
dict_scores = {}
for line in lines[1:]:
lst_items = line.strip().split(",")
dict_scores[lst_items[0]] = (float(lst_items[1]), float(lst_items[2]))
return dict_scores
def print_menu():
print("\nEnter 1 to see all the scores")
print("2 to see a particular student's score")
print("3 to see the class average on a particular test")
print("4 to see the students with the highest score")
print("5 to display a list of students whose combined \n "
"score on both the tests exceeds the average \n "
"of the combined scores on the two tests")
userchoice = int(input("and 0 to quit."))
return userchoice
def display_all_data(dict_scores):
print("Here are all the students' scores:")
for stdname in dict_scores:
print("%s: %f %f" % (stdname, dict_scores[stdname][0], dict_scores[stdname][1]))
def display_specific_student_score(dict_scores):
student_name = input("Provide the student's name whose scores you would like to retrieve: ")
if not student_name in dict_scores:
print("Student %s is not present in our records!" % student_name)
else:
print("Student %s's scores are: %s" % (student_name,
str(dict_scores[student_name][0]) +
" " + str(dict_scores[student_name][1])))
def display_average_score(dict_scores):
test_no = int(input("Enter the number for the test: 1 for the first test and 2 for the second test: "))
if not test_no in (1, 2):
print("Please enter a valid test number: either 1 or 2. You have entered: %d" % test_no)
else:
total = 0
for key in dict_scores:
total += dict_scores[key][test_no - 1]
print("The avg. score on test %d is %f" % (test_no, total / len(dict_scores)))
def get_max_score(dict_scores, test_no):
maxScore = 0
for key in dict_scores:
if maxScore < dict_scores[key][test_no - 1]:
maxScore = dict_scores[key][test_no - 1]
return maxScore
def display_max_scores_on_test(dict_scores):
test_no = int(input("Enter the number for the test: 1 for the first test and 2 for the second test: "))
if not test_no in (1, 2):
print("Please enter a valid test number: either 1 or 2. You have entered: %d" % test_no)
else:
maxScore = get_max_score(dict_scores, test_no)
print("max score is " + str(maxScore))
for key in dict_scores:
if dict_scores[key][test_no - 1] == maxScore:
print("%s had a test score of %d" % (key, dict_scores[key][test_no - 1]))
def student_combined_score_both_tests(dict_scores):
temp_dict = {}
for k, v in dict_scores.items():
temp_dict[k] = (v[0] + v[1])
return temp_dict
def avg_score_both_tests(dict_scores):
testTotal = 0
for v in dict_scores.values():
testTotal += ((v[0]) + (v[1]))
return testTotal/len(dict_scores)
def better_than_the_avg_on_both_tests(dict_scores):
better_dict = {}
temp = student_combined_score_both_tests(dict_scores)
for k, v in temp.items():
if v > avg_score_both_tests(dict_scores):
better_dict[k] = v
print("The students who scored better\n"
"than the average score both tests, {}, are: ".format(avg_score_both_tests(dict_scores)))
for key, value in better_dict.items():
print("{} {}".format(key, value))
def run_ui():
dict_scores = get_data()
while True:
choice = print_menu()
if choice == 0:
print("Good bye!")
quit()
elif choice == 1:
display_all_data(dict_scores)
elif choice == 2:
display_specific_student_score(dict_scores)
elif choice == 3:
display_average_score(dict_scores)
elif choice == 4:
display_max_scores_on_test(dict_scores)
elif choice == 5:
better_than_the_avg_on_both_tests(dict_scores)
else:
print("%d is an invalid choice" % choice)
if __name__ == '__main__':
run_ui()
|
d5844b1e496c7623183bbdd642f083dcb8df8dc5 | grace-pham/CS260-Summer-2021 | /HW/HW1/Refactor/results.py | 809 | 3.671875 | 4 | # Student: Grace Pham - ntp33 - Course: CS 260
# Script Purpose: Generate result lists by running 12 functions (implemented in functions.py) with the elements of x in
# x_list as input values
from functions import *
# Create a list for x(s) to run these fx functions on
x_list = [1, 2, 4, 8, 16, 32, 64]
# Run fx functions with input x_list and store to lists
f1_result = [f1(x) for x in x_list]
f2_result = [f2(x) for x in x_list]
f3_result = [f3(x) for x in x_list]
f4_result = [f4(x) for x in x_list]
f5_result = [f5(x) for x in x_list]
f6_result = [f6(x) for x in x_list]
f7_result = [f7(x) for x in x_list]
f8_result = [f8(x) for x in x_list]
f9_result = [f9(x) for x in x_list]
f10_result = [f10(x) for x in x_list]
f11_result = [f11(x) for x in x_list]
f12_result = [f12(x) for x in x_list]
|
3fdbb2ddcc559d32bfc53b13f1c20a7e971ad6e6 | sakshamchauhn/CS50 | /CS50's_Introduction_to_CS/Week6/Problem_set_6/mario/less/mario.py | 263 | 3.875 | 4 | from cs50 import get_int
while True:
# Getting input from user:
height = get_int("Height: ")
if height > 0 and height < 9:
break
# Iterating for rows:
for i in range(1, height + 1):
print(" " * int(height - i), end="")
print("#" * i)
|
ae9db23556c0d9f5fad29bacaec103b2b79cddfd | tituvely/Python_Efficiency | /Lesson4/replace.py | 924 | 4.03125 | 4 | import re
import fileinput
# 파일을 읽으면서 수정하려고 할 때는 fileinput 사용
def convertToLowerCase():
# inplace는 문제가 생길 경우에 대비해 백업 파일을 생성해주는 것
with fileinput.FileInput('./replace_test_file', inplace=True) as f:
for line in f:
print (line.replace(line, line.lower()), end='')
def convertToUpperCaseWithRe():
with fileinput.FileInput('./replace_test_file', inplace=True) as f:
for line in f:
print (line.replace(line, re.sub('sample', 'Sample', line)), end='')
def readFile():
print ('======================')
with open('./replace_test_file', 'r') as f:
print (f.read())
print ('======================')
def main():
readFile()
convertToLowerCase()
readFile()
convertToUpperCaseWithRe()
readFile()
if __name__ == "__main__":
main() |
be24c6bb71f0c7754f1b6ec26c73294c7ca9248c | bleepster/exercism | /python/raindrops/raindrops.py | 320 | 3.703125 | 4 | def plxng(number, factor, drop_string):
return drop_string if number % factor == 0 else ""
def convert(number):
raindrops = ""
raindrops += plxng(number, 3, "Pling")
raindrops += plxng(number, 5, "Plang")
raindrops += plxng(number, 7, "Plong")
return str(number) if not raindrops else raindrops
|
6f9bf5aa91fda6f7657dfe3eb3b9fabbcf9a7326 | 787264137/Python | /leetcode/hash/寻找重复的子树.py | 607 | 3.625 | 4 | class Solution:
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
def hierarchicalTraversal(root,ans):
if not root:
return '#'
seq = str(root.val) + hierarchicalTraversal(root.left,ans)+hierarchicalTraversal(root.right,ans)
if seq not in hashmap:
hashmap[seq] = root
else:
ans.add(hashmap[seq])
return seq
hashmap = {}
ans = set()
hierarchicalTraversal(root,ans)
return list(ans)
|
80ad00f69d2d91bb3ae0698f210838e12cdadc4d | jaquemff/exercicio-aprendizagem-python | /ExercicioContagemRegressiva.py | 305 | 3.640625 | 4 | #Faça um programa que mostre na tela uma contagem regressiva para o estou de fogos
#de artifício, indo de 10 até 0, com uma pauda de 1 segundo entre eles.
from time import sleep
print('A CONTAGEM REGRESSIVA IRÁ COMEÇAR!')
sleep(2)
for i in range(10, -1, -1):
print(i)
sleep(1)
print('FIM!') |
a7e5d87ff3af437e273955a04ca6534ae3abe82b | jaquemff/exercicio-aprendizagem-python | /ExercicioTuplas001.py | 493 | 4.03125 | 4 | '''Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por
extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e
20) e mostrá-lo por extenso'''
n = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez')
while True:
n2 = int(input('Digite um valor entre 0 e 10: '))
if 0 <= n2 <=10:
break
print('Tente novamente. ', end='')
print('O número digitado foi {}.'.format(n[n2]))
|
6e6abd3de78936fa5260baaa7f8a5a3fcdd09762 | hhm4/AlgorithmsOnGraphs | /MinimumNumberOfEdges.py | 898 | 3.625 | 4 | class Graph:
def __init__(self,ver,edg):
self.noOfVertices=ver
self.noOfEdges=edg
self.edges=[]
self.queue=[]
for i in range(self.noOfVertices+1):
self.edges.append([False])
def addEdges(self,v1,v2):
self.edges[v1].append(v2)
self.edges[v2].append(v1)
def bfs(self,v,u):
if v==u:
return 0
else:
self.queue.append((v,0))
for q in self.queue:
vertex=q[0]
distance=q[1]
for ver in self.edges[vertex][1:]:
if not self.edges[ver][0]:
self.edges[ver][0]=True
if ver!=u:
self.queue.append((ver,distance+1))
else:
return distance+1
return -1
spec=raw_input()
spec=spec.split(' ')
g=Graph(int(spec[0]),int(spec[1]))
for e in range(g.noOfEdges):
input=raw_input()
input=input.split(' ')
i=int(input[0])
j=int(input[1])
g.addEdges(i,j)
path=raw_input()
path=path.split(' ')
print g.bfs(int(path[0]),int(path[1]))
|
3faac07504afdd5d5b12d8651945a426e6a49635 | anikesh4/Projects | /Personal projects/python projects/ceasar_cipher.py | 1,634 | 3.796875 | 4 | alphabet_list=['#','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
alphabet_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
def Next_alphabet(num,key):
new_num=(num+key)%26
if new_num==0:
new_num=26
return new_num
def previous_alphabet(num,key):
new_num=(num-key)
if new_num==0:
new_num=26
if new_num<0:
new_num+=26
return new_num
while True:
key=int(input('Please enter a key for the Cipher, between 1 and 25: '))
string=list(input('Enter the message to be encrypted: ').lower())
for letter in range(len(string)):
if string[letter] in 'qwertyuiopasdfghjklzxcvbnm':
string[letter]=alphabet_list[Next_alphabet(alphabet_dict[string[letter]],key)]
new_string="".join(string)
print(f'The message has been encrypted: {new_string}')
print("\n\n")
key=int(input('Please enter a key for the Cipher, between 1 and 25: '))
string=list(input('Enter the message to be decrypted: ').lower())
for letter in range(len(string)):
if string[letter] in 'qwertyuiopasdfghjklzxcvbnm':
string[letter]=alphabet_list[previous_alphabet(alphabet_dict[string[letter]],key)]
new_string="".join(string)
print(f'The message has been decrypted: {new_string}')
again=" "
while again!='yes' and again !='no':
again= input("Do you want to play again, 'yes' or 'no'??: ").lower()
if again=='no':
print("See you next time!!!")
break |
a7006682b79cc27ab8d53513dd530b26c44f6f7d | dzemildupljak/object_oriented_programming | /vezba1.py | 2,016 | 3.828125 | 4 | # Funkcija print () ispisuje navedenu poruku na ekran ili neki drugi standardni izlazni uređaj.
#
# Poruka može biti niz ili bilo koji drugi objekt, objekt će se pretvoriti u niz prije nego što se upiše na ekran.
# print(object(s), separator=separator, end=end, file=file, flush=flush)
print("Hello world")
print("Hello", "how are you?")
# sep="" Navedite kako razdvojiti objekte ako ih ima više. Podrazumevano je ''
print("Hello", "how are you?", sep="---")
# end="" Na kraju odredite šta treba štampati. Podrazumevano je '\n'
print("Hello world", end="\n\n")
print("Hello", "how are you?")
#############################################################################################3
# String izrazi u pythonu okruženi su ili pojedinačnim navodnicima ili dvostrukim navodnicima.
a = "Hello"
print(a)
# Viselinijski string mozemo kreirati pomocu 3 navodnici
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
# Stringovi u Pithon-u su nizovi bajtova koji
# predstavljaju znakove unicode.
#
# Međutim, Pithon nema karakter tipa podataka, jedan znak je jednostavno niz dužine 1.
#
# Uglaste zagrade mogu se koristiti za pristup elementima niza.
a = "Hello World"
print(a[0])
print(a[6])
# s = ' H e l l o W o r l d '
# 0 1 2 3 4 5 6 7 8 9 10
# -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print(a[-11])
# U toku prikazivanja mozete uporedjivati vrednosti i rezultat tog uporedjivanja ce vam se prikazati
vrednost1 = "Gryffindor"
vrednost2 = "Gryffindor"
print (vrednost1 == vrednost2)
new_vrednost1 = "Slytherin"
print (vrednost1 == new_vrednost1)
print (vrednost2 <= vrednost1)
print (vrednost2 >= vrednost1)
# Ključna reč može da se koristi za proveru da li određeni podstring postoji u drugom nizu.
# Ako se pronađe podstorija, operacija vraća true.
random_string = "This is a random string"
print ('of' in random_string)
print ('random' in random_string) |
14d1a8527bb1231952fc3a93723b684f2ba1b7ed | qszhhd/PythonSpace | /python_old/MyPython/lesson3.py | 5,825 | 4.3125 | 4 | ###--------1113:第1个小游戏------------------
####num=10;
####print('Guess what I think?');
####answer=int(input());#Python3中input()默认输入的都是字符串;
####
####while answer!=num:
#### if answer<num:
#### print("too small!");
#### else:
#### print("too big!");
####print('Bingo!');
##
##
####按照上述方式写的程序,进入了死循环;原因是:输入7,输出“too small!”;没有终止条件;程序一直输出“too small!”
###改进如下:
##
##from random import randint #引入随机模块,产生随机整数;
##
###num=10;
##num=randint(1,100);
##print('Guess what I think?');
##Bingo=False #开始循环前设置一个条件
##
##while Bingo==False:
## answer=int(input())#Python3中input()默认输入的都是字符串;
## if answer<num:
## print('%d is Too small!'%answer)
## elif answer>num:
## print('%d is Too big!'%answer)
## else:
## print('Bingo!%d is right!'%answer)
## Bingo==True;
###---------第1个小游戏的分割线--------------------
#-----练习:编写函数修改第1个小游戏-------
##def isEqual(num1,num2):
## if num1<num2:
## print('%d is too small'%num1);
## return False
## elif num1>num2:
## print('%d is too big'%num1);
## return False
## else:
## print('bingo!%d is right'%num1);
## return True
##
###return是函数的结束语句,return后面的值被作为这个函数的返回值。
###函数中任何地方的return被执行到的时候,这个函数就会结束
##
###或者利用这个函数修改第1个小游戏:
##
##from random import randint
##num=randint(1,100)
##print('Guess What I Think?')
##
##bingo=False
##while bingo==False:
## answer=int(input())
## bingo=isEqual(answer,num)
#------编写函数完成--------------------
#--------练习:高斯大牛在小时候做过的题---------
##sum1=0;
####num=1;
####while num<101:
#### sum1=sum1+num;
#### num=num+1;
####print(sum1);
##
##
##for i in range(1,101): #range(a,b)产生一组从a到b-1的整数序列
## sum1=sum1+i;
##print(sum1);
#------------Say bye to Gauss-----------------------------
#------练习:输出字符串---------
##print('''He said,"I'm yours!"''');
##print('\\\\_v_//');
##print('''
##Stay hungry,
##stay,foolish.
## -- Steve Iobs''');
##print('''
## *
## ***
## *****
## ***
## *''');
##print('My name is %s.'%'Crossin');
##print('The price is $%.2f.'%5.25);
##print('His age is %d.'%25);
##print("%s's score is %d"%('Mike',87));
#------输出字符串结束-------------
#-----练习:类型转换--------------
## 在python中,以下数值会被认为是False:
## 为0的数字,包括0,0.0
## 空字符串,包括'',""
## 表示空值的None
## 空集合,包括(),[],{}
## 其他的值都认为是True
##bool(-123)
##bool(0)
##bool('abc')
##bool('False')
##bool('')
##bool( )
##bool(False)
#------类型转换练习结束--------
#-------1113:第2个小游戏---------------------
###字符串比较出错了,得不到想要的结果
##print('Who do you think I am?');
##you=input();
##
##if you=='My Love'or'Flower'or'Princess':
## print('Oh,yes!');
##elif you=='Pig'or'Idiot':
## print('No,you are a',you,'!');
##else:
## print(None);
#---------字符串比较出错了,得不到想要的结果--------------------
#------练习:循环的嵌套----------
##for i in range(0,5):
## print('*'),
#------和教程15上说的不一样,没实现------
#-----点球小游戏1.0-----------
##from random import choice
##score_you=0;
##score_com=0;
##direction=['left','center','right'];
##for i in range(5):
## print('====Round %d -You Kick!===='%(i+1))
## print('Choose one side to shoot:')
## print('left,center,right')
## you=input()
## print('You kicked'+you)
## com=choice(direction)
## print('Computer saved'+com)
## if you!=com:
## print('Goal!')
## score_you+=1
## else:
## print('Oops...')
## print('Score:%d(you)-%d(com)\n'%(score_you,score_com))
##
## print('====Round %d -You Save!===='%(i+1))
## print('Choose one side to save:')
## print('left,center,right')
## you=input()
## print('You saved'+ you)
## com=choice(direction)
## print('Computer kicked'+com)
## if you==com:
## print('Saved!')
## else:
## print('Oops...')
## score_com+=1;
## print('Score:%d(you)-%d(com)\n'%(score_you,score_com))
#-----点球小游戏完成-------
#-----点球小游戏2.0--------
from random import choice
score=[0,0];
direction=[1,2,3];
def kick():
print('====You kick!====')
print('choose one side to shoot:')
print(1,2,3)
you=int(input())
print('You kicked'+str(you))
com=choice(direction)
print('Computer saved'+str(com))
if you!=com:
print('Goal!')
score[0]+=1;
else:
print('Oops...')
print('Score:%d(you)-%d(com)'%(score[0],score[1]));
print('====You save!====')
print('choose one side to save:')
print(1,2,3)
you=int(input())
print('You saved'+str(you))
com=choice(direction)
print('Computer kicked'+str(com))
if you==com:
print('Saved!')
else:
print('Oops...')
score[1]+=1;
print('Score:%d(you)-%d(com)'%(score[0],score[1]));
for i in range(5):
print('====Round %d===='%(i+1))
kick()
while(score[0]==score[1]):
i+=1;
print('====Round %d===='%(i+1))
kick()
if score[0]>score[1]:
print('You Win!')
else:
print('You Lose.')
#----点球2.0 增加了胜负判断,平分继续玩,直到分出胜负-----
|
2d97212501ea53237f39f753cb7da63fee9a5c08 | matheus-cal/cpftests | /validacpf_matheus.py | 659 | 3.5 | 4 | def retira_cpf(cpf):
format_cpf = ''
for i in cpf:
if i.isalnum():
format_cpf += i
print(format_cpf)
return format_cpf
def valida_cpf(num):
if len(num) < 11:
return False
if num in [s * 11 for s in [str(n) for n in range(10)]]:
return False
try:
calc = [i for i in range(1, 10)]
digit1= (sum([int(a)*b for a,b in zip(num[:-2], calc)]) % 11) % 10
digit2= (sum([int(a)*b for a,b in zip(reversed(num[:-2]), calc)]) % 11) % 10
num = str(digit1) == num[-2] and str(digit2) == num[-1]
return num
except ValueError:
return False
|
174ab3e0f488b9e2431989cf412dbb4a1640bfc0 | pallavi23022/Python-Programs | /string.py | 73 | 3.578125 | 4 | str1=input()
str2=int(input())
print(str2*str1)
print(str1+ str(str2) )
|
55ec5d557a6bcedcabd4324898f531f696e8dab8 | pallavi23022/Python-Programs | /Bill.py | 275 | 3.96875 | 4 | quantity=float(input("Enter quantity"))
value=float(input("Enter price"))* quantity
discount=float(input("Enter discount percentage"))
tax=float(input("Enter tax amount percentage"))
bill= value-( (discount/100)*value )+ ( (tax/100)*value )
print("Total bill: " , bill)
|
4b88afec8fb0deb41b99e71b6a114525c5e4ab82 | pallavi23022/Python-Programs | /program1.py | 238 | 3.734375 | 4 | #Q 2. WAP to create list of numbers divisible by 4 or 13
#all th eelements of the list should lie in the range from 200 to 500
list1=[]
for num in range(200,501,1):
if(num%4==0) or (num%13==0):
list1.append(num)
print(list1)
|
b2882b72d0f4681535c0009a5fdcc98249fefe98 | pallavi23022/Python-Programs | /listbegining.py | 170 | 4.125 | 4 | n=int(input("Enter a list"))
list1=[]
for i in range(0,n):
list1.append((input("Enter a element of a list ")))
print(list1)
l1=[1,2,3]
list1.append(l1)
print(list1)
|
b2fb7a3e0815ef919ffa920619e082597adb45eb | pallavi23022/Python-Programs | /CopiesOfString.py | 197 | 3.828125 | 4 | string=input("Enter String: ")
copies=int(input("Enter number of copies to be printed: "))
l=int(input("Enter length to be extracted: "))
for i in string:
slice=string[0:l]
print(slice*copies)
|
e8c226bb156c7f7e88664fedb3d3ee0eca2cf605 | pallavi23022/Python-Programs | /factorOfeachElement.py | 279 | 4 | 4 | num=int(input("ENter a number: "))
list1=[]
modified=[]
while(num!=0):
list1.append(num)
modified.append(num*10)
num=int(input("ENter a number: "))
print(list1)
print(sorted(list1)," :sorted list")
print(modified)
print(sorted(modified),": modified list")
|
c2faadf1267de8933b1fce5b64acd3c564ad95c3 | adwaithkj/random_problems_dynamicprog | /fib.py | 481 | 4 | 4 | def fib(n, db, data):
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 1
elif n in db:
return data[db.index(n)]
val = fib(n-1, db, data)+fib(n-2, db, data)
db.append(n)
data.append(val)
return val
def main():
n = int(input("Type in the number n and you will have the nth fibonacci number "))
db = []
data = []
f = fib(n, db, data)
print(f"The fibonacci number is {f}")
main()
|
b13dd7edaf3c6269f3d3fa90682eeeb989d78571 | TigerAppsOrg/TigerHost | /deploy/deploy/utils/click_utils.py | 586 | 4.1875 | 4 | import click
def prompt_choices(choices):
"""Displays a prompt for the given choices
:param list choices: the choices for the user to choose from
:rtype: int
:returns: the index of the chosen choice
"""
assert len(choices) > 1
for i in range(len(choices)):
click.echo('{number}) {choice}'.format(
number=i + 1,
choice=choices[i]
))
value = click.prompt('1-{}'.format(len(choices)), type=int) - 1
if value < 0 or value >= len(choices):
raise click.ClickException('Invalid choice.')
return value
|
81bfaa5b74312076cd2bd660ebb58a9cbb172664 | mingziV5/python_script | /thread_queue_ring.py | 1,092 | 3.65625 | 4 | #!/usr/bin/python
#coding:utf-8
from threading import Thread
from Queue import Queue
class TestRing(Thread):
def __init__(self,q,thread_num,thread_name):
Thread.__init__(self)
#self.q_out = q_out
#self.q_in = q_in
self.q = q
self.thread_num = thread_num
self.thread_name = thread_name
def run(self):
while True:
i,q_num = self.q.get()
if i==10000:
self.q.put((i,q_num))
print '%s is done' %self.thread_name
break
elif q_num%10 == self.thread_num and i != 10000:
i += 1
q_num += 1
print "put the i = %s,my name is %s" %(i,self.thread_name)
self.q.put((i,q_num))
else:
self.q.put((i,q_num))
def main():
q1 = Queue()
q1.put((1,1))
thread_list = []
for i in range(10):
t1 = TestRing(q1,i,str(i))
thread_list.append(t1)
t1.start()
for t in thread_list:
t.join
if __name__ == '__main__':
main()
|
5492a26a3881c41ce5ad9a013f9541d834146ac6 | shreyassgs00/Ciphers | /caesar_cipher/decrypt.py | 585 | 3.75 | 4 | #To decrypt the strings in encrypt.txt and write them to decrypt.txt
to_decrypt_file = open('encrypted.txt','r')
decrypt_file = open('decrypted.txt','w')
s = int(input('Enter the shift pattern to decrypt: '))
encrypted_lines = to_decrypt_file.readlines()
for a in encrypted_lines:
ans = ''
for i in range(0, len(a)):
if ord(a[i]) >= 97 and ord(a[i]) <= 122:
ans = ans + chr(ord(a[i])-32-s)
elif ord(a[i]) >= 65 and ord(a[i]) <= 90:
ans = ans + chr(ord(a[i])+32-s)
else:
ans = ans + a[i]
decrypt_file.write(ans)
|
b5659a82b681c6c80ecdc1ee2e217519f8b1a852 | Anny8910/Electricity-Consumption-vs-States | /plot.py | 813 | 3.5625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('Per capita consumption of electricity.csv')
print(df.head())
desc=df.describe()
print(desc)
print(df.columns)
df=df.drop(40,axis=0)#to remove all india data that is total
for each in desc.columns:
print('details of--',each)
print('mean = ', desc.iloc[1][each])
print('Standard Deviation = ', desc.iloc[2][each])
print('Max = ', desc.iloc[7][each])
print('Min = ', desc.iloc[3][each])
print()
plt.bar(df['Region/State/U.T.'],df[each],color='blue')
plt.xticks(rotation=90)
plt.ylabel('consumption of electricity(kwh)')
plt.xlabel(each)
plt.title('States vs Consumption of energy for '+ each)
plt.show() #this will show 6 different bar graphs for 6 different time period
|
ae3af6069669c629916b11f7771cccbebc83e89e | andidietz/python_data_structures | /14_compact/compact.py | 502 | 3.765625 | 4 | def compact(lst):
"""Return a copy of lst with non-true elements removed.
>>> compact([0, 1, 2, '', [], False, (), None, 'All done'])
[1, 2, 'All done']
"""
# Source: Accessing index in python for loop (6/21/2021): https://realpython.com/python-enumerate/
# Source: Understanding Enumrate args (6/21/2021): https://www.geeksforgeeks.org/enumerate-in-python/
for count, item in enumerate(lst, start=0):
if not item:
lst.pop(count)
return lst
|
e9c18facb40dc769063bc59a4364804ee16f88bf | vineet247/text-extractor | /src/desktop.py | 2,939 | 3.734375 | 4 | from tkinter import filedialog
from tkinter import *
from tkinter.filedialog import askopenfilename
from app import extract_from_folder, extract_from_file
from tkinter import messagebox;
def browse_button():
# Allow user to select a directory and store it in global var
# called folder_path
global folder_path
global folder_name
folder_name = ""
folder_name = filedialog.askdirectory()
#folder_path.set(folder_name)
#print(folder_name)
def browse_button_file():
global filename
filename = ""
filename = askopenfilename()
#print(filename)
#def lang_text_file():
# global textname
# textname = askopenfilename()
#print(textname)
def execute():
global save_file_name
global filename
global folder_name
global textname
save_file_name = ""
save_file_name = filedialog.askdirectory()
if len(filename) == 0 and len(folder_name) == 0:
messagebox.showinfo("Error", "No file or folder detected. Please select either a folder or a PDF file")
if len(filename) > 0 and len(folder_name) > 0:
messagebox.showinfo("Error", "Cannot select more than 1 file or folder. Please select either a folder or a PDF file")
filename = ""
folder_name = ""
textname = ""
else:
if len(filename) > 0:
#if len(textname) == 0:
# messagebox.showinfo("Error", "No language file detected. Please add a language file")
#else:
extract_from_file(filename, textname, save_file_name)
messagebox.showinfo("Saved", "File Saved Successfully")
filename = ""
textname = ""
if len(folder_name) > 0:
#if len(textname) == 0:
# messagebox.showinfo("Error", "No language file detected. Please add a language file")
#else:
extract_from_folder(folder_name, textname, save_file_name)
messagebox.showinfo("Saved", "File Saved Successfully")
folder_name = ""
textname = ""
root = Tk()
root.geometry("600x600")
folder_path = ""
filename = ""
textname = ""
folder_name = ""
save_file_name = ""
lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=5, column=2)
button2 = Button(text="For multiple PDF files, specify folder here", command=browse_button)
button2.place(relx=0.5, rely=0.3, anchor=CENTER)
lbl2 = Label(master=root,textvariable=filename)
lbl2.grid(row=2, column=2)
button3 = Button(text="Select single PDF file here", command=browse_button_file)
button3.place(relx=0.5, rely=0.4, anchor=CENTER)
lbl3 = Label(master=root,textvariable=textname)
lbl3.grid(row=3, column=2)
#button4 = Button(text="Enter language file here (.txt files)", command=lang_text_file)
#button4.place(relx=0.5, rely=0.5, anchor=CENTER)
button4 = Button(text="Execute and Save", command=execute)
button4.place(relx=0.5, rely=0.7, anchor=CENTER)
root.mainloop()
|
092c70f41ebe8ad994fe679742c76aa9af2e76f7 | MrZhangzhg/nsd_2018 | /nsd1811/python01/day04/check_idt.py | 606 | 3.515625 | 4 | import sys
import keyword
from string import ascii_letters, digits
first_chs = ascii_letters + '_'
other_chs = first_chs + digits
def check_idt(idt): # abc@123
if keyword.iskeyword(idt):
return '%s 是关键字' % idt
if not idt[0] in first_chs:
return '第1个字符不合法'
for ind, ch in enumerate(idt[1:]): # [(0, 'b'), (1, 'c'), (2, '@'), (3, '1'), (4, '2'), (5, '3')]
if ch not in other_chs:
return "第%s个字符不合法" % (ind + 2)
return '%s是合法的标识符' % idt
if __name__ == '__main__':
print(check_idt(sys.argv[1]))
|
702a6a7a507adab77dd080f235544229d6c219b6 | MrZhangzhg/nsd_2018 | /nsd1809/python2/day01/stack.py | 1,102 | 4.28125 | 4 | """
列表模拟栈结构
栈:是一个后进先出的结构
"""
stack = []
def push_it():
data = input('data to push: ').strip()
if data: # 如果字符串非空
stack.append(data)
def pop_it():
if stack: # 如果列表非空
print('from stack, popped \033[31;1m%s\033[0m' % stack.pop())
else:
print('\033[31;1mEmpty stack\033[0m')
def view_it():
print('\033[32;1m%s\033[0m' % stack)
def show_menu():
cmds = {'0': push_it, '1': pop_it, '2': view_it} # 将函数存入字典
prompt = """(0) push it
(1) pop it
(2) view it
(3) quit
Please input your choice(0/1/2/3): """
while True:
choice = input(prompt).strip()
if choice not in ['0', '1', '2', '3']:
print('Invalid choice. Try again.')
continue
if choice == '3':
break
cmds[choice]() # choice=0 => cmds[0]() =>pushit()
# if choice == '0':
# push_it()
# elif choice == '1':
# pop_it()
# else:
# view_it()
if __name__ == '__main__':
show_menu()
|
de1736077c5565ee27abb6868337ea2a84ee64a1 | MrZhangzhg/nsd_2018 | /nsd1808/python2/day03/oop.py | 761 | 3.796875 | 4 | class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def create_date(cls, date_str):
# tlist = date_str.split('-')
# year = int(tlist[0])
# month = int(tlist[1])
# day = int(tlist[2])
year, month, day = map(int, date_str.split('-'))
return cls(year, month, day)
@staticmethod
def is_date_valid(date_str):
year, month, day = map(int, date_str.split('-'))
return year < 4000 and 1 <= month <= 12 and 1 <= day <= 31
if __name__ == '__main__':
d1 = Date(2019, 1, 20)
print(d1.month)
d2 = Date.create_date('2019-1-21')
print(d2.year)
print(Date.is_date_valid('2019-13-21'))
|
01aaacdbb9d0efa13175bbb822dd7b7ff72c587b | MrZhangzhg/nsd_2018 | /nsd1810/python1/day02/while_continue.py | 260 | 3.90625 | 4 | # 计算1-100以内偶数之和
result = 0
counter = 0
while counter < 100:
counter += 1
# if counter % 2 == 1:
if counter % 2: # counter除以2的余数只有1或0,1是True,0是False
continue
result += counter
print(result)
|
a2040c08d3ed7057355f57cf9fbdb522d1096702 | MrZhangzhg/nsd_2018 | /nsd1807/python1/day02/game2.py | 413 | 3.734375 | 4 | import random
all_choice = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
computer = random.choice(all_choice)
player = input('请出拳(石头/剪刀/布): ')
print('你的出拳:', player, ', 计算机出拳:', computer)
if player == computer:
print('平局')
elif [player, computer] in win_list:
print('You WIN!!!')
else:
print('You LOSE!!!')
|
ea790c65632f47dd6d0e78d0f366b8b042d0b3ad | MrZhangzhg/nsd_2018 | /nsd1807/python1/day03/fibs_func.py | 819 | 4.15625 | 4 | # def generate_fib():
# fib = [0, 1]
#
# for i in range(8):
# fib.append(fib[-1] + fib[-2])
#
# print(fib)
#
# # generate_fib() # 调用函数,即将函数内的代码运行一遍
# # generate_fib()
# a = generate_fib()
# print(a) # 函数没有return语句,默认返回None
##############################
# def generate_fib():
# fib = [0, 1]
#
# for i in range(8):
# fib.append(fib[-1] + fib[-2])
#
# return fib
#
# alist = generate_fib()
# print(alist)
# blist = [i * 2 for i in alist]
# print(blist)
##############################
def generate_fib(n):
fib = [0, 1]
for i in range(n - 2):
fib.append(fib[-1] + fib[-2])
return fib
a = generate_fib(10)
print(a)
b = generate_fib(20)
print(b)
x = int(input('length: '))
c = generate_fib(x)
print(c)
|
fc0b8a09ad96e90490b28fae6374818a51bf7ed5 | MrZhangzhg/nsd_2018 | /nsd1808/python2/day02/day02.py | 2,405 | 3.828125 | 4 | # def foo():
# print('in foo')
# bar()
#
#
# def bar():
# print('in bar')
#
# if __name__ == '__main__':
# foo()
###############################
#
# def myfunc(*args): # *表示args是个元组
# print(args)
#
# def myfunc2(**kwargs): # **表示kwargs是个字典
# print(kwargs)
#
# if __name__ == '__main__':
# myfunc() # args=()
# myfunc('hello') # 参数将会放到元组中 args=('hello',)
# myfunc('hello', 123) # args=('hello', 123)
# myfunc2() # kwargs={}
# myfunc2(name='bob', age=23) # kwargs={'name': 'bob', 'age': 23}
##############################
# #
# def add(x, y):
# print(x + y)
#
# if __name__ == '__main__':
# add(10, 20)
# nums = [10, 20]
# add(nums[0], nums[1])
# add(*nums) # *nums表示把nums拆开
##############################
#
# def add(x, y):
# return x + y
#
# if __name__ == '__main__':
# print(add(10, 20))
#
# a = lambda x, y: x + y
# print(a(20, 30))
##############################
#
# import random
#
# def func1(x):
# return x % 2 # 结果是1或0,表示True和Flase
#
# def func2(x):
# return x * 2 + 1
#
# if __name__ == '__main__':
# nums = [random.randint(1, 100) for i in range(10)]
# print(nums)
# # filter实现过滤,将nums中的每一项当成func1的参数,func1的结果为真,则把数字留下,否则过滤掉
# print(list(filter(func1, nums)))
# print(list(filter(lambda x: x % 2, nums)))
# # map用来加工数据,将nums中的每一个项目作为func2的参数进行加工,得到结果
# print(list(map(func2, nums)))
# print(list(map(lambda x: x * 2 + 1, nums)))
##############################
#
# from functools import partial
#
# def add(a, b, c, d):
# print(a + b + c + d)
#
# if __name__ == '__main__':
# add(10, 20, 30, 5)
# add(10, 20, 30, 8)
# add(10, 20, 30, 9)
# myadd = partial(add, 10, 20, 30)
# myadd(5)
# myadd(8)
# myadd(9)
##############################
#
def func1(x):
if x == 1:
return 1 # 如果x是1,返回1
return x * func1(x - 1) # 否则,返加这个数乘以它下一个数的阶乘
# 5 * func1(4)
# 5 * 4 * func1(3)
# 5 * 4 * 3 * func1(2)
# 5 * 4 * 3 * 2 * func1(1)
# 5 * 4 * 3 * 2 * 1
if __name__ == '__main__':
print(func1(5))
print(func1(6))
|
ef21ec72f602453a7a0111302890bd6c85eb3d85 | MrZhangzhg/nsd_2018 | /nsd1808/python2/day03/toys4.py | 502 | 3.734375 | 4 | class PigToy:
def __init__(self, name, color):
self.name = name
self.color = color
def show_me(self):
print('Hi, my name is %s, I am %s' % (self.name, self.color))
class NewPigToy(PigToy):
def __init__(self, name, color, size):
# PigToy.__init__(self, name, color)
super(NewPigToy, self).__init__(name, color)
self.size = size
def walk(self):
print('walking...')
a = NewPigToy('piggy', 'pink', 'Middle')
print(a.name, a.size)
|
78f78f2e1925e85974f9c89988c04b48b71746db | MrZhangzhg/nsd_2018 | /nsd1811/python02/day01/try1.py | 486 | 3.53125 | 4 | try: # 把有可能发生异常的代码放到try中执行
num = int(input('number: '))
result = 100 / num
except (ValueError, ZeroDivisionError): # 用except捕获异常
print('无效的数字')
except (KeyboardInterrupt, EOFError):
print('\nBye-bye')
exit() # 程序序到exit就会退出,后续代码不再执行
else: # 没有发生异常才执行的语句
print(result)
finally: # 不管是否发生异常,都会执行的语句
print('Done')
|
81b8771788890aa2f6794dde1f7552b4c07a80cd | MrZhangzhg/nsd_2018 | /weekend1/py0102/for1.py | 550 | 3.90625 | 4 | astr = 'tom'
alist = [10, 20]
atuple = ('tom', 'jerry')
adict = {'name': 'tom', 'age': 20}
# for ch in astr:
# print(ch)
#
# for i in alist:
# print(i)
#
# for name in atuple:
# print(name)
#
# for key in adict:
# print(key, adict[key])
# range函数
print(range(10))
print(list(range(10)))
for i in range(10):
print(i)
# range只有一个参数,表示结束数字,开始默认为0,但是结束数字不包含
print(list(range(6, 11)))
print(list(range(1, 11, 2))) # 2是步长值
print(list(range(10, 0, -1)))
|
5ed42743a1c6a789d0cd39eb0945dbdc758be5fb | MrZhangzhg/nsd_2018 | /nsd1808/python2/day03/toys2.py | 589 | 3.734375 | 4 | class Vendor:
def __init__(self, company, ph):
self.company = company
self.phone = ph
def call(self):
print('Calling %s...' % self.phone)
class PigToy: # 定义玩具类
def __init__(self, name, color, company, ph):
self.name = name
self.color = color
self.vendor = Vendor(company, ph)
def show_me(self):
print('Hi, my name is %s, I am %s' % (self.name, self.color))
piggy = PigToy('Piggy', 'pink', 'tedu', '400-800-1234') # 创建实例
# piggy.show_me()
print(piggy.vendor.company)
piggy.vendor.call()
|
69b21bbb24cf992e9c0d4b50c0d68e9240a82df4 | MrZhangzhg/nsd_2018 | /nsd1811/python01/day03/forloop.py | 248 | 3.734375 | 4 | chs = 'hello'
alist = ['bob', 'alice']
atuple = (10, 20)
adict = {'name': 'tom', 'age': 23}
for ch in chs:
print(ch)
for name in alist:
print(name)
for i in atuple:
print(i)
for key in adict:
print('%s: %s' % (key, adict[key]))
|
bf2281c858a66bdc70cb6be934b5d8e42504ba1a | MrZhangzhg/nsd_2018 | /nsd1807/devops/day01/myfork.py | 339 | 3.9375 | 4 | import os
# print('开始')
# os.fork()
# print('你好')
# print('start')
# a = os.fork()
# if a:
# print('in parent')
# else:
# print('in child')
#
# print('end')
for i in range(3):
retval = os.fork()
if not retval:
print('hello world!')
exit() # 一旦遇到exit,进程将彻底结束
|
ca74db9ec4f2c69978919b8f28987638505ea69c | sealanguage/somePythonChallenges | /yahtzee1.py | 597 | 3.96875 | 4 | import random
# from operator import setitem
dice = []
reroll = []
dienums = random.randint(1, 6)
all_dice = 5
for value in range(all_dice):
dice.append(random.randint(1, 6))
print (dice)
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print "That's your Shopping List"
print (shopList)
# n = int(input("reroll which sep by space? "))
# reroll = n.split()
# print(reroll)
# for value in range(reroll):
# reroll.append(n)
# print(reroll)
dice[n] = random.randint(1, 6)
print (dice)
|
6cbf9d107e36dad6efbc143b4778260dea37f0c0 | sealanguage/somePythonChallenges | /string_loops5.py | 1,837 | 3.84375 | 4 | # a, b = input("Enter two of your lucky number: ").split()
T = int(input())
S = input() # S is a string of chars, it prints each letter in a word
splits = S.split()
print("1 ", splits)
lines = []
# lines = input().strip()
# print("2 ", lines)
# while True:
# line = S.split()
# if line:
# lines.append(line)
# else:
# break
# FinalText = '\n'.join(line)
# print("\n")
# print(lines)
# str.splitlines()
# lines = 0
# Ssplit = S.split()
# while lines < T:
# for word in Ssplit:
# print (word)
# lines +=1
# for words in S.input().split():
# # words = S.splitlines()
# print(words)
# my_string = "this is a string"
# for word in my_string.split():
# print (word)
# loop grab input run it and then grab the next input
# splits = S.split()
# print("splits :", splits)
# # for split in splits:
# # print("split :", split)
# print("The original string is : " + S) # Hacker
# S = input()
# # # loop grab input run it and then grab the next input
# # splits = S.split()
# print("The original string is : " + S) # Rank
# for split in splits:
# print("this ", splits)
# while (splits < T):
# print("split is ", split)
# trying to get the second string in the input-not working
# for split in S.split():
# print("split is: ", split)
# keep below, it works to separate the strings
# # use slice [] operator to iterate every other letter
# for letter in split[::2]:
# print(letter, end="")
# # use slice [] operator to get the missing letters
# print(end=" ")
# for letter in split[1::2]:
# print(letter, end="") |
9aa376fd604e2b891016b7c8847def98b1539416 | medialab/ural | /scripts/utils.py | 336 | 3.609375 | 4 | from timeit import default_timer as timer
class Timer(object):
def __init__(self, name="Timer"):
self.name = name
def __enter__(self):
self.start = timer()
def __exit__(self, *args):
self.end = timer()
self.duration = self.end - self.start
print("%s:" % self.name, self.duration)
|
40480382b93eeb0999228c54a12ee53b2c2ef638 | medialab/ural | /ural/classes/trie_dict.py | 5,238 | 3.65625 | 4 | # =============================================================================
# TrieDict
# =============================================================================
#
# A simple Python implementation of a (prefix, value) Trie.
#
NULL = object()
class TrieDictNode(object):
__slots__ = ("children", "value", "counter")
def __init__(self):
self.children = None
self.value = NULL
# Counts the number of items in the node's children
self.counter = 0
class TrieDict(object):
__slots__ = "__root"
def __init__(self):
self.__root = TrieDictNode()
def __len__(self):
return self.__root.counter
def __setitem__(self, prefix, value):
node = self.__root
visited_nodes = []
for token in prefix:
if node.children is None:
child = TrieDictNode()
node.children = {token: child}
visited_nodes.append(node)
node = child
continue
child = node.children.get(token)
if child is not None:
visited_nodes.append(node)
node = child
else:
child = TrieDictNode()
node.children[token] = child
visited_nodes.append(node)
node = child
if node.value is NULL:
for n in visited_nodes:
n.counter += 1
node.value = value
def get(self, prefix, default=None):
node = self.__root
for token in prefix:
if node.children is None:
return default
child = node.children.get(token)
if child is None:
return default
node = child
if node.value is not NULL:
return node.value
return default
def __getitem__(self, prefix):
node = self.__root
for token in prefix:
if node.children is None:
raise KeyError(prefix)
child = node.children.get(token)
if child is None:
raise KeyError(prefix)
node = child
if node.value is not NULL:
return node.value
raise KeyError(prefix)
def longest_matching_prefix_value(self, prefix):
node = self.__root
last_value = NULL
for token in prefix:
if node.value is not NULL:
last_value = node.value
if node.children is None:
break
child = node.children.get(token)
if child is None:
break
node = child
if node.value is not NULL:
return node.value
return last_value if last_value is not NULL else None
def items(self):
stack = [(self.__root, [])]
while len(stack) > 0:
node, prefix = stack.pop()
if node.value is not NULL:
yield (prefix, node.value)
if node.children is None:
continue
for token, child in node.children.items():
stack.append((child, prefix + [token]))
def prefixes(self):
stack = [(self.__root, [])]
while len(stack) > 0:
node, prefix = stack.pop()
if node.value is not NULL:
yield prefix
if node.children is None:
continue
for token, child in node.children.items():
stack.append((child, prefix + [token]))
def values(self):
stack = [self.__root]
while len(stack) > 0:
node = stack.pop()
if node.value is not NULL:
yield node.value
if node.children is None:
continue
stack.extend(node.children.values())
def __iter__(self):
return self.items()
def set_and_prune_if_shorter(self, prefix, value):
node = self.__root
visited_nodes = []
for token in prefix:
# Check if we try to add a longer prefix
if node.value is not NULL:
return
if node.children is None:
child = TrieDictNode()
node.children = {token: child}
visited_nodes.append(node)
node = child
continue
child = node.children.get(token)
if child is not None:
visited_nodes.append(node)
node = child
else:
child = TrieDictNode()
node.children[token] = child
visited_nodes.append(node)
node = child
# Trie already has longer prefixes of the prefix we are trying to add : we delete those prefixes and new (shortest) one
if node.children is not None:
node.children = None
for n in visited_nodes:
n.counter -= node.counter - 1
node.counter = 0
# We add a prefix with no longer prefixes in the Trie
elif node.value is NULL:
for n in visited_nodes:
n.counter += 1
node.value = value
|
111b6c2759bfd7676336db845106102f7b94fb00 | pythrick/python-javonico | /python_javonico/models/palestra.py | 922 | 3.609375 | 4 |
class Palestra:
__codigo: str = None
__tema: str = None
__descricao: str = None
def __init__(self, codigo: str, tema: str, descricao: str):
self.set_codigo(codigo)
self.set_tema(tema)
self.set_descricao(descricao)
def get_codigo(self):
return self.__codigo
def set_codigo(self, valor: str):
self.__codigo = valor
def get_tema(self):
return self.__tema
def set_tema(self, valor: str):
self.__tema = valor
def get_descricao(self):
return self.__descricao
def set_descricao(self, valor: str):
self.__descricao = valor
def imprimir(self):
print("----------------------------")
print("Imprimindo Palestra")
print("----------------------------")
print(f"Código: {self.__codigo}")
print(f"Tema: {self.__tema}")
print(f"Descrição: {self.__descricao}")
|
6ccce55fe0b842ffc006d85bceafde2849a9ffb8 | jzaldumbide/lab4 | /conteo.py | 174 | 3.671875 | 4 | contador=int(0)
frase =input("ingrese una frase \n")
fraux=frase.split (" ")
for i in fraux:
contador=contador+1
print("El numero de palabras ingresadas es"+str(contador))
|
a4dc65a8f1f19df3230fff9a879dcbf23d77201b | ElAnbals/Mision-08 | /listas.py | 1,768 | 3.5625 | 4 | def sumarAcumulado(lista):
listaSumada=[]
for k in (0,len(lista)+1):
contador=0
for x in range (0,k+1):
contador=contador+lista[k]
if k==x:
listaSumada.append(contador)
return listaSumada
def recortarLista(lista):
listaRecor=[]
for k in (1,len(lista),1):
listaRecor.append(lista[k])
return listaRecor
def estanOrdenados(lista):
verdadero = True
falso = False
for k in range(1,len(lista)+1):
if lista[k-1]<=lista[k]:
pass
else:
return falso
return verdadero
def sonAnagramas():
pass
def hayDuplicados(lista):
verdadero=True
falso=False
for x in range (0,len(lista)+1):
contador = 0
for k in range(0,len(lista)+1):
if lista[x] == lista[k]:
contador=contador+1
if contador ==2:
return falso
return verdadero
def borrarDuplicados(lista):
for x in range (0,len(lista)+1):
contador = 0
for k in range(0,len(lista)+1):
if lista[x] == lista[k]:
contador=contador+1
if contador ==2:
lista.pop(k)
return lista
def main():
lista = [] # Lista sin datos
numero = int(input("Valor [-1 para terminar el programa]: "))
while numero != -1:
# procesan
lista.append(numero)
numero = int(input("Valor [-1 para terminar el programa]: "))
sumarAcumulado(lista)
recortarLista(lista)
estanOrdenados(lista)
sonAnagramas()
estanOrdenados(lista)
hayDuplicados(lista)
borrarDuplicados(lista)
main()
|
f701b712294044a7f89048017be6f173094c0580 | insuajuan/snake_game | /main.py | 1,238 | 3.703125 | 4 | from turtle import Screen
import time
from snake import Snake
from food import Food
from scoreboard import Score
screen = Screen()
# Create Window
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)
# Instantiate Classes
snake = Snake()
food = Food()
score = Score()
# Key instructions
screen.listen()
screen.onkey(snake.up, "w")
screen.onkey(snake.down, "s")
screen.onkey(snake.left, "a")
screen.onkey(snake.right, "d")
# Move Snake
difficulty = []
game_on = True
while game_on:
screen.update()
time.sleep(0.1)
snake.move()
# Detect collision with food
if snake.head.distance(food) < 15:
food.refresh()
snake.extend()
score.increase_score()
# Detect collision with wall
limit_wall = 295
if snake.head.xcor() > limit_wall \
or snake.head.ycor() > limit_wall \
or snake.head.xcor() < -limit_wall \
or snake.head.ycor() < -limit_wall:
score.game_over()
game_on = False
# Detect collision with tail
for segment in snake.segments[1:]:
if snake.head.distance(segment) < 10:
score.game_over()
game_on = False
screen.exitonclick()
|
f57ac27ef8aa579c0a10eab584f72ca15d84f41d | manuel-delverme/games | /flaskTictacToe/blocks_src.py | 3,414 | 3.609375 | 4 | import random
from copy import deepcopy
import functools
def pick_random_move(board):
row = random.randint(0, 2)
column = random.randint(0, 2)
if board[row][column] != None:
return pick_random_move(board)
return [row, column]
def findEmptyCells(board):
empty_cells = [] # count_freeSpace or depth
for rowLoop in range(len(board)):
for columnLoop in range(len(board[rowLoop])):
if board[rowLoop][columnLoop] == ' ':
empty_cells.append((rowLoop, columnLoop))
return empty_cells
def game_turn(turn):
assert type(turn) == str
if turn == "X":
return "O"
else:
return "X"
def get_opponent(player):
"""Returns the opposite sign playes by the current agent"""
if player == 'X':
return 'O'
return 'X'
def check_winner(board):
# check for matches and winner
winner = None
for j in range(len(board)):
# check rows matches
if board[j][0] == "X":
if (board[j][1] == "X") and (board[j][2] == "X"):
winner = "X"
if board[j][0] == "O":
if (board[j][1] == "O") and (board[j][2] == "O"):
winner = "O"
# Check columns matches
if board[0][j] == "X":
if (board[1][j] == "X") and (board[2][j] == "X"):
winner = "X"
if board[0][j] == "O":
if (board[1][j] == "O") and (board[2][j] == "O"):
winner = "O"
# Check Left Diagonal matches
if board[0][0] == "X":
if (board[1][1] == "X") and (board[2][2] == "X"):
winner = "X"
if board[0][0] == "O":
if (board[1][1] == "O") and (board[2][2] == "O"):
winner = "O"
# Check Right Diagonal matches
if board[0][2] == "X":
if (board[1][1] == "X") and (board[2][0] == "X"):
winner = "X"
if board[0][2] == "O":
if (board[1][1] == "O") and (board[2][0] == "O"):
winner = "O"
return winner
def minimax2(board, turn):
# if game is over:
# return score
moves = findEmptyCells(board)
if turn == "X":
value = -99999999
for move in moves:
value = max(value, minimax2(board, "0"))
else:
value = 999999999
for move in moves:
value = min(value, minimax2(board, "X"))
return value
pass
def minimax(game, turn, coords=None):
if check_winner(game) == "X":
return 1, coords
elif check_winner(game) == "O":
return -1, coords
moves = []
for i in range(3):
for j in range(3):
if game[i][j] is None:
moves.append((i, j))
# Draw
if moves == []:
return 0, coords
if turn == "X":
score = -100, coords
for move in moves:
new_game = game.copy()
new_game[move[0]][move[1]] = "X"
new_score = minimax(new_game, "O", move)
if new_score[0] > score[0]:
score = new_score
return score
if turn == "O":
score = 100, coords
for move in moves:
new_game = game.copy()
new_game[move[0]][move[1]] = "O"
new_score = minimax(new_game, "X", move)
if new_score[0] < score[0]:
score = new_score
return score
|
cbb7499303ee47083a330a9e50f5b5af3c9a3756 | voooltexx/Summer_School2021 | /My Code/Calculator.py | 3,571 | 3.703125 | 4 | from tkinter import *
from tkinter import messagebox
def add_digit(digit):
value = calc.get() + digit
calc.delete(0, END)
calc.insert(0, value)
def add_operation(operation):
value = calc.get()
if value[-1] in '+-*/':
value = value[:-1]
value = value + operation
calc.delete(0, END)
calc.insert(0, value)
def clear():
value = calc.get()
value = value[:-1]
calc.delete(0, END)
calc.insert(0, value)
def calculate():
value = calc.get()
if len(value) and value [-1] in '+-*/':
value = value[:-1] + value[-1] + value [:-1]
if len(value):
try:
resulr = eval(value)
calc.delete(0, END)
calc.insert(0, resulr)
except ZeroDivisionError:
messagebox.showinfo('ERROR!', 'You cannot divide by zero!')
calc.delete(0, END)
except (NameError, SyntaxError):
messagebox.showinfo('ERROR!', 'Problems with syntax!')
calc.delete(0, END)
def make_digit_button(digit):
return Button(text=digit, font = ('Arial', 20), bd = 2, command=lambda : add_digit(digit))
def make_operation_button(operation):
return Button(text=operation, font = ('Arial', 20), bd = 2, command=lambda : add_operation(operation))
def make_calc_button(operation):
return Button(text=operation, font = ('Arial', 20), bd = 2, command=lambda : calculate())
def press_key(event):
if event.char.isdigit():
add_digit(event.char)
elif event.char in '+-*/':
add_operation(event.char)
elif event.char == '\r':
calculate()
elif event.char == '\x08':
clear()
root = Tk()
root.title("Calculator")
root.geometry("240x270")
root.bind('<Key>', press_key)
calc = Entry(root, justify=RIGHT, font = ('Arial', 15), width= 15)
calc.grid(row = 0, column = 0, columnspan=4, stick = 'we', padx = 2)
make_digit_button('1').grid(row = 1, column=0, stick = 'wens', padx = 2, pady = 2)
make_digit_button('2').grid(row = 1, column=1, stick = 'wens', padx = 2, pady = 2)
make_digit_button('3').grid(row = 1, column=2, stick = 'wens', padx = 2, pady = 2)
make_digit_button('4').grid(row = 2, column=0, stick = 'wens', padx = 2, pady = 2)
make_digit_button('5').grid(row = 2, column=1, stick = 'wens', padx = 2, pady = 2)
make_digit_button('6').grid(row = 2, column=2, stick = 'wens', padx = 2, pady = 2)
make_digit_button('7').grid(row = 3, column=0, stick = 'wens', padx = 2, pady = 2)
make_digit_button('8').grid(row = 3, column=1, stick = 'wens', padx = 2, pady = 2)
make_digit_button('9').grid(row = 3, column=2, stick = 'wens', padx = 2, pady = 2)
make_digit_button('0').grid(row = 4, column=1, stick = 'wens', padx = 2, pady = 2)
make_operation_button('+').grid(row = 1, column=3, stick = 'wens', padx = 2, pady = 2)
make_operation_button('-').grid(row = 2, column=3, stick = 'wens', padx = 2, pady = 2)
make_operation_button('*').grid(row = 3, column=3, stick = 'wens', padx = 2, pady = 2)
make_operation_button('/').grid(row = 4, column=3, stick = 'wens', padx = 2, pady = 2)
make_operation_button('.').grid(row = 4, column=2, stick = 'wens', padx = 2, pady = 2)
make_calc_button('=').grid(row = 4, column=0, stick = 'wens', padx = 2, pady = 2)
root.grid_columnconfigure(0,minsize = 60)
root.grid_columnconfigure(1,minsize = 60)
root.grid_columnconfigure(2,minsize = 60)
root.grid_columnconfigure(3,minsize = 60)
root.grid_rowconfigure(1,minsize = 60)
root.grid_rowconfigure(2,minsize = 60)
root.grid_rowconfigure(3,minsize = 60)
root.grid_rowconfigure(4,minsize = 60)
root.mainloop() |
1076b8facc5fcdddd9282ea7d257a82933bd52fa | voooltexx/Summer_School2021 | /My Code/GraphicsWindow.py | 1,580 | 3.703125 | 4 | from tkinter import*
import tkinter.font as font
clicks=0
def button_click():
global clicks
clicks += 1
button_text.set('Clicks: {}'.format(clicks))
root = Tk()
root.title('New Python Program!')
root.geometry('800x600')
root.configure(bg='#424242')
button_text = StringVar()
button_text.set('Make Kiriki: {}'.format(clicks))
button2_text = StringVar()
button2_text.set('Buy Manufacter 1 Level: {}'.format(clicks))
button3_text = StringVar()
button3_text.set('Buy Manufacter 2 Level: {}'.format(clicks))
gametitle = Label(text="NereaJLniy Zavod Kirikov",
font="Arial 32")
undergametitle = Label(text="PART ONE",
font=("Arial",
24, "bold"))
gametitle.config(bd=5, bg='#F8E6E0')
undergametitle.config(bd=10, bg='#F5BCA9')
gametitle.place(relx=.35, rely=.025)
undergametitle.place(relx=.737, rely=.14)
balance = Label(text='Your Balance Is:',
font='Arial 32')
balance.place(relx=.01, rely=.9)
balance.config(bg='#FA5858')
def buy_manufacter():
pass
btn = Button (textvariable=button_text, bg='#088A08', command=button_click)
btn2 = Button (textvariable=button2_text, command=button_click)
btn3 = Button (textvariable=button3_text, command=button_click)
btn.place(relx = .2, rely = .3, anchor = 'c', height = 50, width = 250)
btn2.place(relx = .2, rely = .4, anchor = 'c', height = 50, width = 250)
btn3.place(relx = .2, rely = .5, anchor = 'c', height = 50, width = 250)
myFont = font.Font(weight='bold')
myFont = font.Font(size=10)
btn['font'] = myFont
btn2['font'] = myFont
btn3['font'] = myFont
root.mainloop() |
0263e18809fea766f9455be0853036079af1736f | mjs139/PythonPractice | /Kaggle Titanic Competition.py | 8,668 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Kaggle Titanic Competition
#
# In this project, I will compete in the Kaggle Titanic Competition.
# In[12]:
import pandas as pd
train = pd.read_csv("train.csv")
holdout = pd.read_csv("test.csv")
print(train.shape)
train.head()
# ## Loading Functions
# In[13]:
# %load functions.py
def process_missing(df):
"""Handle various missing values from the data set
Usage
------
holdout = process_missing(holdout)
"""
df["Fare"] = df["Fare"].fillna(train["Fare"].mean())
df["Embarked"] = df["Embarked"].fillna("S")
return df
def process_age(df):
"""Process the Age column into pre-defined 'bins'
Usage
------
train = process_age(train)
"""
df["Age"] = df["Age"].fillna(-0.5)
cut_points = [-1,0,5,12,18,35,60,100]
label_names = ["Missing","Infant","Child","Teenager","Young Adult","Adult","Senior"]
df["Age_categories"] = pd.cut(df["Age"],cut_points,labels=label_names)
return df
def process_fare(df):
"""Process the Fare column into pre-defined 'bins'
Usage
------
train = process_fare(train)
"""
cut_points = [-1,12,50,100,1000]
label_names = ["0-12","12-50","50-100","100+"]
df["Fare_categories"] = pd.cut(df["Fare"],cut_points,labels=label_names)
return df
def process_cabin(df):
"""Process the Cabin column into pre-defined 'bins'
Usage
------
train process_cabin(train)
"""
df["Cabin_type"] = df["Cabin"].str[0]
df["Cabin_type"] = df["Cabin_type"].fillna("Unknown")
df = df.drop('Cabin',axis=1)
return df
def process_titles(df):
"""Extract and categorize the title from the name column
Usage
------
train = process_titles(train)
"""
titles = {
"Mr" : "Mr",
"Mme": "Mrs",
"Ms": "Mrs",
"Mrs" : "Mrs",
"Master" : "Master",
"Mlle": "Miss",
"Miss" : "Miss",
"Capt": "Officer",
"Col": "Officer",
"Major": "Officer",
"Dr": "Officer",
"Rev": "Officer",
"Jonkheer": "Royalty",
"Don": "Royalty",
"Sir" : "Royalty",
"Countess": "Royalty",
"Dona": "Royalty",
"Lady" : "Royalty"
}
extracted_titles = df["Name"].str.extract(' ([A-Za-z]+)\.',expand=False)
df["Title"] = extracted_titles.map(titles)
return df
def create_dummies(df,column_name):
"""Create Dummy Columns (One Hot Encoding) from a single Column
Usage
------
train = create_dummies(train,"Age")
"""
dummies = pd.get_dummies(df[column_name],prefix=column_name)
df = pd.concat([df,dummies],axis=1)
return df
# In[14]:
def process(df):
df = process_missing(df)
df = process_age(df)
df = process_fare(df)
df = process_titles(df)
df = process_cabin(df)
for col in ["Age_categories","Fare_categories",
"Title","Cabin_type","Sex"]:
df = create_dummies(df,col)
return df
# In[15]:
train = process(train)
holdout = process(holdout)
print(train.shape)
train.head()
# ## Exploring the Data
#
# I am going to examine the two columns that contain information about the family members each passenger has onboard: SibSp and Parch. These columns count the number of siblings/spouses and the number of parents/children each passenger has onboard respectively.
# In[17]:
explore = train[["SibSp", "Parch", "Survived"]].copy()
explore.info()
# In[18]:
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
explore.drop("Survived",axis=1).plot.hist(alpha=0.5,bins=8)
plt.show()
# We can see that our data is heavily skewed right.
#
# I will combine these columns and look at the resulting distribution of values and survival rate
# In[20]:
explore["combined"] = explore["SibSp"] + explore["Parch"]
explore.drop("Survived",axis=1).plot.hist(alpha=0.5,bins=10)
plt.xticks(range(11))
plt.show()
# In[22]:
import numpy as np
for col in explore.columns.drop("Survived"):
pivot = explore.pivot_table(index=col,values="Survived")
pivot.plot.bar(ylim=(0,1),yticks=np.arange(0,1,.1))
plt.axhspan(.3, .6, alpha=0.2, color='red')
plt.show()
# We can see that if you had no family member onboard, you were more likely to die.
#
# Based off this, I will create a new feature: was the passenger alone. This will be a binary column with a 1 representing that the passenger had no family members onboard.
# In[46]:
def isalone(df):
df["isalone"] = 0
df["combined"] = df["SibSp"] + df["Parch"]
bool_values = df["combined"] == 0
df.loc[bool_values, "isalone"] = 1
df = df.drop("combined", axis = 1)
return df
# In[47]:
train = isalone(train)
holdout = isalone(holdout)
train.head()
# ## Feature Selection
#
# I will create a function that automates selecting the best performing features using recursive feature elimination using Random Forest algorithm.
# In[48]:
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import RFECV
def select_features(df):
#remove non-numeric columns and null values
df = df.select_dtypes([np.number]).dropna(axis=1)
all_X = df.drop(["PassengerId", "Survived"], axis = 1)
all_y = df["Survived"]
clf = RandomForestClassifier(random_state=1)
selector = RFECV(clf,cv=10)
selector.fit(all_X,all_y)
best_columns = list(all_X.columns[selector.support_])
print("Best Columns \n"+"-"*12+"\n{}\n".format(best_columns))
return best_columns
# In[49]:
best_cols = select_features(train)
# In[50]:
len(best_cols)
# ## Model Selection and Tuning
#
# I will write a function to do the heavy lifting of model selection and tuning. The function will use three different algorithms and use grid search to train using different combinations of hyperparamters to find the best performing model.
#
# I will return a list of dictionaries to see which was the most accurate.
# In[61]:
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
def select_model(df, features):
all_X = df[features]
all_y = df["Survived"]
models = [
{
"name": "LogisticRegression",
"estimator": LogisticRegression(),
"hyperparameters":
{
"solver": ["newton-cg", "lbfgs", "liblinear"]
}
},
{
"name": "KNeighborsClassifier",
"estimator": KNeighborsClassifier(),
"hyperparameters":
{
"n_neighbors": range(1,20,2),
"weights": ["distance", "uniform"],
"algorithm": ["ball_tree", "kd_tree", "brute"],
"p": [1,2]
}
},
{
"name": "RandomForestClassifier",
"estimator": RandomForestClassifier(random_state=1),
"hyperparameters":
{
"n_estimators": [4, 6, 9],
"criterion": ["entropy", "gini"],
"max_depth": [2, 5, 10],
"max_features": ["log2", "sqrt"],
"min_samples_leaf": [1, 5, 8],
"min_samples_split": [2, 3, 5]
}
}
]
for model in models:
print(model["name"])
print('\n')
grid = GridSearchCV(model["estimator"], param_grid = model["hyperparameters"], cv = 10)
grid.fit(all_X, all_y)
model["best_params"] = grid.best_params_
model["best_score"] = grid.best_score_
model["best_model"] = grid.best_estimator_
print("Best Score: {}".format(model["best_score"]))
print("Best Parameters: {}\n".format(model["best_params"]))
return models
# In[62]:
result = select_model(train,best_cols)
# ## Automating Kaggle Submission
#
# I will now create a function to automate my Kaggle submissions
# In[66]:
def save_submission_file(model, cols, filename="submission.csv"):
holdout_data = holdout[cols]
predictions = model.predict(holdout_data)
holdout_ids = holdout["PassengerId"]
submission_df = {"PassengerId": holdout_ids,
"Survived": predictions}
submission = pd.DataFrame(submission_df)
submission.to_csv(filename,index=False)
best_rf_model = result[2]["best_model"]
save_submission_file(best_rf_model,best_cols)
|
2609c2b1f06d647b086493c1294a1652787cefd8 | FranciscoValadez/Course-Work | /Python/CS119-PJ 6 - Simple Calculator/PJ 6 - Simple Calculator/PJ_6___Simple_Calculator.py | 1,900 | 4.5 | 4 | # Author: Francisco Valadez
# Date: 1/23/2021
# Purpose: A simple calculator that shows gives the user a result based on their input
#This function is executed when the user inputs a valid operator
def Results(num1, num2, operator):
if operator == '+':
print("Result:", num1, operator, num2, "=", (num1 + num2))
elif operator == '-':
print("Result:", num1, operator, num2, "=", (num1 - num2))
elif operator == '*':
print("Result:", num1, operator, num2, "=", (num1 * num2))
elif operator == '/':
if num2 == 0: #checks if the second number is zero
print("The second number cannot be zero!")
else:
print("Result:", num1, operator, num2, "=", (num1 / num2))
elif operator == '**':
print("Result:", num1, operator, num2, "=", (num1 ** num2))
elif operator == '%':
if num2 == 0: #checks if the second number is zero
print("The second number cannot be zero!")
else:
print("Result:", num1, operator, num2, "=", (num1 % num2))
else:
print("Sorry,", operator, "is not a valid operator!")
#Prints the welcom message
print("Welcome to use the Simple Calculator of Francisco Valadez!")
counter = 0
operator = ''
#The while loop below will not stop until the user enter '@' for the operator
while operator != '@':
counter +=1
print (counter, "="*40)
num1 = float(input("Enter your first number: "))
operator = input("Enter your operator(@ to stop): ")
num2 = float(input("Enter your second number: "))
#If the user does not want to exit then this bit of code is run
if operator != '@':
Results(num1, num2, operator) #sends the user's input to a function
else: #Prints the goodbye message
print(counter + 1, "="*40)
print("Thank you for playing this Simple Calculator of Francisco Valadez!")
print(counter + 2, "="*40)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.