blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
fb56b8ce1d1987049f9cc36b48efaf0a445d7ecf | seblogapps/coursera_python | /Part 2 - Week 1/MemoryCardGame.py | 3,403 | 3.625 | 4 | # "Memory Card Game" mini-project
# Sebastiano Tognacci
import simplegui
import random
# Define constants (can resize canvas if needed)
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 100
CARD_WIDTH = CANVAS_WIDTH / 16.0
CARD_HEIGHT = CANVAS_HEIGHT
FONT_SIZE = CARD_WIDTH
LINE_WIDTH = CARD_WIDTH - 1
# Define global variables
deck1 = range(8)
deck2 = range(8)
# Concatenate the two deck of cards
deck = deck1 + deck2
# List to store the last two selected cards
selected_card = [None] * 2
# List to store the last two selected cards indexes
selected_card_idx = [None] * 2
# helper function to initialize globals
def new_game():
global deck, game_state, turn, exposed
# Shuffle deck
random.shuffle(deck)
# Card exposed list (True/False), initialize all to face down
exposed = [False]*len(deck)
# Game state (0 = no card flipped,1 = one card flipped ,2 = two cards flipped)
game_state = 0
# Initial turn count
turn = 0
# define event handlers
def mouseclick(pos):
global game_state, selected_cards, selected_cards_idx, turn
# Translate pos to index in the deck:
pos_index = pos[0] // CARD_WIDTH
# First click, flip one card face up
if game_state == 0:
exposed[pos_index] = True
selected_card[0] = deck[pos_index]
selected_card_idx[0] = pos_index
game_state = 1
# Second click, flip second card face up
elif game_state == 1:
if not exposed[pos_index]:
exposed[pos_index] = True
selected_card[1] = deck[pos_index]
selected_card_idx[1] = pos_index
game_state = 2
turn += 1
# Third click, check if cards paired, flip one card
else:
# Flip one card,
if not exposed[pos_index]:
# If previously two selected cards are not paired, flip them face down
if selected_card[0] is not selected_card[1]:
exposed[selected_card_idx[0]] = exposed[selected_card_idx[1]] = False
# Flip card, store his value and index
exposed[pos_index] = True
selected_card[0] = deck[pos_index]
selected_card_idx[0] = pos_index
game_state = 1
# cards are logically 50x100 pixels in size
def draw(canvas):
# Update current turn text
label.set_text('Turns = '+str(turn))
# First position where to draw first card and first box (made with a thick line)
card_x_pos = CARD_WIDTH // 5 #10
box_x_pos = CARD_WIDTH // 2 #25
for card_index in range(len(deck)):
#Draw card face up or face down based on exposed list
if exposed[card_index]:
canvas.draw_text(str(deck[card_index]), (card_x_pos,CARD_HEIGHT * 0.7), FONT_SIZE, 'White')
else: # Flip card down (draw green rectangle)
canvas.draw_line((box_x_pos, 0), (box_x_pos, CARD_HEIGHT), LINE_WIDTH, 'Green')
# Move positions of elements 50 pixel on the right of last position
card_x_pos+=CARD_WIDTH
box_x_pos+=CARD_WIDTH
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", CANVAS_WIDTH, CANVAS_HEIGHT)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = 0")
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start() |
a9bc7c1de42cf3bc67125581a6c8d402faa70ea9 | rfolk/Project-Euler | /problem92.py | 1,523 | 3.8125 | 4 | #! /usr/bin/env python3.3
# Russell Folk
# July 9, 2013
# Project Euler #92
# A number chain is created by continuously adding the square of the digits in
# a number to form a new number until it has been seen before.
#
# For example,
# 44 → 32 → 13 → 10 → 1 → 1
# 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
# Therefore any chain that arrives at 1 or 89 will become stuck in an endless
# loop. What is most amazing is that EVERY starting number will eventually
# arrive at 1 or 89.
#
# How many starting numbers below ten million will arrive at 89?
import time
squares = []
numbers = []
start = time.perf_counter()
for i in range ( 10 ) :
squares.append ( i * i )
for i in range ( 568 ) :
numbers.append ( 0 )
numbers [ 1 ] = -1
numbers [ 89 ] = 1
def squareOfDigits ( n ) :
sumOfSquares = 0
while n >= 1 :
sumOfSquares += squares[ n % 10 ]
n = int ( n / 10 )
return sumOfSquares
def chainDigits ( n ) :
if numbers [ n ] == -1 :
return False
if numbers [ n ] == 1 :
return True
#print ( n )
if chainDigits ( squareOfDigits ( n ) ) :
numbers [ n ] = 1
return True
else :
numbers [ n ] = -1
return False
success = 0
for i in range ( 2, 10000001 ) :
n = i
if i > 567 :
n = squareOfDigits ( i )
if chainDigits ( n ) :
success += 1
elapsed = ( time.perf_counter() - start )
print ( "The number of chains that end in 89 is " + str ( success ) )
print ( "Calculated in: " + str ( elapsed ) + " seconds." )
|
e773f8fe3492f330395e0d2c44900b9b96f75b63 | rfolk/Project-Euler | /problem65.py | 1,050 | 3.796875 | 4 | #! /usr/bin/env python3.3
# Russell Folk
# December 3, 2012
# Project Euler #65
# http://projecteuler.net/problem=65
import time
limit = 100
def digitSum ( n ) :
"""
Adds the sum of the digits in a given number 'n'
"""
return sum ( map ( int , str ( n ) ) )
def calceNumerator ( term , numeratorN1 , numeratorN2 ) :
"""
Calculates the numerator of e to the required term
"""
if term == limit :
if term % 3 == 0 :
return ( 2 * int ( term / 3 ) * numeratorN1 ) + numeratorN2
return numeratorN1 + numeratorN2
multiplier = 1
if term % 3 == 0 :
multiplier = 2 * int ( term / 3 )
numerator = multiplier * numeratorN1 + numeratorN2
return calceNumerator ( term + 1 , numerator , numeratorN1 )
start = time.perf_counter()
number = calceNumerator ( 2 , 2 , 1 )
total = digitSum ( number )
elapsed = ( time.perf_counter() - start )
print ( "The digit sum of the numerator of the 100th convergent of e is: " +
str ( total ) + "." )
print ( "Calculated in: " + str ( elapsed ) + " seconds." )
|
7994be2f3282be98f6ff2ad6f63a8e18f39a5833 | siukwan/python-programming | /network/chapter1/1_13a_echo_server.py | 1,111 | 3.671875 | 4 | import socket
import sys
import argparse
host = 'localhost'
data_payload = 2048
backlog = 5
def echo_server(port):
"""A simple echo server """
#Create a TCP socket
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Enable reuse address/port
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
#Bind the socket to the port
server_address = (host,port)
print "Starting up echo server on %s port %s" %server_address
sock.bind(server_address)
#Listen to clients, backlog argument specifies the max no. of queued connections
sock.listen(backlog)
while True:
print "Waiting to receive message from client"
client, address = sock.accept()
data = client.recv(data_payload)
if data:
print "Data: %s" %data
client.send(data)
print "sent %s bytes back to %s" % (data,address)
#end connection
client.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Socket Server Example')
parser.add_argument('--port',action="store",dest = "port",type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
echo_server(port)
|
49893875d1c65cf248f45912a31f9552042b0bd3 | sudhasr/Competitive_Coding_2 | /TwoSum.py | 401 | 3.625 | 4 | #One pass solution. Accepted on Leetcode
#Time complexity - O(n)
#space complexity - O(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict1 = {}
for i in range(0,len(nums)):
if (target - nums[i]) in dict1:
return [i,dict1[target-nums[i]]]
else:
dict1[nums[i]] = i
return [] |
989514af8deb8d7d68c51f0a1a0983cf04629656 | cwormsl2-zz/2PlayerPongGame | /cwormsl2Pong.py | 4,268 | 3.625 | 4 | from Ball import Ball
from Paddle import Paddle
from graphics import *
from time import sleep
"""
Caitlin Wormsley 12/14/12
This prgorams runs the game Pong while calling a Ball class and a Paddle class.
Along with the minimum requirements, this game has a background and is a two player version.
"""
class Pong:
def __init__(self):
#creates the window, the ball, the two paddles, and draws the background and the scoreboard.
self.win = GraphWin("Pong", 800, 400)
self.background = Image(Point(400,200),"pingpong.gif")
self.background.draw(self.win)
self.ball=Ball(self.win)
self.paddle = Paddle(self.win,740,150,750,250,"red")
self.paddle1 = Paddle(self.win, 60, 150,70,250,"blue")
self.radius = self.ball.getRadius()
self.scoreboard = Text(Point(400, 50), "")
self.scoreboard.setSize(12)
self.scoreboard.setTextColor("white")
self.scoreboard.draw(self.win)
y = 200
self.middle = self.paddle.move(self.win, y)
self.middle1 = self.paddle1.move(self.win,y)
def checkContact(self):
#gets the values for the top and bottom of the paddles
self.top = self.paddle.getMiddle()- (self.paddle.getHeight()/2)
self.bot = self.paddle.getMiddle() +(self.paddle.getHeight()/2)
self.top1 = self.paddle1.getMiddle() - (self.paddle1.getHeight()/2)
self.bot1 = self.paddle1.getMiddle() + (self.paddle1.getHeight()/2)
#gets the values of the left and right edges of the ball
right = self.ball.getCenter().getX()+self.radius
left = self.ball.getCenter().getX()-self.radius
ballHeight = self.ball.getCenter().getY()
touch = right - self.frontedge
touch1 = self.frontedge1 - left
#if the ball touches either paddle it returns true
if (0 <= touch <= 10) or (0<= touch1 <= 10):
if(self.top < ballHeight <self.bot) and self.ball.moveRight():
return True
elif (self.top1 < ballHeight < self.bot1) and self.ball.moveLeft():
return True
else:
return False
def gameOver(self):
self.frontedge = self.paddle.getEdge()
self.frontedge1 = self.paddle1.getEdge()
ballWidth = self.ball.getCenter().getX()
#returns true if the ball passes either of the paddles
if (ballWidth > self.frontedge):
return True
elif(ballWidth < self.frontedge1):
return True
else:
return False
def play(self):
click = self.win.getMouse()
y = click.getY()
end = self.gameOver()
contact = self.checkContact()
self.hits = 0
self.level = 1
while not end:
#moves the paddles based on the user's click point
#if the ball is moving right the right paddle moves
#if the ball is moving left the left paddle moves
click = self.win.checkMouse()
if click != None and self.ball.moveRight():
y = click.getY()
self.paddle.move(self.win, y)
elif click != None and self.ball.moveLeft():
y = click.getY()
self.paddle1.move(self.win, y)
#moves the ball and reverses the X direction of the ball
self.ball.move(self.win)
sleep(0.025)
contact = self.checkContact()
if contact == True :
self.ball.reverseX()
self.hits = self.hits+1
#increases ball speed after every 5 hits
if self.hits%5==0:
self.ball.goFaster()
self.level=self.level+1
self.scoreboard.setText(("Hits:",self.hits, "Level:", self.level))
end = self.gameOver()
self.scoreboard = Text(Point(400, 100),"You Lost")
self.scoreboard.setSize(12)
self.scoreboard.setTextColor("white")
self.scoreboard.draw(self.win)
self.win.getMouse()
self.win.close()
def main():
p =Pong()
p.play()
main()
|
7b4c2a9f79f8876ab091a03d83e10918d7cf358a | chinaglia-rafa/sorting | /classes/QuickSort.py | 906 | 3.578125 | 4 | from Sorter import *
from random import randint
def partition(lst, start, end, pivot):
lst[pivot], lst[end] = lst[end], lst[pivot]
store_index = start
for i in range(start, end):
if lst[i] < lst[end]:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort(lst, start, end):
if start >= end:
return lst
pivot = (start + end)//2
new_pivot = partition(lst, start, end, pivot)
quick_sort(lst, start, new_pivot - 1)
quick_sort(lst, new_pivot + 1, end)
class QuickSort(Sorter):
def __init__(self, entrada):
super().__init__("QuickSort", entrada)
def sort(self):
entrada = self.getEntrada()[:]
quick_sort(entrada, 0, len(entrada) - 1)
self.setSaida(entrada)
return entrada
|
b2427bd9bf568696217c5e0dd1db531d8472cb5e | kamadforge/ranking | /algorithms/breadth_first_search.py | 441 | 3.9375 | 4 | BFS(v):
Q = Queue()
Q.add(v)
visited = set()
visted.add(v) #Include v in the set of elements already visited
while (not IsEmpty(Q)):
w = Q.dequeue() #Remove a single element from Q and store it in w
for u in w.vertices(): #Go through every node w is adjacent to.
if (not u in visited): #Only do something if u hasn't already been visited
visited.add(u)
Q.add(u) |
26cf949e46bd2bb958eca1241fe25beef76bbb1d | kamadforge/ranking | /algorithms/binary_tree.py | 1,273 | 4.25 | 4 | class Tree:
def __init__(self):
self.root=None
def insert(self, data):
if not self.root:
self.root=Node(data)
else:
self.root.insert(data)
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Use the insert method to add nodes
# root = Node(12)
# root.insert(6)
# root.insert(14)
# root.insert(3)
# root.PrintTree()
#second way
tree=Tree()
tree.insert(3)
tree.insert(10)
tree.insert(12)
tree.insert(5)
tree.insert(6)
tree.insert(11)
tree.root.PrintTree()
|
a64c513cd683163b5596310bf0c15c39b83e2e3d | remnestal/eppu | /keyboard.py | 1,007 | 4.09375 | 4 | import curses
class Keyboard(object):
""" Simple keyboard handler """
__key_literals = ['q', 'w', 'e', 'f', 'j', 'i', 'o', 'p']
__panic_button = ' '
def __init__(self, stdscr):
self.stdscr = stdscr
def next_ascii(self):
""" Returns the next ascii code submitted by the user """
sequence = self._next_sequence()
return chr(sum(2**i for i, bit in enumerate(sequence) if bit))
def _next_sequence(self):
""" Get the next key sequence entered by the user """
key_sequence = [False] * len(self.__key_literals)
while True:
try:
key = self.stdscr.getkey()
if key == self.__panic_button:
# submit sequence when the panic button is pressed
return key_sequence
else:
index = self.__key_literals.index(key)
key_sequence[index] = not key_sequence[index];
except:
pass
|
2185999943f7891d33a7519159d3d08feba8e14d | tim-jackson/euler-python | /Problem1/multiples.py | 356 | 4.125 | 4 | """multiples.py: Exercise 1 of project Euler.
Calculates the sum of the multiples of 3 or 5, below 1000. """
if __name__ == "__main__":
TOTAL = 0
for num in xrange(0, 1000):
if num % 5 == 0 or num % 3 == 0:
TOTAL += num
print "The sum of the multiples between 3 and 5, " \
"below 1000 is: " + str(TOTAL)
|
7588f35f10bea6d457e9058d21b41d8fff329fe9 | karthik137/tensorflow | /housing_prices_byprice.py | 787 | 3.75 | 4 | import tensorflow as tensor
import numpy as np
from tensorflow import keras
'''
Housing Price Condition
One house cost --> 50K + 50K per bedroom
2 bedroom cost --> 50K + 50 * 2 = 150K
3 bedroom cost --> 50K + 50 * 3 = 200K
.
.
.
7 bedroom cost --> 50K + 50 * 4 = 400K
'''
'''
Training set to be given
xs = [100,150,200,250,300,350]
ys = [1,2,3,4,5,6]
'''
# Create model
model = tensor.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
xs = np.array([1.0,2.0,3.0,4.0,5.0,6.0],dtype=float)
ys = np.array([100.0,150.0,200.0,250.0,300.0,350.0],dtype=float)
# Train the neural network
model.fit(xs, ys, epochs=1000)
print("Predicting for house with number of bedrooms = 7")
print(model.predict([7.0]))
|
ac4244195cf8ecf1330621bd31773f3b211f4d5c | HaNuNa42/pythonDersleri | /python dersleri/tipDonusumleri.py | 1,286 | 4.1875 | 4 | #string to int
x = input("1.sayı: ")
y = input("2 sayı: ")
print(type(x))
print(type(y))
toplam = x + y
print(toplam) # ekrana yazdirirken string ifade olarak algiladigindan dolayı sayilari toplamadi yanyana yazdi bu yuzden sonuc yanlis oldu. bu durumu duzeltmek için string'ten int' veri tipine donusturmemiz gerek
print("doğrusu şöyle olmalı")
toplam = int(x) + int(y)
print(toplam)
print("---------------")
a = 10
b = 4.1
isim = "hatice"
ogrenciMi = True
print(type(a))
print(type(b))
print(type(isim))
print(type(ogrenciMi))
print("---------------")
#int to float
a = float(a) # int olan a degiskeni floata donusturduk
print(a)
print(type(a)) # donusup donusmedigini kontrol edelim
print("---------------")
#float to int
a = int(b) # float olan a degiskeni inte donusturduk
print(b)
print(type(b))
print("---------------")
# bool to string
ogrenciMi = str(ogrenciMi) # bool olan a degiskeni stringe donusturduk
print(ogrenciMi)
print(type(ogrenciMi))
print("---------------")
#bool to int
ogrenciMi = int(ogrenciMi) # bool olan a degiskeni inte donusturduk
print(ogrenciMi)
print(type(ogrenciMi)) |
74d037e74d7f602d96e5c07931ac5f561eab0359 | mehoil1/Lesson-10 | /News_json.py | 726 | 3.5625 | 4 | import json
def ten_popular_words():
from collections import Counter
with open('newsafr.json', encoding='utf-8') as f:
data = json.load(f)
words = data['rss']['channel']['items']
descriptions = []
for i in words:
descriptions.append(i['description'].split())
format_description = []
for word in sum(descriptions, []):
if len(word) > 6:
format_description.append(word.lower())
Counter = Counter(format_description)
words = Counter.most_common(10)
for word in words:
print(f'Слово: "{word[0]}" встречается: {word[1]} раз')
ten_popular_words()
|
c62c8cac3dd6d0f918755eea1d4a28c025a4afac | masterfabela/Estudios | /FRMCode/DI/Exame Python/romaymendezfrancisco/MetodosDB.py | 2,337 | 3.53125 | 4 | import sqlite3
try:
"""datos conexion"""
bbdd = 'frm'
conex = sqlite3.connect(bbdd)
cur = conex.cursor()
print("Base de datos conectada.")
except sqlite3.OperationalError as e:
print(e)
def pechar_conexion():
try:
conex.close()
print("Pechando conexion coa BD.")
except sqlite3.OperationalError as e:
print(e)
def consultar_pacientes():
try:
cur.execute("select * from paciente")
listado = cur.fetchall()
conex.commit()
print("Pacientes")
return listado
except sqlite3.Error as e:
print("Erro na recuperacion dos pacientes")
print(e)
conex.rollback()
def consultar_medidas():
try:
cur.execute("select * from medida")
listado = cur.fetchall()
conex.commit()
print("Medidas")
return listado
except sqlite3.Error as e:
print("Erro na recuperacion das medidas")
print(e)
conex.rollback()
def insert_paciente(fila,lblavisos):
try:
cur.execute("insert into paciente(dni,nome,sexo) values (?,?,?)", fila)
conex.commit()
lblavisos.show()
lblavisos.set_text('Fila ' + fila[0] + ' engadida.')
except sqlite3.OperationalError as e:
print(e)
conex.rollback()
def insert_medida(fila,lblavisos):
try:
cur.execute("insert into medida (dni,peso,talla,imc,fecha,clasificacion) values (?,?,?,?,?,?)", fila)
conex.commit()
lblavisos.show()
lblavisos.set_text('Fila ' + fila[0] + ' engadida.')
except sqlite3.OperationalError as e:
print(e)
conex.rollback()
def update_paciente(fila, lblavisos):
try:
cur.execute("update paciente set nome = ?, sexo = ? where dni = ? ;",fila)
conex.commit()
lblavisos.show()
lblavisos.set_text('Fila ' + fila[2] + ' modificada.')
except sqlite3.OperationalError as e:
print(e)
conex.rollback()
def delete_paciente(fila,lblavisos):
try:
cur.execute('delete from paciente where dni = ? and nome = ? and sexo = ?;',fila)
conex.commit
lblavisos.show()
lblavisos.set_text('Fila '+fila[0]+' eliminada.')
except sqlite3.OperationalError as e:
print(e);
conex.rollback() |
2afdae0bc871c7651934dedb5a6a72e696fef54f | liuyzGIt/python_datastructure_algorithms | /data_structure_algorithms/code/queue_prio_list.py | 1,157 | 3.8125 | 4 | class PrioQueueError(ValueError):
pass
class PrioQueue:
"""小的元素优先"""
def __init__(self, elems):
self.elems = list(elems)
self.elems.sort(reverse=True)
def is_empty(self):
return not self.elems
def enqueue(self, item):
i = len(self.elems) -1
while i >= 0:
if self.elems[i] <= item:
i -= 1
else:
break
self.elems.insert(i+1, item)
def dequeue(self):
if self.is_empty():
raise PrioQueueError(' Empty in dequeue')
return self.elems.pop()
def peek(self):
if self.is_empty():
raise PrioQueueError(' Empty in dequeue')
return self.elems[-1]
def show(self):
print(self.elems)
if __name__ == "__main__":
pq = PrioQueue([1,54,8])
pq.show()
print(pq.dequeue())
pq.enqueue(100)
pq.show()
pq.enqueue(2)
pq.show()
pq.dequeue()
pq.show()
pq.peek()
pq.show()
pq.dequeue()
pq.dequeue()
pq.dequeue()
pq.dequeue()
|
68372dfabb4a768815176fd77acbab0dca4cfd68 | AngelLiang/python3-stduy-notes-book-one | /ch02/memory.py | 635 | 4.28125 | 4 | """内存
对于常用的小数字,解释器会在初始化时进行预缓存。
以Python36为例,其预缓存范围是[-5,256]。
>>> a = -5
>>> b = -5
>>> a is b
True
>>> a = 256
>>> b = 256
>>> a is b
True
# 如果超出缓存范围,那么每次都要新建对象。
>>> a = -6
>>> b = -6
>>> a is b
False
>>> a = 257
>>> b = 257
>>> a is b
False
>>> import psutil
>>> def res():
... m = psutil.Process().memory_info()
... print(m.rss >> 20, 'MB')
...
>>> res()
17 MB
>>> x = list(range(10000000))
>>> res()
403 MB
>>> del x
>>> res()
17 MB
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
|
b83d307111992d4dae35a3769afa7e3a26e7d6a4 | Man-lu/100DaysOfCodingMorseCode | /MorseCode/main.py | 2,110 | 3.515625 | 4 | from colorama import Fore
from data import morse_dict
continue_to_encode_or_decode = True
print(f"{Fore.MAGENTA}############## MORSE CODE | ENCODE AND DECODE MESSAGES ##############{Fore.MAGENTA}")
def encode_message():
""""Encodes Normal Text, Numbers and Some Punctuation into Morse Code"""
message = input(f"****** TYPE IN THE MESSAGE TO ENCODE :\n{Fore.RESET}")
message = message.replace(" ", "|").upper()
encoded_message = []
for char in message:
try:
encoded_message.append(morse_dict[char])
except KeyError:
print(f"{Fore.LIGHTRED_EX}******I Cannot Recognize One or More of Your Letters: ******{Fore.RESET}")
encoded_message.append(" ")
print(f"{Fore.MAGENTA}******Your Encoded Message is as follows: ******{Fore.RESET}")
print(f"{Fore.CYAN}<START> {Fore.RESET} {''.join(encoded_message)} {Fore.CYAN} <END>")
def decode_message():
""""Decodes the Morse Code into a Normal Text"""
message = input(f"****** TYPE IN THE MORSE CODE TO DECODE "
f"{Fore.RED}**USE 'SPACE' TO SEPARATE MORSE CODE REPRESENTING A LETTER AND '|' "
f"TO SEPARATE WORDS :\n{Fore.RESET}\n").split(" ")
decoded_message = []
for char in message:
for key,value in morse_dict.items():
if value == char:
decoded_message.append(key)
decoded_message = "".join(decoded_message).replace("|", " ").title()
print(f"{Fore.MAGENTA}******Your Decoded Message is as follows: ******{Fore.RESET}")
print(f"{Fore.CYAN}<START> {Fore.RESET} {decoded_message} {Fore.CYAN} <END>")
while continue_to_encode_or_decode:
encode_decode = input(f"{Fore.LIGHTGREEN_EX}############## Type 'E' to Encode and 'D' to Decode"
f" and 'any key' to Quit ##############\n{Fore.RESET}").lower()
if encode_decode == 'e':
encode_message()
elif encode_decode == 'd':
decode_message()
else:
print(f"{Fore.RED}******You Have Quit Encoding or Decoding: ******{Fore.RESET}")
continue_to_encode_or_decode = False
|
56dd440b18d46fb27786c94f6ba663d8fd29f284 | tomjay1/auth | /authcontproject.py | 2,546 | 4.09375 | 4 | #register
#-first name, last name, password, email
#-generate useraccount
#login
#-account number and password
#bank operation
#initialization process
import random
database = {} #dictonary
def init():
print ('welcome to bankphp')
haveaccount = int(input('do you have an account with us: 1 (yes) 2 (no) \n'))
if (haveaccount == 1):
isValidOptionSelected = True
login()
elif(haveaccount == 2):
isValidOptionSelected = True
#register()
print(register())
else:
print('you have selected invalid option')
init()
def login():
print ('*******login********')
accountnumberfromuser =int(input('insert your account number \n'))
password = input('input your password \n')
for accountnumber,userdetails in database.items():
if(accountnumber == accountnumberfromuser):
if(userdetails[3] == password):
bankoperation(userdetails)
print("invalid account number")
login()
def register():
print('***Register***')
email = input('what is your email address? \n')
first_name = input('what is your first name? \n')
last_name = input('what is your last name? \n')
password= input('create a password for yourself \n')
accountnumber = generationaccountnumber()
database[accountnumber] = [ first_name, last_name, email, password ]
print('Your account has been created')
print ('your account number is: %d' % accountnumber)
print ('make sure to keep it safe')
print ('======== ========= =========== ======')
#return database
login()
def bankoperation(user):
print('welcome %s %s '% (user[0], user[1]))
selectedoption = int(input('select an option (1)deposit (2)withdrawal (3) logout (4)exit \n'))
if(selectedoption == 1):
depositoperation()
elif(selectedoption == 2):
withdrawaloperation()
elif(selectedoption ==3):
logout()
elif(selectedoption ==4):
exit()
else:
print('invalid option selected')
bankoperation(user)
def withdrawaloperation():
print('withdrawal')
def depositoperation():
print('deposit operation')
def generationaccountnumber():
print('generating account number')
return random.randrange(1111111111,9999999999)
print(generationaccountnumber())
def logout():
login()
### actual banking system ###
init()
|
2334036ddc243ed0d3befd33a69d030a0d82c215 | klq/euler_project | /euler26.py | 1,124 | 3.84375 | 4 | def euler26():
"""
Reciprocal cycles:
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
"""
max_length = 0
for i in range(2,1000):
cycle = unit_fraction(i)
if cycle > max_length:
d = i
max_length = cycle
print d, max_length
def unit_fraction(n):
# Key to solve: just need to store a list of remainders
current_digit = 1
temp_r = []
while True:
m,r = divmod(current_digit * 10, n)
if r == 0:
return 0 # no recurring cycle
if r not in temp_r: # not recurring yet
temp_r.append(r)
current_digit = r
else:
recurring_cycle = len(temp_r) - temp_r.index(r)
return recurring_cycle
#print unit_fraction(81)
euler26() # 983 |
017df190a9e6ad31ef89fb5dc929f5c58551c2b7 | klq/euler_project | /euler5.py | 660 | 3.859375 | 4 | def least_common_multiple(numbers):
lcm = 1
for i in range(len(numbers)):
factor = numbers[i]
if factor != 1:
lcm = lcm * factor
for j in range(len(numbers)):
if numbers[j] % factor == 0 :
numbers[j] = numbers[j] / factor
return lcm
def euler5():
# Problem:
"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
# Solve:
return least_common_multiple(range(1,21)) #232792560
euler5() |
3b7fce6dfa1739f58a0a5a451f0dc8c14425ac9b | klq/euler_project | /euler20.py | 412 | 4.0625 | 4 | import math
def euler20():
"""
n! means n x (n - 1) x ... x 3 x 2 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
number = math.factorial(100)
sum_digits = sum( [int(d) for d in str(number)])
return sum_digits
print euler20()
|
c0bbbecf90a0e6128b03981b56a3c8a175f82a0b | klq/euler_project | /euler32.py | 1,272 | 3.796875 | 4 | def euler32():
"""
Pandigital products:
We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 x 186 = 7254,
containing multiplicand, multiplier,
and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product
identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
"""
pandigital_set = set('123456789')
products_set = set()
for m1 in range(1,2000):
for m2 in range(1,5000):
p = m1 * m2
totalstr = str(m1) + str(m2) + str(p)
if len(totalstr) == len(set(totalstr)) and set(totalstr) == pandigital_set:
print m1, m2, p
products_set.add(p)
return sum(products_set)
print euler32()
"""
4 1738 6952
4 1963 7852
12 483 5796
18 297 5346
27 198 5346
28 157 4396
39 186 7254
42 138 5796
48 159 7632
138 42 5796
157 28 4396
159 48 7632
186 39 7254
198 27 5346
297 18 5346
483 12 5796
1738 4 6952
1963 4 7852
45228
"""
|
78b2dadaa067264258ed93da5a4e13ebf692ec6a | klq/euler_project | /euler41.py | 2,391 | 4.25 | 4 | import itertools
import math
def is_prime(n):
"""returns True if n is a prime number"""
if n < 2:
return False
if n in [2,3]:
return True
if n % 2 == 0:
return False
for factor in range(3, int(math.sqrt(n))+1, 2):
if n % factor == 0:
return False
return True
def get_primes(maxi):
"""return a list of Booleans is_prime in which is_prime[i] is True if i is a prime number for every i <= maxi"""
is_prime = [True] * (maxi + 1)
is_prime[0] = False
is_prime[1] = False
# is_prime[2] = True and all other even numbers are not prime
for i in range(2,maxi+1):
if is_prime[i]: # if current is prime, set multiples to current not prime
for j in range(2*i, maxi+1, i):
is_prime[j] = False
return is_prime
def get_all_permutations(l):
# returns n-length iterable object, n = len(l)
# in lexical order (which means if input is [5,4,3,2,1], output will be in strictly decreasing order)
return itertools.permutations(l)
def list2num(l):
s = ''.join(map(str, l))
return int(s)
def get_sorted_pandigital(m):
"""returns a (reversed) sorted list of all pandigital numbers given m digits"""
perms = get_all_permutations(range(m,0,-1))
for perm in perms:
# per is a m-length tuple
perm = list2num(perm)
yield perm
def euler41():
"""https://projecteuler.net/problem=41
Pandigital Prime
What is the largest n-digit pandigital prime that exists?
"""
# Method 1: -----Turns out 1.1 itself is too costly
# 1. Get all the primes
# 2. Get all the pandigital numbers (sorted)
# 3. Test if prime from largest to smallest, stop when first one found
# is_prime = get_primes(987654321) taking too long
# Method 2: ----
# 1. Get all the pandigital numbers (sorted)
# 2. Test if prime from largest to smallest, stop when first one found
# !!! There will not be 8-digit or 9-digit pandigital prime numbers
# !!! Because they are all divisible by 3!
# !!! Only check 7-digit and 4-digit pandigital numbers
for m in [7,4]:
for pd in get_sorted_pandigital(m):
if is_prime(pd):
print pd
return
# Answer is:
# 7652413
def main():
euler41()
if __name__ == '__main__':
main() |
43e039d8f937cbdad0da0a04204611436eb10ba2 | jjfiv/mm2019 | /mm10534.py | 643 | 3.734375 | 4 |
import time
name=input("What's your name?\n")
time.sleep(1)
print("HELLO", name)
time.sleep(1)
print("I'm Anisha.")
time.sleep(1)
feel=input("How are you today?\n")
time.sleep(1)
print("Glad to hear you're feeling", feel, "today!")
time.sleep(1)
print("Anyway in a rush g2g nice meeting you!")
# import sys
# from typing import List
#
# # This is the main program:
# def main(args: List[str]):
#
# # loop through main arguments
# for arg in args:
# print("You said: {0}".format(arg))
#
# # or else print instructions
# if len(args) == 0:
# print("Try this script with arguments!")
#
# if __name__ == '__main__':
# main()
|
37c3dcf02898d3d6f510814948f0a4c4de72d2d9 | geekbaba/happy_python | /square.py | 345 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#类4边形
import turtle
colors=['red','blue','green','orange']
t=turtle.Pen()
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colors[x%4]) #设置画笔的颜色
t.width(x/100+1) #笔尖的宽度
t.forward(x) #笔向前移动多少
t.left(90) #笔的角度调整 90度 |
d838b971f537f51123defb0358633a9041fd2732 | Haribabu1433/gitpython | /test.py | 176 | 4.03125 | 4 | print("Hello World")
print("Hello from Hari")
list1 = [x*2 for x in [1,2,3]]
print(list1)
dict1 = {'x':1,'y':2}
print(dict1['x'])
set1 = set([1,2,3,4,4,3,2,4])
print(set1)
|
5ddf987c72fed9f1576ddd4fc236693c0cab0101 | hsnbskn/sqlite-python | /sqlAuthDemo.py | 1,069 | 3.515625 | 4 | #!/usr/bin/python3
import sqlite3
dbConnect = sqlite3.connect('userAuthData.db') #Veritabanina baglan.
dbCursor = dbConnect.cursor() #imlec olustur.
dbCursor.execute("""CREATE TABLE IF NOT EXISTS users (username,password)""") #Kullanici adi ve parola tutan bir tablo ekle.
datas = [('admin','123456'),('hasan','2021'),('haydar','hay123dar')] #Kullanici verileri olustur.
for data in datas:
dbCursor.execute("""INSERT INTO users VALUES %s"""%(data,)) #Kullanici verileri tek ogeli bir demet ile tabloya yerlestir.
dbConnect.commit() #Verileri veritabanina isle.
userName = raw_input("Username: ") #Kullanici adi giris
passWord = raw_input("Password: ") #Parola giris
dbCursor.execute("""SELECT * FROM users WHERE username = '%s' AND password = '%s'"""%(userName,passWord)) #Kullanici adi ve Parolayi Veritabanindan dogrula
dataFromDb = dbCursor.fetchone() #Bir tane veriyi al.
if dataFromDb:
print("Login Success, welcome {}".format(dataFromDb[0]))
else:
print("Access Denied !")
|
085357eaa91ec17fcad387c048b18b4858eb6c6b | schumanzhang/python | /pandas_demo.py | 1,068 | 3.953125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
#dataframe is like a python dictonary
web_stats = {'Day' : [1, 2, 3, 4, 5, 6],
'Visitors' : [34, 56, 34, 56, 23, 56],
'Bounce_Rate' : [65, 74, 23, 88, 93, 67]}
#how to convert above to a dataframe?
df = pd.DataFrame(web_stats)
#print(df)
#print first 5 rows
print(df.head())
#print the last 5 rows
print(df.tail())
#print the last 2 rows
print(df.tail(2))
#look at index, time series data, index should be Day
#the following returns a new dataframe, second line modifies the dataframe
df.set_index('Day')
df.set_index('Day', inplace=True)
print(df.head())
#reference a column
print(df['Visitors'])
print(df.Visitors)
#show two columns
print(df[['Bounce_Rate', 'Visitors']])
#convert a column to a list
print(df.Visitors.tolist())
#use numpy to convert to a numpy array
print(np.array(df[['Bounce_Rate', 'Visitors']]))
#create new dataframe
df2 = pd.DataFrame(np.array(df[['Bounce_Rate', 'Visitors']]))
print(df2) |
199e8640a08e85102ba40a418487ce262137ac22 | jkarwacki/Mosh-s-Python-course | /Examples and excercises/secret_number.py | 410 | 3.921875 | 4 | secretNumber = 9
noOfGuesses = 0
maxGuesses = 3
while noOfGuesses < maxGuesses:
guess = int(input('Guess: '))
noOfGuesses += 1
if guess == secretNumber:
print("You won!")
break
else: # else statement to the while loop; if the condition is not longer fulfilled
print("Sorry, you failed") # and no break was made, this code is run
|
9981ba51c093c04e7458a5ce0394d2736c6647e3 | bgagan911/Python_edX | /test.py | 545 | 4 | 4 | # [ ] review and run example
student_name = "Joana"
# get last letter
end_letter = student_name[-1]
print(student_name,"ends with", "'" + end_letter + "'")
# [ ] review and run example
# get second to last letter
second_last_letter = student_name[-2]
print(student_name,"has 2nd to last letter of", "'" + second_last_letter + "'")
# [ ] review and run example
# you can get to the same letter with index counting + or -
print("for", student_name)
print("index 3 =", "'" + student_name[3] + "'")
print("index -2 =","'" + student_name[-2] + "'")
|
f6ae082ababd05373fa7170573662f83c6686a00 | sososeng/DigitalCrafts_Exercises | /function_exercises/degree_conversion.py | 242 | 3.671875 | 4 | import matplotlib.pyplot as plot
import math
def f(x):
# put your code here
return x +1
c = int(input("Celsius? "))
xs = list(range(c, int(c *(9/5)+ 32)))
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.show()
|
55016de6c8eb6bfd69668f561b4686f0d23a9f9a | sososeng/DigitalCrafts_Exercises | /python_exercises_2/loop/multiplication_table.py | 89 | 3.578125 | 4 | for i in range(1,11):
for j in range(1,11):
print("{0} X {1} = {2}".format(i,j,(i*j))) |
0fbd1ecb479efa0ab654ae686d8ecc3acdab53b4 | sososeng/DigitalCrafts_Exercises | /python_exercises_2/list/matrix_addition.py | 196 | 4.03125 | 4 | one = [ [1, 3],
[2, 4]]
two = [ [5, 2],
[1, 0]]
three=[ [0,0],
[0,0]]
for i in range (0, len(one)):
for j in range(0,len(one)):
three [i][j] = (one[i][j] + two[i][j])
print(three) |
11e4e6ec3b1d406dc98967eebbe6f040e28a5704 | sososeng/DigitalCrafts_Exercises | /python_exercises_1/tip_calc.py | 374 | 3.84375 | 4 | bill = input("Total bill amount? ")
level = input("Level of service? ")
tip = 0.0
if(level == "good"):
tip = "{:.2f}".format(float(bill) * .20)
if(level == "fair"):
tip = "{:.2f}".format(float(bill) * .15)
if(level == "bad"):
tip = "{:.2f}".format(float(bill) * .1)
print ("Tip amount:", tip)
print ("Total bill amount: " , "{:.2f}".format(float(bill) + float(tip))) |
e6f4754b851d4f078593a7dc5c4976f0dd43b3be | A-ZHANG1/CS61ACS88 | /part1.py | 12,227 | 3.640625 | 4 | #CS61A,CS88
#Textbook from http://composingprograms.com/
"""
#######Local state,Recursion Text book#############################
"""
# def outer(f,x):
# def inner():
# return f(x)
# return inner
# g=outer(min,[5,6])
# print(g())
# def outer(f,x):
# return inner
# def inner():
# return f(x)
# g=outer(min,[5,6])
# print(g())
# def letters_generator():
# current='a'
# while current<='d':
# yield current
# current=chr(ord(current)+1)
#
# letters=letters_generator()
# type(letters)
#
# caps=map(lambda x:x.upper(),b_to_k)
# def cascade(n):
# """Print a cascade of prefixes of n."""
# print(n)
# if n >= 10:
# cascade(n//10)
# print(n)
#
# cascade(1234)
# def inverse_cascade(n):
# grow(n)
# print(n)
# shrink(n)
# def f_then_g(f,g,n):
# if n:
# f(n)
# g(n)
# grow=lambda n:f_then_g(grow,print,n//10)
# shrink=lambda n:f_then_g(print,shrink,n//10)
# def split(n):
# return n//10,n%10
# def sum_digits(n):
# if n<10:
# return n
# else:
# all_but_last,last=split(n)
# return sum_digits(all_but_last)+last
# def luhm_sum(n):
# if n<10:
# return n
# else:
# all_but_last,last=split(n)
# return luhm_sum_double(all_but_last)+last
# def luhm_sum_double(n):
# all_but_last,last=split(n)
# luhm_digit=luhm_sum(2*last)
# if n<10:
# return luhm_digit
# else:
# return luhm_sum(all_but_last)+luhm_digit
# print(luhm_sum(32))
# def partitions(n,m):
# if n==0:
# return Link(Link.empty)
# elif n<0 or m==0:
# return Link.empty
# else:
# using_m=partitions(n-m,m)
# with_m=map_link(lambda s:Link(s,m),using_m)
# without_m=partitions(n,m-1)
# return with_m+without_m
# def reduce(reduce_fn,s,initial):#!!
# reduced=initial
# for x in s:
# redudced=reduce_fn(redudced,x)
# return reduced
# reduce(mul,[2,4,8],1)
"""
####2.3 tree from textbook#################################
"""
# def tree(root,branches=[]):#!!
# for branch in branches:
# assert is_tree(branch),'Branch must be a tree.'
# return [root]+list(branches)
# def root(tree):
# return tree[0]
# def branches(tree):
# return tree[1:]
# def is_tree(t):#!!
# if type(t) is not list or len(t)<0:
# return False
# for branch in branches(t):
# if not is_tree(branch):
# return False
# return True
# def is_leaf(tree):
# return not branches(tree)
# ####general parts for tree implementation ends#
# ####specific functioning functions begins######
# # def fib_tree(n):#!!
# # if n==0 or n==1:
# # return tree(n)
# # else:
# # left,right=fib_tree(n-1),fib_tree(n-2)
# # fib_n= root(left)+root(right)
# # return tree(fib_n,[left,right])
# # print(fib_tree(5))#!!
# #
# # def partition_tree(n,m):
# # if n==0:
# # return tree(True)#!!
# # if n<0 or m==0:
# # return tree(False)#!!
# # left=partition_tree(n-m,m)
# # right=partition_tree(n,m-1)
# # return tree(m,[left,right])#!!
# # def print_parts(tree,partition=[]):
# # if is_leaf(tree):#
# # #if root(tree):#??
# # print('+'.join(partition))#a string
# # #method takes a list of things to join with the string.
# # else:
# # left,right=branches(tree)
# # m=str(root(tree))
# # print_parts(left,partition+[m])
# # print_parts(right,partition)
# # print_parts(partition_tree(6,4))
# #
# # def right_binarize(tree):
# # if is_leaf(tree):
# # return tree
# # if len(tree)>2:
# # tree=[tree[0],tree[1:]]
# # return [right_binarize(b) for b in tree]
# # print(right_binarize([1,2,3,4,5,6,7]))
# ###2.3 tree####################################
"""
# ##hw5 tree#####################################
"""
# def print_tree(t,indent=0):
# print(' '*indent+str(root(t)))
# for branch in branches(t):
# print_tree(branch,indent+1)
# print_tree(tree(1,[tree(2)]))
#
# def make_pytunes(username):
# return tree(username,[tree('pop',[tree('justinbieber',[tree('single',[tree('what do you mean?')])]),tree('105 pop mashup')]),
# tree('trace',[tree('darude',[tree('sandstorm')])])])
# print_tree(make_pytunes('I love music'))
#
# def num_leaves(t):
# if is_leaf(t):
# return 1
# else:
# #return 1+num_leaves(branches(t))??
# return sum([num_leaves(branch) for branch in branches(t)])
# print(num_leaves(make_pytunes('music')))
#
# def num_leaves_2(t):
# if is_leaf(t):
# return 1
# else:
# leaves=0
# for b in branches(t):
# leaves+=num_leaves_2(b)
# return leaves
# print(num_leaves_2(make_pytunes('music')))
#
# ###crtl+F#######################
# def find(t,target):
# if root(t)==target:
# return True
# else:
# return any([find(branch,target) for branch in branches(t)])#
# def find_2(t,target):
# if root(t)==target:
# return True
# else:
# for branch in branches(t):
# if find(branch,target):
# return True
# return False
# my_account = tree('kpop_king',
# [tree('korean',
# [tree('gangnam style'),
# tree('wedding dress')]),
# tree('pop',
# [tree('t-swift',
# [tree('blank space')]),
# tree('uptown funk'),
# tree('see you again')])])
# print(find(my_account, 'bad blood'))
#
# ###add to tree#################
# def add_song(t,song,category):
# if root(t)==category:
# return tree(category,branches(t)+[tree(song)])
# else:
# #for b in branches(t):
# #all_branches=add_song(b,song,category)
# #link! jianya!
# return tree(root(t),[add_song(b,song,category) for b in branches(t)])
# ##test#######################
# indie_tunes = tree('indie_tunes',
# [tree('indie',
# [tree('vance joy',
# [tree('riptide')])])])
# new_indie = add_song(indie_tunes, 'georgia', 'vance joy')
# print_tree(new_indie)
#
# ####delete###################
# def delete(t, target):
# kept_branches=[b for b in branches(t) if root(b)!=target]
# return tree(root(t),kept_branches)
# ######test##################
# my_account = tree('kpop_king',[tree('korean',[tree('gangnam style'),tree('wedding dress')]),tree('pop',[tree('t-swift',[tree('blank space')]),tree('uptown funk'),tree('see you again')])])
# new = delete(my_account, 'pop')
# print_tree(new)
"""
# ###mutable#################
"""
# #not passing test because nonloca not available in python 2.x#
# def make_withdraw(balance, password):
# attempt=[]#!!
# def withdraw(amount,p):
# nonlocal balance#!!
# for i in range(3):
# if p!=password:
# attempt+=[p]
# else:
# break;
# if i==3:
# return "Your account is locked. Attempts: "+str(attempt)
# if amount > d['y']:
# return 'Insufficient funds'
# d['y'] = d['y'] - amount
# print(d['y'])
# return withdraw
# ##
#
# def make_joint(withdraw, old_password, new_password):
# error = withdraw(0,old_passord)
# if type(error)==str:#nice way to decide whether return value is a 'insufficient funds'or valid amount
# return error
# def joint(amount,password_attempt):#READ the question
# if password_attempt==new_password:
# return withdraw(amount,old_passord)
# return withdraw(amount,password_attempt)
# return joint
"""
##dispatch dictionary################################
"""
#abstract data type : account
# def account(initial_balance):#constructor
# def deposit(amount):
# dispatch['balance'] += amount
# return dispatch['balance']
# def withdraw(amount):
# if amount > dispatch['balance']:
# return 'Insufficient funds'
# dispatch['balance'] -= amount
# return dispatch['balance']
# dispatch = {'deposit': deposit, #store the local state of account
# 'withdraw': withdraw,
# 'balance': initial_balance}
# # message : number or functions
# #functions here have access to the dispatch library
# #thus can read or write balance
# return dispatch
#
# def withdraw(account, amount):#function to withdraw
# return account['withdraw'](amount)
# def deposit(account, amount):#function to withdraw
# return account['deposit'](amount)
# def check_balance(account):#selector
# return account['balance']
#####test##########################
# a = account(20)
# deposit(a, 5)
# withdraw(a, 17)
# print(check_balance(a))
"""
##########text book 2.3.7 linked list########################
"""
###initialization#############
# empty='empty'
# def is_link(s):
# return s is empty or len(s)==2 and is_link(s[1])
# def link(first,rest):
# assert is_link(rest)
# return [first,rest]
# def first(s):
# assert is_link(s)
# assert s!=empty
# return s[0]
# def rest(s):
# assert is_link(s)
# assert s!=empty
# return s[1]
# four=link(1,link(2,link(3,link(4,empty))))
# print(is_link(four))
# print(rest(four))
# print(first(four))
###functions######################
# def len_link_recursive(s):#don't use the name 'len' for it's internally defined
# if s is empty:
# return 0
# return len_link(rest(s))+1
# def len_link_using_built_in_len(s):
# return 1+len(rest(S))
# def len_link_loop(s):
# return 1+len(rest(s))
# length=0
# while s is not empty:
# s=rest(s)
# length+=1
# return length
# print(len_link_loop(four))
# def getitem_link(s,i):
# while i !=1:
# s,i=rest(s),i-1
# return first#not s[0] (abstraction barrier)
# print(getitem_link(four,2))
# def extend_link(s,t):
# assert is_link(s),is_link(t)
# if s==empty:
# return t
# else:
# return link(first(s),extend_link(rest(s),t))#cotect form for recursion
# print(extend_link(four,link(5,'empty')))
# import math
# def apply_to_all_link(f,s):
# assert is_link(s)
# if s==empty:
# return s
# else:
# return link(f(first(s)),apply_to_all_link(f,rest(s)))#same as above
# print(apply_to_all_link(math.sqrt, four))
# def keep_if_link(f, s):
# assert is_link(s)
# if s==empty:
# return s
# else:
# kept=keep_if_link(f,rest(s))
# if f(first(s)):#create a linked list with recursion
# return link(first(s),kept)
# else:
# return kept
# print(keep_if_link(lambda x:x%2, four))
# def join_link(s, separator):
# assert is_link(s)
# if s==empty:
# return ""
# if rest(s)==empty:
# return str(first(s))
# else:
# return str(first(s))+str(separator)+join_link(rest(s),separator)
# print(join_link(four,","))
###OOP Textbook 2.5 2.6 2.9###########################################
# def make_instance(cls):
# def get_value(name):
# if name i attributes:
# return attributes[name]
# else:
# value = cls['get'](name)#??
# return bind_method(value,instance)
# def set_value(name,value):
# attributes[name]=value
# attributes={}
# instance={'get':get_}
#haven't finished this sample code
####################################################################
|
492736dac8fb52067c21b4561ba9731337f8b84c | merveky/BASKENT-TBY414-Bahar2020 | /3 Mart 2020/beden kutle indeksi.py | 1,244 | 3.84375 | 4 | # Beden kütle indeksi - Sağlık göstergesi hesaplama
# TBY414 03.03.2020
# ADIM 1 - Kullanıcı girdilerinden indeksi hesaplamak
# ağırlık (kg) boy (metre) olacak şekilde bki = a/(b*b)
agirlik = float( input("Lütfen ağırlığınızı giriniz (kg): ") )
# ^ bir sayı olması gereken bir girdi alıyoruz.
boy = float( input("Lütfen boyunuzu giriniz (cm):") )
boy = boy / 100.0 # metreye çevirdik
bki = agirlik / (boy * boy)
print("BKİ değeri: ", bki)
# ADIM 2 - Kullanıcının sınıflandırmasını yapmak
# <18.5 <25 <30 <35 <40 --
# zayıf sağlıklı az kilolu 1. obez 2. obez 3. obez
if bki <18.5:
print("Zayıfsınız")
print("Sağlıklı biçimde kilo alabilirsiniz")
if boy<1.40:
# Belki de çocuk?
print("Çocuklar için BKİ formülü farklıdır.")
elif bki < 25:
print("Sağlıklısınız")
elif bki <30:
print("Az kilolusunuz")
elif bki<35:
print("Dikkat! 1. Obez")
elif bki<40:
print("Dikkat! 2. Obez")
else:
print("Dikkat 3. Obez")
# ADIM 3 - Bir kilo alma/verme hedefi oluşturmak
# Bu aynı zamanda ikinci ödevin bir parçası.
# Not: Birinci ödev github hesabı açamak idi.
|
9c030cd12cc6af8ecde57f52ed0063e5acc4bf5e | artraya/scrapeDB | /Template Scripts/FlixmetricScrape.py | 2,205 | 3.625 | 4 | import requests
import http.client
from bs4 import BeautifulSoup
MetaUrl = 'https://flickmetrix.com/watchlist'
MetaHeaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
# result = requests.get(MetaUrl, headers=MetaHeaders)
with open("Flick.html", "r") as f: #open the HTML file
contents = f.read()
html_soup = BeautifulSoup(contents, 'html.parser') #parse the contents of the html file that we've opened
type(html_soup) #have no idea what this does
movie_title, movie_date = html_soup.find_all('div', class_ = 'title ng-binding'), html_soup.find_all('div', class_ = 'film-section ng-binding') #double variable control
for i, j in zip(movie_title[::2], movie_date[::3]): # [::2] and [::3] iterates over every 2nd and 3rd element in each list respectively.
title = i.text
title = title.replace(" ", "+")
title = title.replace(":", "%3A") #URL encoding for each title for a later POST request
date = j.text #storing movie date into a variable for accurate search results
date = date.replace("(", "")
date = date.replace(")", "")
#print(title, date)
url = "https://api.themoviedb.org/3/search/movie?api_key=2b5c62f4ed3da916c3b4c6ca47003e46&language=en-US&page=1&include_adult=false&query={}&year={}".format(
title, date)
payload = "{}"
response = requests.request("GET", url, data=payload)
results = response.json()
#print(results)
if results["results"] and results["results"][0]["release_date"][:4] == date:
movie_id = results["results"][0]["id"]
conn = http.client.HTTPSConnection("api.themoviedb.org")
payload = "{\"media_id\":%s}" % movie_id
headers = {'content-type': "application/json;charset=utf-8"}
conn.request("POST",
"/3/list/127145/add_item?api_key=2b5c62f4ed3da916c3b4c6ca47003e46&session_id=9ef3454015fb183f7611e6e510ff77bb52db2b74",
payload, headers)
res = conn.getresponse()
data = res.read()
print(data)
print("added:", title, date, "to your list")
else:
print(title, "was not added to your list because your code is crap!")
|
684ed7e9ab5c2bce663e47c8791f4e23465dd0c6 | Romihime/Algo3.2.tp1 | /aed3-tp3-master/cargar.py | 1,242 | 3.875 | 4 | #!/usr/bin/python
import sys
def leer_datos(path):
xs = []
ys = []
ds = []
with open(path, 'r') as f:
#Ignoro las primeras 3 lineas
nombre_archivo_salida = str(f.readline().split()[2])
nombre_archivo_salida = nombre_archivo_salida + ".in"
for i in range(2):
f.readline()
#Leo la cantidad de nodos
line = f.readline()
p, s, t = line.split()
n = int(t)
#print(n)
#Ignoro la siguiente linea y leo la capacidad de los camiones
f.readline()
line = f.readline()
p, s, t = line.split()
c = int(t)
#print(c)
#Ignoro la siguiente linea y por cada id y coordenada voy guardando
f.readline()
for i in range(n):
line = f.readline()
_id, x, y = line.split()
xs.append(x)
ys.append(y)
#Ignoro la siguiente linea y guardo la demanda segun cada id
f.readline()
for i in range(n):
line = f.readline()
_id, d = line.split()
ds.append(d)
#print(ds)
with open(nombre_archivo_salida, 'w') as f2:
f2.write('{} {}\n'.format(n, c))
for i in range(n):
f2.write('{} {} {}\n'.format(xs[i], ys[i], ds[i]))
return 0
def main():
nombre_archivo = sys.argv[1] #tomamos el nombre dle archivo
datos = leer_datos( nombre_archivo )
if __name__ == '__main__':
main()
|
7f311d686d93dd4894dfac265c66eea3e8ae7f38 | senzuo/tryleetcode | /leetcode5Bruce.py | 1,747 | 3.90625 | 4 | # 自己写的暴力求解
def longestPalindrome(s):
"""
:type s: str
:rtype: str
"""
imax = len(s)
longest = s[0]
for k in range(imax - 1):
# 两种情况考虑 1. xxxaaxxx 2.xxaxx
# 但是 xxxaaaxxx GG
# 只能乖乖都执行了……
if s[k] == s[k + 1]:
i, j = k, k + 1
# while i > 0 and j < imax - 1 and s[i - 1] == s[j + 1]:
# i -= 1
# j += 1
# if j - i + 1 > len(longest):
# longest = s[i: j + 1]
else:
i, j = k, k
while i > 0 and j < imax - 1 and s[i - 1] == s[j + 1]:
i -= 1
j += 1
if j - i + 1 > len(longest):
longest = s[i: j + 1]
return longest
# print(longestPalindrome('cbbd'))
# print(longestPalindrome('babad'))
# print(longestPalindrome('a'))
# print(longestPalindrome('bbb'))
# print('Wrong!')
# 人家的暴力求解
def longestPalindromeBruteForce(s):
"""
:type s: str
:rtype: str
"""
ans, pal_str = 0, ''
for i in range(len(s)):
for j in range(i, len(s)):
print(s[i:j + 1])
if s[i:j + 1] == s[i:j + 1][::-1]:
length = j - i + 1
if length > ans:
ans = length
pal_str = s[i:j + 1]
return pal_str
# print(longestPalindromeBruteForce('cbbd'))
print(longestPalindromeBruteForce('babad'))
# print(longestPalindromeBruteForce('a'))
# print(longestPalindromeBruteForce('bb'))
### 对比
# 出发点不同,自己的函数从每个点向两边拓展,别人的是检查每个字串是否是回文
# 自己函数效率稍微高一些,别人的函数代码简洁一些
|
969dcb391cd130eb1f02357eac75c53c0c4427ac | wonnacry/hw | /task_generator_password.py | 164 | 3.5 | 4 | import random
import string
def password_generator(n):
while 1:
a = []
for i in range(n):
a.append(random.choice(string.ascii_letters))
yield ''.join(a)
|
ba0392de63e38ed23e776be5de7c09ed61510360 | JinnieJJ/leetcode | /67-Add Binary.py | 571 | 3.5 | 4 | class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = ""
value = 0
carry = 0
if len(a) < len(b):
return self.addBinary(b, a)
for i in range(len(a)):
val = carry
val += int(a[-(i + 1)])
if i < len(b):
val += int(b[-(i + 1)])
carry, val = int(val/2), val % 2
result += str(val)
if carry:
result += str(carry)
return result[::-1]
|
a6fe9e17e19a70fc6b383af53ccbe645469a7a39 | JinnieJJ/leetcode | /430-Flatten a Multilevel Doubly Linked List.py | 944 | 3.84375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
curr, stack = head, []
while curr:
if curr.child:
# If the current node is a parent
if curr.next:
# Save the current node's old next pointer for future reattachment
stack.append(curr.next)
curr.next, curr.child.prev, curr.child = curr.child, curr, None
if not curr.next and len(stack):
# If the current node is a child without a next pointer
temp = stack.pop()
temp.prev, curr.next = curr, temp
curr = curr.next
return head
|
363aed625a6b0236330372b0355d6d3c4a032020 | JinnieJJ/leetcode | /437-Path Sum III.py | 698 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def pathSum(self, root, target):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
res = 0
queue = deque([(root, [])])
while queue:
node, prev = queue.popleft()
if node:
tmp = [node.val + p for p in prev] + [node.val]
res += sum([v == target for v in tmp])
queue.extend([(node.left, tmp), (node.right, tmp)])
return res
|
862bf3f795351c97753078b73cd9992b89b24d50 | JinnieJJ/leetcode | /680-Valid Palindrome II.py | 467 | 3.515625 | 4 | class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left = 0
right = len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return s[left+1:right+1] == s[left+1:right+1][::-1] or s[left:right] == s[left:right][::-1]
#[::-1]要分开写
return True
|
c7b2c1ef58c980fa43b866a1c81ab6c5e79069bc | JinnieJJ/leetcode | /269-Alien Dictionary.py | 1,768 | 3.78125 | 4 | from collections import deque
class Solution:
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
self.visited = {}
self.graph = {}
self.results = deque()
characters = set()
for word in words:
for char in word:
self.visited[char] = 0
self.graph[char] = []
characters.add(char)
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i+1]
success = self.addEdge(word1, word2)
if not success:
return ""
for char in characters:
success = self.topologicalSort(char)
if not success:
return ""
return "".join(list(self.results))
def topologicalSort(self, char):
if self.visited[char] == -1: # detected cycle
return False
if self.visited[char] == 1: #char has been visited and completed topological sort on
return True
self.visited[char] = -1
for neigh in self.graph[char]:
success = self.topologicalSort(neigh)
if not success:
return False
self.visited[char] = 1
self.results.appendleft(char)
return True
def _addEdge(self, var1, var2):
self.graph[var1].append(var2)
def addEdge(self, word1, word2):
for char1, char2 in zip(word1, word2):
if char1 != char2:
self._addEdge(char1, char2)
return True
if len(word1) > len(word2):
return False
return True
|
741b914a0720c6637a7c7a39b6e744e6ec873fd3 | JinnieJJ/leetcode | /298-Binary Tree Longest Consecutive Sequence.py | 956 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
stack = [(root, 1)]
maxlen = 1
while stack:
e = stack.pop()
if e[0].left:
if e[0].left.val == e[0].val + 1:
stack.append((e[0].left, e[1]+1))
maxlen = max(maxlen, e[1]+1)
else:
stack.append((e[0].left, 1))
if e[0].right:
if e[0].right.val == e[0].val + 1:
stack.append((e[0].right, e[1]+1))
maxlen = max(maxlen, e[1]+1)
else:
stack.append((e[0].right, 1))
return maxlen
|
40ace747a74a8261a90b44a01292e40a9ff56877 | Rakeshgsekhar/DataStructure | /QCodes/swapNodesInPair.py | 492 | 3.5625 | 4 | class Solution:
def swapPairs(self, head: ListNode):
if head is None or head.next is None:
return head
tempx = ListNode(0)
tempx.next = head
temp2 = tempx
while tempx.next is not None and tempx.next.next is not None:
first = tempx.next
sec = tempx.next.next
tempx.next = sec
first.next = sec.next
sec.next = first
tempx = tempx.next.next
return temp2.next |
2b92afe371f111e0353ac1276c33d79a17f2c6e1 | Rakeshgsekhar/DataStructure | /QCodes/printMiddleNodeofList.py | 628 | 3.75 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
def printMiddleElement(head):
temp = head
temp1 = head
if temp is None:
print ('No Elements Found')
count = 0
while temp is not None:
count += 1
temp = temp.next
mid = count//2 + 1
for i in range(1,mid):
temp1 = temp1.next
print(temp1.data)
l1 = Node(1)
l2 = Node(2)
l3 = Node(3)
l4 = Node(4)
l5 = Node(5)
l6 = Node(6)
l7 = Node(7)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
l5.next = l6
l6.next = l7
head = None
head = l1
printMiddleElement(head)
|
ea7bccb74b723915301aa7328f7c1baaeadaffa1 | Nesters/python-workshop | /intro/solutions/animals/cat.py | 169 | 3.5 | 4 | from animals.animal import Animal
class Cat(Animal):
def __init__(self, name):
super(Animal,self).__init__()
def meow(self):
print('meow') |
734c2933e3fc24ecb3efc7ca1e468d5264d53ea3 | hrldcpr/cryptopals | /set2/challenge9.py | 418 | 3.765625 | 4 |
import utilities
def pad(text, n):
m = n - len(text)
return text + bytes([m] * m)
def unpad(text, n):
if text:
m = text[-1]
if m < n and text.endswith(bytes([m] * m)):
return text[:-m]
return text
@utilities.main
def main():
x = b'YELLOW SUBMARINE'
y = pad(x, 20)
assert y == b'YELLOW SUBMARINE\x04\x04\x04\x04'
assert unpad(y, 20) == x
print(y)
|
c18a67801410dab787e4cbe3e2915074a040377e | lidannili/IIPP-Part1 | /stopwatch.py | 1,992 | 3.59375 | 4 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
width = 150
height = 150
interval=100
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
# t is in 0.1 seconds
# A:BC.D
A=0
B=0
C=0
D=0
win = 0
trial = 0
#time = str(A) + ":" + str(B)+str(C) + "." + str(D)
def format(t):
global A
global B
global C
global D
if t< 600:
B= (t-600*(t/600) )/100
C= ((t-600*(t/600) )%100-(t-600*(t/600) )%10)/10
D= (t-600*(t/600) )%10
return str(A) + ":" + str(B)+str(C) + "." + str(D)
else:
A = A+t/600
B= (t-600*(t/600) )/100
C= ((t-600*(t/600) )%100-(t-600*(t/600) )%10)/10
D= (t-600*(t/600) )%10
return str(A) + ":" + str(B)+str(C) + "." + str(D)
# define event handlers for buttons; "Start", "Stop", "Reset"
def Start():
global trial
if not timer.is_running():
trial = trial + 1
timer.start()
def Stop():
global win
if timer.is_running() and D==0:
win = win + 1
timer.stop()
def Reset():
global time
global win
global trial
timer.stop()
time = 0
win = 0
trial = 0
# define event handler for timer with 0.1 sec interval
time = 0
def timer_handler():
global time
time=time+1
# define draw handler
def draw(canvas):
canvas.draw_text(format(time), [80,150], 60, "White")
canvas.draw_text("player :"+ str(win) + "/" + str(trial),[200,50],20,"Red")
# create frame
frame = simplegui.create_frame("Home", 300, 300)
timer = simplegui.create_timer(interval,timer_handler)
# register event handlers
frame.set_draw_handler(draw)
frame.add_button("Start", Start, 100)
frame.add_button("Stop", Stop, 100)
frame.add_button("Reset", Reset, 100)
# start frame
frame.start()
# Please remember to review the grading rubric
|
a084d4b1a3a99cd2b6dcfc996af18aa6514245f1 | QaisZainon/Learning-Coding | /Automate the Boring Stuff/Ch.13 - Working with Excel Spreadsheets/TextFilestoSpreadsheet.py | 952 | 3.96875 | 4 | #! python3
# Reads text files, put them into lists and then input into an excel file
import openpyxl, os
def TextToExcel(folder):
wb = openpyxl.Workbook()
sheet = wb.active
num_column = 0
# Going through the file
for foldername, subfolders, filenames in os.walk(folder):
for fl_int in range(len(filenames)):
filename = list(filenames)
file_ = open(foldername + '\\' + filename[fl_int],'r')
# Acquiring the text form .txt
text_ = file_.readlines()
text_ = text_[0].split(' ')
for num_row in range(len(text_)):
sheet.cell(row = num_row + 1, column = num_column + 1).value = text_[num_row]
print(text_[num_row])
num_column += 1
wb.save('TextToExcel.xlsx')
TextToExcel(r'C:\Users\Dr. Wan Asna\Desktop\Python Projects\Automate the Boring Stuff\Ch.13 - Working with Excel Spreadsheets\num') |
cb24203b039fe1ad617c34c1c14b920c8ca3a8fc | QaisZainon/Learning-Coding | /Statistics for Financial Analysis/Week 3/Population&Sample.py | 1,219 | 4.03125 | 4 | import pandas as pd
import numpy as np
#Create a Population DataFrame with 10 data
data = pd.DataFrame()
data['Population'] = [47, 48, 85, 20, 19, 13, 72, 16, 50, 60]
#Draw sample with replacement, size=5 from Population
a_sample_with_replacement = data['Population'].sample(5, replace=True)
print(a_sample_with_replacement)
a_sample_without_replacement = data['Population'].sample(5, replace=False)
print(a_sample_without_replacement)
#Calculate mean and variance
population_mean = data['Population'].mean()
population_var = data['Population'].var(ddof=0)
print('Population mean is', population_mean)
print('Population variance is', population_var)
#Calculate sample mean and sample standard deviation, size=10
#You will get different mean and variance every time when yuo execute the below code
a_sample = data['Population'].sample(10, replace=True)
sample_mean = a_sample.mean()
sample_var = a_sample.var()
print('Sample mean is ', sample_mean)
print('Sample variance is ', sample_var)
#Average of an unbiased estimator
sample_length = 500
sample_variance_collection =[data['Population'].sample(10, replace=True).var(ddof=1) for i in range(sample_length)]
print(sample_variance_collection) |
0f8ded0901ca84c9b277aaba67b9578f799d75de | QaisZainon/Learning-Coding | /Practice Python/Exercise_24.py | 249 | 3.890625 | 4 | #Returns a board based on user input
def board(width, height):
top_bot = ' ---'
vertical = '| '
for i in range(height):
print(top_bot*(width))
print(vertical*(width + 1))
print(top_bot*(width))
board(3, 3) |
e077c341cf3f4dc0825b712a24ffd1ad2378dac0 | QaisZainon/Learning-Coding | /Practice Python/Exercise_31.py | 482 | 4.03125 | 4 | # make a hangman game?-ish
random_word = 'BALLISTOSPORES'
def hangman():
print('Welcome to Hangman!')
missing = ['_ ' for i in range(len(random_word))]
while '_ ' in missing:
print(''.join(missing))
guess = input('Guess your letter: ').upper()
# word checker and updater
for i in range(len(random_word)):
if random_word[i] == guess:
missing[i] = guess + ' '
print(''.join(missing))
hangman() |
1ba8cda2d2376bd93a169031caa473825b3912da | QaisZainon/Learning-Coding | /Practice Python/Exercise_02.py | 795 | 4.375 | 4 | '''
Ask the user for a number
Check for even or odd
Print out a message for the user
Extras:
1. If number is a multiple of 4, print a different message.
2. Ask the users for two numbers, check if it is divisible, then
print message according to the answer.
'''
def even_odd():
num = int(input('Enter a number\n'))
if num % 4 == 0:
print('This number is divisible by 4')
if num % 2 == 0:
print('This is an even number')
elif num % 2 == 1:
print('This is an odd number')
print('Give me two numbers,the first to check and the second to divide')
check = int(input('Check number'))
divide = int(input('Divider'))
if num / divide == check:
print('Correct!')
else:
print('Incorrect!')
even_odd()
|
297253a153c50c6a2c4c64a1242584fe98801ae7 | QaisZainon/Learning-Coding | /Automate the Boring Stuff/Ch.10 - Organizing Files/DeletingUnneededFiles.py | 561 | 3.59375 | 4 |
from pathlib import Path
import os
p = Path.cwd()
#Walk through a folder tree
for foldername, subfolders, filename in os.walk(p):
print(f'checking folders {foldername}...')
for filenames in filename:
try:
#searches for large files, > 100MB
size = os.path.getsize(os.path.join(foldername,filenames))
print(size)
if size >= 1*10**8:
#Print these files on the screen
print(f'The size of {filenames} is {size}.')
except:
continue
|
3ce261f1cc1721461582343902df008991a61382 | Rain-Sun/ABCA | /ABCA_topK.py | 13,643 | 3.984375 | 4 | """ A Python Class
A simple Python graph class, demonstrating the essential
facts and functionalities of graphs.
"""
#import queue
import math
from random import choice
#import copy
import sys
import time
from collections import deque
#from numba import jit
class Graph(object):
def __init__(self, graph_dict=None):
""" initializes a graph object
If no dictionary or None is given,
an empty dictionary will be used
"""
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict
def self_dict(self):
return self.__graph_dict
def bfs_dict(self):
return self.__bfs_dict
def vertices(self):
""" returns the vertices of a graph """
return list(self.__graph_dict.keys())
def edges(self):
""" returns the edges of a graph """
return self.__generate_edges()
def num_vertices(self):
""" returns the number of vertices of a graph """
return len(self.__graph_dict.keys())
def num_edges(self):
""" returns the number of edges of a graph """
return len(self.__generate_edges())
def add_vertex(self, vertex):
""" If the vertex "vertex" is not in
self.__graph_dict, a key "vertex" with an empty
list as a value is added to the dictionary.
Otherwise nothing has to be done.
"""
if vertex not in self.__graph_dict:
self.__graph_dict[vertex] = {}
def delete_vertex(self,vertex):
if vertex not in self.__graph_dict.keys():
print("The vertex is not in the graph")
else:
for node in self.__graph_dict[vertex]:
self.__graph_dict[node].remove(vertex)
self.__graph_dict.pop(vertex)
def add_edge(self, edge):
""" assumes that edge is of type set, tuple or list;
between two vertices can be multiple edges!
"""
edge = set(edge)
(vertex1, vertex2) = tuple(edge)
if vertex1 in self.__graph_dict.keys() and vertex2 in self.__graph_dict.keys():
if vertex2 in self.__graph_dict[vertex1] and vertex1 in self.__graph_dict[vertex2]:
return
self.__graph_dict[vertex1].add(vertex2)
self.__graph_dict[vertex2].add(vertex1)
elif vertex1 not in self.__graph_dict.keys() and vertex2 in self.__graph_dict.keys():
self.__graph_dict[vertex1] = {vertex2}
self.__graph_dict[vertex2].add(vertex1)
elif vertex1 in self.__graph_dict.keys() and vertex2 not in self.__graph_dict.keys():
self.__graph_dict[vertex2] = {vertex1}
self.__graph_dict[vertex1].add(vertex2)
else:
self.__graph_dict[vertex1] = {vertex2}
self.__graph_dict[vertex2] = {vertex1}
def delete_edge(self, edge):
edge = set(edge)
(vertex1, vertex2) = tuple(edge)
if vertex1 in self.__graph_dict.keys() and vertex2 in self.__graph_dict[vertex1]:
self.__graph_dict[vertex1].remove(vertex2)
#if vertex2 in self.__graph_dict.keys() and vertex1 in self.__graph_dict[vertex2]:
self.__graph_dict[vertex2].remove(vertex1)
else:
print("This edge is not in the graph.")
def __generate_edges(self):
""" A static method generating the edges of the
graph "graph". Edges are represented as sets
with one (a loop back to the vertex) or two
vertices
"""
edges = []
for vertex in self.__graph_dict:
for neighbor in self.__graph_dict[vertex]:
if {neighbor, vertex} not in edges:
edges.append({vertex, neighbor})
return edges
# the bfs_dict need to be renewed every time the node changed in graph
def bfs(self, vertex_s):
"""
use bfs explore graph from a single vertex
return a shortest path tree from that vertex
"""
nd_list = list(self.vertices())
visited = dict((node, 0) for node in nd_list)
nq = deque()
pre_dict, dist = {}, {}
nq.append(vertex_s)
visited[vertex_s]=1
dist[vertex_s] = 0
loop_counts = 0
while nq:
s = nq.popleft()
for node in self.__graph_dict[s]: # for each child/neighbour of current node 's'
loop_counts += 1
#if not node in visited:
if not visited[node]:
nq.append(node) # let 'node' in queue
pre_dict[node] = [s] # the 'parent' (in terms of shortest path from 'root') of 'node' is 's'
dist[node] = dist[s] + 1 # shortest path to 'root'
visited[node]=1 # 'node' is visted
#if node in visited and dist[node] == dist[s] + 1: # still within the shortest path
if visited[node] and dist[node] == dist[s] + 1: # still within the shortest path
if s not in pre_dict[node]: # if this path have NOT been recorded, let's do that now
pre_dict[node].append(s)
if visited[node] and dist[node] > dist[s] + 1: # the previous 'recorded' path is longer than our current path (via node 's'); let's update that path and distance
pre_dict[node] = [s]
dist[node] = dist[s] + 1
#print(" #loops: %d" %loop_counts)
#current_bfs[vertex_s] = pre_dict
return pre_dict
def read_edgelist(self, file):
f = open(file, 'r')
while True:
line = f.readline()
if not line:
break
v1, v2 = line.strip().split()
if v1 != v2: # no self loop
self.add_edge({v1,v2})
def is_connect(self, s, t):
#current_bfs = dict()
pre_map = self.bfs(s)
if t in pre_map:
return [True, pre_map]
return[False, pre_map]
def __str__(self):
res = "vertices: "
for k in self.__graph_dict:
res += str(k) + " "
res += "\nedges: "
for edge in self.__generate_edges():
res += str(edge) + " "
return res
class Node(object):
"""Generic tree."""
def __init__(self, name='', children=None):
self.name = name
if children is None:
children = []
self.children = children
def add_child(self, child):
self.children.append(child)
####not in graph class#############
def bfs_counting(graph, root_vertex, bottom_vertex): # perform analysis twice: 1) set root_vertex = 't'; 2) set root_vertex = 's'
"""
use bfs explore graph from a single vertex
return a shortest path tree from that vertex
"""
#visited = dict()
nd_list = graph.keys()
visited = dict((node, 0) for node in nd_list)
visited[bottom_vertex]=0
nq = deque()# queue for recording current nodes
pre_dict, dist, parents, node_count_dict = {}, {}, {}, {}
nq.append(root_vertex)
visited[root_vertex]=1
dist[root_vertex] = 0
parents[root_vertex]=['fake_root']
node_count_dict['fake_root']=1
while nq:
s = nq.popleft() # dequeue
node_count_dict[s] = 0
for p in parents[s]: # count is defined as the sum of counts from all parents
node_count_dict[s] += node_count_dict[p]
#for node in self.__graph_dict[s]: # for each child/neighbour of current node 's'
if not s in graph.keys():
continue
for node in graph[s]:
#if not node in visited:
if not visited[node]:
nq.append(node) # let 'node' in queue
pre_dict[node] = [s] # the 'parent' (in terms of shortest path from 'root') of 'node' is 's'
dist[node] = dist[s] + 1 # shortest path to 'root'
visited[node]=1 # 'node' is visted
parents[node]=[s] # record 'parents' of this node
else:
parents[node].append(s) # record 'parents' of this node
pre_dict[node].append(s)
node_count_dict.pop('fake_root')
return [pre_dict, node_count_dict] # two returns: 1) tree; 2) node count dictionary
def dfs(root, total_count):
#visited = []
leaf_count = dict()
#total_count = dict()
dfs_helper(root, leaf_count, total_count)
n = leaf_count['root']
for k in total_count.keys():
total_count[k] = total_count[k]/n
return total_count
def dfs_helper(v, leaf_count, total_count):
# Set current to root of binary tree
#visited.append(v.name)
if len(v.children) == 0:
leaf_count[v.name] = 1
else:
leaf_count[v.name] = 0
for nd in v.children:
#print(nd.name)
dfs_helper(nd, leaf_count, total_count)
leaf_count[v.name] += leaf_count[nd.name]
#print(leaf_count)
total_count[nd.name] += leaf_count[nd.name]
#print(total_count)
return
def add_branch(tree_map, current_node, total_count):
total_count[current_node.name] = 0
if current_node.name not in tree_map.keys():
return
children = tree_map[current_node.name]
for child in children:
child_node = Node(child)
current_node.add_child(child_node)
add_branch(tree_map, child_node, total_count)
return
def set_m(graph, eta):
m = int(math.log2((graph.num_vertices()**2)/(eta**2)))
print("m = %d" %m)
return m
#@jit
def cal_bc(graph, m, s_list, t_list): # m must be much smaller than the number of edges
nd_list = list(graph.vertices())
bc_dict = dict((node, 0) for node in nd_list)
for i in range(m):
#ndl_copy = copy.copy(nd_list)
print(i)
if len(nd_list) >=2:
s = choice(nd_list)
s_list.add(s)
nd_list.remove(s)
t = choice(nd_list)
t_list.add(t)
bfsts1 = time.time()
connect, pre_g = graph.is_connect(s, t)
bfsts2 = time.time()
print(" BFS: Duration: %f seconds" %(bfsts2-bfsts1))
dfsts1 = time.time()
if connect:
pre_g_rev, count1 = bfs_counting(pre_g,t,s)
pre_g_rev2, count2 = bfs_counting(pre_g_rev,s,t)
count = dict((node, count1[node] * count2[node]) for node in count1.keys())
count = dict((node, count1[node] / count[t]) for node in count1.keys())
count.pop(s)
count.pop(t)
for node in count.keys():
bc_dict[node] += count[node]
else:
#print("The two vertice are not connected")
continue
dfsts2 = time.time()
print(" BFS counting: Duration: %f seconds" %(dfsts2-dfsts1))
else:
break
return [bc_dict, s_list, t_list]
def maxBC(dict): #to be finished, default remove highest 1
#return sorted(dict, key=dict.get, reverse=True)[:n]
max_value = max(dict.values()) # maximum value
max_keys = [k for k, v in dict.items() if v == max_value]
#print(max_keys)
return max_keys
def get_set(g1, percent = 1.0, eta = 0.1):
#print(g1)
#g1 = read_udgraph('Wiki-Vote.txt')
#bc_dict = dict()
high_bc_set = []
vertice_list_s = {-1}
vertice_list_t = {-1}
m = set_m(g1, eta)
#m = 10
#print(m)
init, vertice_list_s, vertice_list_t = cal_bc(g1, m, vertice_list_s, vertice_list_t) # first calculation
#print(init)
num_nodes = g1.num_vertices()
for i in range(num_nodes**2): # set to 2
#print (i)
vi = maxBC(init)
high_bc_set += vi
if len(high_bc_set) >= percent * num_nodes:
for i in high_bc_set:
print(i)
break
for node in vi:
#print(node)
g1.delete_vertex(node)
init, vertice_list_s, vertice_list_t = cal_bc(g1, m, vertice_list_s, vertice_list_t)
return high_bc_set
if __name__ == "__main__":
graph = Graph()
#path = "email-Eu-core.txt"
path = sys.argv[1]
#path = "compositePPI_bindingOnly_edges.txt"
graph.read_edgelist(path)
#graph.read_edgelist("compositePPI_bindingOnly_edges.txt")
print("Vertices of graph:")
#print(graph.vertices())
print(graph.num_vertices())
print("Edges of graph:")
ts1 = time.time()
m = set_m(graph, 0.1)
#bc_set = get_set(graph, 0.5, 0.1)
percentage = float(sys.argv[2]) # in this version the percentrage is the top1%, 5% etc
bc_set = get_set(graph, percentage, 0.1)
ts2 = time.time()
print("Duration: %d seconds" %(ts2-ts1))
outfile = open(path.split('.')[0] + "_" + str(percentage) +"percentage_high_bc_set.txt", "w")
for i in bc_set:
outfile.write(i)
outfile.write('\n')
outfile.close()
|
29bc7b008f6dfe00a089dafda4b1a606408bd68d | ErikZornWallentin/Fun_Challenges | /Python/Length_Converter/length_converter.py | 3,447 | 4.1875 | 4 | #!/usr/bin/python
'''
Author: Erik Zorn - Wallentin
Created: May. 10 / 2016
This program was created to polish and improve my Python programming skills during my spare time.
This was created in several languages in my repository of code to show the differences in each language with the same functionality.
The script is on Length Conversion, if you don't know what that is, see below link:
http://www.metric-conversions.org/length/centimeters-to-feet.htm
The program will calculate Centimetre to Feet, and Feet to Centimetre.
It starts off by waiting for user input with a menu displayed to the user.
Menu:
1) Centimetre to Feet (cm to ft)
2) Feet to Centimetre (ft to cm)
3) Quit the program (q)
Choosing an option from the menu will allow you to do a specific conversion and ask for more input.
Once it gives you the result from the conversion it will return you to the menu.
The program has error checking to determine if the input from user was valid or not.
'''
import sys, timeit, datetime
import time
import os
'''
Purpose: The main menu that is displayed to the user
Parameters: NONE
Return: NONE
'''
def menu():
print("Please choose one of the following using (1,2,3):")
print("1) Centimetre to Feet (cm to ft)")
print("2) Feet to Centimetre (ft to cm)")
print("3) Quit the program (q)")
'''
Purpose: Checks if the input is only numbers, and gives a correct return value ( success or failure ) depending on the result
Parameters: input ( string input to be checked if it's only numbers )
Return: result (EXIT_SUCESS is 0 or EXIT_FAILURE is 1 or higher)
'''
def checkIsNumber(input):
periodCounter = 0
negativeNumber = False
for i in range(len(input)):
if (input[i] == '-' and i == 0):
#Do nothing as we will accept negative numbers
negativeNumber = True
elif (input[i] == '.'):
periodCounter = periodCounter + 1
if (periodCounter > 1):
print ("Entered input is not a number!\n")
return 0
elif (input[i].isdigit() == False):
print ("Entered input is not a number!\n")
return 0
return 1
userInput = '0'
checker = 1
os.system('clear')
menu()
while (checker == 1):
userInput = raw_input("Please enter a menu option: ")
if (userInput == '1'):
os.system('clear')
#Variables we will use our formula on
feetConverted = 0.0
centimetreInput = 0.0
input = "0"
print("*** Converting Centimetre to Feet (cm to ft) ***\n")
input = raw_input("Please enter Centimetre value: ")
#Check if the input is acceptable
result = checkIsNumber(input)
if (result == 1):
centimetreInput = float(input)
#Convert from Centimetre to Feet
feetConverted = centimetreInput * 0.032808
print("Feet result: %f\n" % feetConverted)
menu()
elif (userInput == '2'):
os.system('clear')
#Variables we will use our formula on
centimetreConverted = 0
feetInput = 0
input = "0"
print("*** Feet to Centimetre (ft to cm) ***\n")
input = raw_input("Please enter Feet value: ")
#Check if the input is acceptable
result = checkIsNumber(input)
if (result == 1):
feetInput = float(input)
#Convert from Feet to Centimetre
centimetreConverted = feetInput / 0.032808
print("Centimetre result: %f\n" % centimetreConverted)
menu()
elif (userInput == '3' or userInput == 'q'):
print("\nNow quitting the program!\n")
checker = 0
else:
os.system('clear')
print("Incorrect input, try again!\n")
menu() |
6426ac00f17c7d1c5879ddf994938cfa0a412e62 | ChienSien1990/Python_collection | /Ecryption/Encrpytion(applycoder).py | 655 | 4.375 | 4 | def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers, and spaces.
shift: 0 <= int < 26
returns: dict
"""
### TODO
myDict={}
for i in string.ascii_lowercase:
if((ord(i)+shift)>122):
myDict[i] = chr(ord(i)+shift-26)
else:
myDict[i] = chr(ord(i)+shift)
for i in string.ascii_uppercase:
if((ord(i)+shift)>90):
myDict[i] = chr(ord(i)+shift-26)
else:
myDict[i] = chr(ord(i)+shift)
return myDict
|
7dddf0cba7cb5f97137282a09323a090931f31f2 | xingchenwan/NeuAcademy | /initialisation.py | 2,893 | 3.9375 | 4 | # Initialisation routine for first time login of an user
import pandas as pd
import numpy as np
from settings import *
from utils import *
def init_user(udata: pd.DataFrame) -> pd.DataFrame:
"""
Initialise a new user in the system
:param udata: the user data df
:return: the updated user data df containing the new information
"""
user_data = pd.Series(0, index=udata.columns)
while True:
user_id = input("Welcome to NeuAcademy v.1. Please enter your preferred ID: ")
if user_id in udata['ID']:
print("ID " + user_id + " already exists. Choose another ID")
else:
user_data['ID'] = user_id
break
while True:
try:
level = int(input("Select your syllabus: \n Physics Aptitude Test (PAT): 1"))
break
except ValueError:
print("Please enter an integer number.")
if level == 1:
print("Syllabus PAT selected.")
response = generate_pat_questionnaire()
# Update user profile using the response to the initial questionnaire
udata = update_user_profile_from_questionnaire(user_data, response)
else: # This will be updated when we have question data for other syllabi
print("Syllabus" + str(level) + "not currently available.")
save_user_data_csv(udata)
return udata
def generate_pat_questionnaire() -> list:
"""
Generate survey question for each and every PAT topic.
:return: A list of integers (length = number of PAT topics) in the range of [1,5] which gauges the self-assessed
ability of the student in each topic.
"""
print("The next few questions are intended to survey your understanding across five broad categories of the PAT"
"syllabus. On a scale of 1 (least understanding) to 5 (best understanding), select your response.")
responses = [0] * NUM_PAT_TOPICS
for i in range(NUM_PAT_TOPICS):
while True:
try:
responses[i] = int(input("Enter an integer from 1 to 5 for"+ PAT_TOPICS[i] + ": "))
if responses[i] >= 1 and responses[i] <= 5:
break
else:
print("Please enter an integer between 1 to 5")
except ValueError:
print("Please enter an integer number.")
return responses
def update_user_profile_from_questionnaire(user_id: pd.Series, responses: list) -> pd.DataFrame:
"""
Update user profile from the questionnaire response
:param user_data: data of the single user presented as a pandas series
:param responses: responses from the questionnaire - a list by default
todo: we have to design an algorithm that assigns appropriate weight to this initial questionnnaire!
:return: a new userdata dataframe that contains the updated information about this user
"""
pass
|
1105fd4cb3e9b95294e5e918b0017e7f109d1aac | sujit4/problems | /interviewQs/InterviewCake/ReverseChars.py | 1,023 | 4.25 | 4 | # Write a function that takes a list of characters and reverses the letters in place.
import unittest
def reverse(list_of_chars):
left_index = 0
right_index = len(list_of_chars) - 1
while left_index < right_index:
list_of_chars[left_index], list_of_chars[right_index] = list_of_chars[right_index], list_of_chars[left_index]
left_index += 1
right_index -= 1
# Tests
class Test(unittest.TestCase):
def test_empty_string(self):
list_of_chars = []
reverse(list_of_chars)
expected = []
self.assertEqual(list_of_chars, expected)
def test_single_character_string(self):
list_of_chars = ['A']
reverse(list_of_chars)
expected = ['A']
self.assertEqual(list_of_chars, expected)
def test_longer_string(self):
list_of_chars = ['A', 'B', 'C', 'D', 'E']
reverse(list_of_chars)
expected = ['E', 'D', 'C', 'B', 'A']
self.assertEqual(list_of_chars, expected)
unittest.main(verbosity=2) |
a88d70f775bc70026cb338561fecd88be94058fb | michaelstreyle/CS160 | /Exercises/Exercise8B.py | 1,263 | 4.03125 | 4 | """
Tree building exercise
Michael Streyle
LIST IMPLEMENTATION
"""
def BinaryTree(r):
return [r, [], []]
def insert_child_left(root, new_branch):
t = root.pop(1)
if len(t) > 1:
root.insert(1, [new_branch, t, []])
else:
root.insert(1, [new_branch, [], []])
return root
def insert_child_right(root, new_branch):
t = root.pop(2)
if len(t) > 1:
root.insert(2, [new_branch, [], t])
else:
root.insert(2, [new_branch, [], []])
return root
def get_root_val(root):
return root[0]
def set_root_val(root, new_val):
root[0] = new_val
def get_child_left(root):
return root[1]
def get_child_right(root):
return root[2]
def clockwise(root):
"""Clockwise tree traversal"""
print(get_root_val(root), end=" ")
if get_child_right(root):
clockwise(get_child_right(root))
if get_child_left(root):
clockwise(get_child_left(root))
def build_tree_lst() -> list:
"""Build a tree and return it"""
tree = BinaryTree('a')
insert_child_left(tree, 'b')
insert_child_right(get_child_left(tree), 'd')
insert_child_right(tree, 'c')
insert_child_left(get_child_right(tree), 'e')
insert_child_right(get_child_right(tree), 'f')
return tree |
2003afa4046346dda230a99effaebb4f337413a6 | fanwangwang/fww_study | /doc/py_example/femknowledge/change.py | 558 | 3.53125 | 4 | #给定一个$5×4$ 的矩阵,把它变成 $4×5$ $2*10$ 的列向量,并且每隔 $4$ 行取一个元素
import numpy as np
A = np.array([[1,2,3,3],[1,2,3,4],[1,1,2,3],[2,0,0,2],[0,0,1,2]])
print(A)
a = np.reshape(A,(4,5))
print(a)
B = np.reshape(A,(4,5),order = 'F')
C = np.reshape(A,(4,5),order = 'C')
print(B)
print(C)
# 变换的时候默认是‘C’,如果加‘order = 'F'’,则是按列排列,例如变换成 $m×n$ 矩阵,
# 则取先取第一列的前 $m$ 个元素组成一行,再接着按列取$m$个元素组成第二行...
|
eb93656378a977bac3503804f3a8ad7123d41385 | fanwangwang/fww_study | /doc/py_example/femknowledge/matrixmutivec.py | 289 | 3.546875 | 4 | # 给定一个 $5×n5$ 的矩阵,$5×1$ 的向量,对矩阵与向量作乘积,以及对向量与数作乘积
import numpy as np
A = np.array([[4,-1,0,0,0],[-1,4,-1,0,0],[0,-1,4,-1,0],[0,0,-1,4,-1],[0,0,0,-1,4]])
b = [1,1,1,1,1]
x = A*b
y = A@b
y = y.reshape(5,1)
print(x)
print(y)
|
d97afa0117f3088d653e118423252078f9b1982c | gcarrara97/projeto_semantix | /projeto_semantix_6_balanco.py | 2,548 | 3.53125 | 4 | arquivo_parcial = open("bank.csv", "r")
arquivo_completo = open("bank-full.csv", "r")
#Questo 6
#BALANO
linhas = arquivo_completo.readlines()
fl = False
emprestimo_imobiliario = 0
balanco = []
for i in linhas:
linha = i.split(';')
if fl == True:
if linha[6] == "\"yes\"":
emprestimo_imobiliario += 1
balanco.append(int(linha[5]))
else:
fl = True
print("Nmero de clientes com emprstimo imobilirio: " + str(emprestimo_imobiliario))
print("MENOR BALANO " + str(min(balanco)))
print("MAIOR BALANO " + str(max(balanco)))
b0 = 0
b0_10000 = 0
b10000_20000 = 0
b20000_30000 = 0
b30000_40000 = 0
b40000_50000 = 0
b50000_60000 = 0
fl = False
for i in linhas:
linha = i.split(';')
if fl == True:
if linha[6] == "\"yes\"":
if int(linha[5]) < 0:
b0 += 1
if int(linha[5]) >= 0 and int(linha[5]) < 10000:
b0_10000 += 1
if int(linha[5]) >= 10000 and int(linha[5]) < 20000:
b10000_20000 += 1
if int(linha[5]) >= 20000 and int(linha[5]) < 30000:
b20000_30000 += 1
if int(linha[5]) >= 30000 and int(linha[5]) < 40000:
b30000_40000 += 1
if int(linha[5]) >= 40000 and int(linha[5]) < 50000:
b40000_50000 += 1
if int(linha[5]) >= 50000 and int(linha[5]) < 60000:
b50000_60000 += 1
else:
fl = True
print("Menor que 0 euros: freq. absoluta de " + str(b0) + " e freq. relativa de " + str(float(b0)/emprestimo_imobiliario))
print("Entre 0 e 10000 euros: freq. absoluta de " + str(b0_10000) + " e freq. relativa de " + str(float(b0_10000)/emprestimo_imobiliario))
print("Entre 10000 e 20000 euros: freq. absoluta de " + str(b10000_20000) + " e freq. relativa de " + str(float(b10000_20000)/emprestimo_imobiliario))
print("Entre 20000 e 30000 euros: freq. absoluta de " + str(b20000_30000) + " e freq. relativa de " + str(float(b20000_30000)/emprestimo_imobiliario))
print("Entre 30000 e 40000 euros: freq. absoluta de " + str(b30000_40000) + " e freq. relativa de " + str(float(b30000_40000)/emprestimo_imobiliario))
print("Entre 40000 e 50000 euros: freq. absoluta de " + str(b40000_50000) + " e freq. relativa de " + str(float(b40000_50000)/emprestimo_imobiliario))
print("Entre 50000 e 60000 euros: freq. absoluta de " + str(b50000_60000) + " e freq. relativa de " + str(float(b50000_60000)/emprestimo_imobiliario))
|
6a28d887ba8bf192a48254a460922cbadd0b0074 | jasonzhixian/PythonForOffer | /Python_exercise/5_print_linked_list_for_end_to_start/exercise_reverse.py | 664 | 3.90625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def printLinkedListFromHeadToTail(self, listNode):
if listNode is None:
return None
result = []
cur = listNode
while cur:
result.append(cur.val)
cur = cur.next
return result
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next= node2
node2.next = node3
node3.next = node4
solution = Solution()
test = ListNode(None)
print(solution.printLinkedListFromHeadToTail(node1))
print(solution.printLinkedListFromHeadToTail(test))
|
dfb0505e3afbc8e12cf9f22f0e65d14cce9cda17 | jasonzhixian/PythonForOffer | /Python_exercise/19_Mirror_of_binary_tree/exercise.py | 691 | 3.609375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#change the exist tree
def mirrorBinaryTree(self, root):
if root == None:
return None
root.left, root.right = root.right, root.left
self.mirrorBinaryTree(root.left)
self.mirrorBinaryTree(root.right)
return root
#create the new tree
def mirrorBinaryTree_2(self, root):
if root == None:
return None
newTree = TreeNode(root.val)
newTree.left = self.mirrorBinaryTree_2(root.left)
newTree.right = self.mirrorBinaryTree_2(root.right)
return newTree |
9fe23b1af531610a538a71a5a2e19986cb992506 | jasonzhixian/PythonForOffer | /exercise_for_tree.py | 4,999 | 3.625 | 4 | #6
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#reconstructbinarytree
def reConstructBinaryTree(self, preorder, inorder):
if not preorder and not inorder:
return None
root = TreeNode(preorder[0])
if set(preorder) != set(inorder):
return None
i = preorder.indes(inorder[0])
root.left = self.reConstructBinaryTree(preorder[1, i+1], inorder[:i])
root.right = self.reConstructBinaryTree(preorder[i+1], inorder[i+1:])
return root
def preorder(self, root):
if root is None:
return None
print(root.val, end = '')
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
if root is None:
return None
self.inorder(root.left)
print(root.val, end = '')
self.inorder(root.right)
def backorder(self, root):
if root is None:
return None
self.backorder(root.left)
self.backorder(root.right)
print(root.val, end = '')
#39
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#maximum depth of binary tree
def maxDepth(self, root):
if root is None:
return 0
else:
max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
#minimum depth of binary tree
def minDepth(self, root):
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
#19
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#change the exist tree
def mirrorBinaryTree(self, root):
if root is None:
return None
root.left, root.right = root.right, root.left
self.mirrorBinaryTree(root.left)
self.mirrorBinaryTree(root.right)
return root
#create the new tree
def mirrorBinaryTree(self, root):
if root is None:
return None
newtree = TreeNode(root.val)
newtree.left = self.mirrorBinaryTree(root.left)
newtree.right = self.mirrorBinaryTree(root.right)
return newtree
#pathSum
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
else:
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-roo.val)
#is symmetric_tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
self.isSymmetricRe(root.left, root.right)
def isSymmetricRe(self, left, right):
if left is None and right is None:
return True
if left is None or right is None or left.val != right.val:
return False
return self.isSymmetricRe(left.left, right.right) and self.isSymmetricRe(left.right, right.left)
#binary tree level order traversal / reverse
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root): #def levelOrderBottom
if root is None:
return []
result, cur = [], [root]
while cur:
next_level, vals = [], []
for node in cur:
vals.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
cur = next_level
result.append(vals)
return result #return result[::-1]
#39_2 is balanced binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#solution one
def getDepth(self, root):
if root is None:
return 0
else:
return max(self.getDepth(root.left), self.getDepth(root.right)) + 1
def isBalanced(self):
if root is None:
return True
if abs(self.getDepth(root.left) - self.getDepth(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
|
73db8a09cd5009c1c9cdca7ffdc92a3f7fc34fab | 12389285/meps | /code/constraints/distribution.py | 7,548 | 3.84375 | 4 | from itertools import permutations, repeat
import numpy
def distribution(schedule, courses):
"""
This function calculates the malus points regarding the spread of course
activities over the week.
This function takes as input arguments:
- the schedule
- list of courses
This function works as follows:
- makes lists with days on which lectures, tutorials and practica
are given
- calculates bonus and malus points regarding the best spread
combinations of tutorials, lectures and practica
"""
malus = 0
# make lists to see on what day the different activities are scheduled
for i in range(len(courses)):
name = courses[i].name
number_activities = courses[i].dif_total
day_lec_1 = None
day_lec_2 = None
day_tut = []
day_pr = []
total_days = []
total_lecs = []
double_lec = 0
for i in range(len(schedule)):
for j in range(len(schedule[i])):
for k in range(len(schedule[i][j])):
if schedule[i][j][k] != None:
course, sort = str(schedule[i][j][k]).split("_")
if course == name:
if 'lec' in sort:
if day_lec_1 == None:
day_lec_1 = i
# add to lecture and total list
total_lecs.append(i)
total_days.append(i)
else:
day_lec_2 = i
if day_lec_2 != day_lec_1:
total_lecs.append(i)
total_days.append(i)
else:
double_lec = 1
elif 'tut' in sort:
# add to tutorial days list
day_tut.append(i)
elif 'pr' in sort:
# add to practica days list
day_pr.append(i)
# in case there are both practica and tutorials
if day_pr and day_tut:
malus = malus + tut_and_prac(day_tut, day_pr, total_days, number_activities)
# in case there are only tutorials and no practica
elif day_tut and not day_pr:
malus = malus + only_tut(day_tut, total_days, total_lecs, double_lec, number_activities)
# in case there are only practica and no tutorials
elif day_pr and not day_tut:
malus = malus + only_prac(day_pr, total_days, total_lecs, double_lec, number_activities)
else:
if double_lec == 1:
malus = malus + 10
return malus
def tut_and_prac(tut, prac, total_days, number_activities):
"""
This function calculates bonus and malus points regarding the best spread
combinations of tutorials, lectures and practica.
"""
# set variables and lists
malus = 0
comb_doubles = []
best_comb = []
combinations = list(list(zip(r, p)) for (r, p) in zip(repeat(tut), permutations(prac)))
# calculate combination list without prac and tut on the same day
for i in range(len(combinations)):
double = 0
for j in range(len(combinations[i])):
num = str(combinations[i][j])
num1, num2 = num.split(',')
num1 = num1.replace('(', '')
if num1 in num2:
double = double + 1
comb_doubles.append(double)
best = numpy.min(comb_doubles)
best_index = [i for i,x in enumerate(comb_doubles) if x == best]
for i in range(len(best_index)):
ind = best_index[i]
best_comb.append(combinations[ind])
# for these combinations, calculate the malus points
tot = []
points_list = []
for i in range(len(best_comb)):
points_tot = 0
for j in range(len(best_comb[i])):
tot = []
tot.extend(total_days)
tot.extend(best_comb[i][j])
tot = list(set(tot))
points_m = spread_malus(number_activities, tot)
points_b = spread_bonus(number_activities, tot)
points_tot = points_tot + (points_m + points_b) / len(best_comb[i])
points_list.append(points_tot)
# choose the option with the smallest amount malus points, and calculate points
best_points = numpy.min(points_list)
best_points_index = numpy.argmin(points_list)
couples = best_comb[best_points_index]
malus = best_points
return malus
def only_tut(day_tut, total_days, total_lecs, double_lec, number_activities):
"""
This function calculates bonus and malus points regarding the best spread
combinations of tutorials and lectures.
"""
malus = 0
double = 0
# if the lectures are on te same day it costs points
if double_lec == 1:
malus = malus + 10
# count malus points
for i in range(len(day_tut)):
total_days.append(day_tut[i])
if day_tut[i] in total_lecs:
double = double + 1
double_frac = double / len(day_tut)
malus = malus + double_frac * 10
# count bonus points for perfectly spread activities
bonus = 0
for i in range(len(day_tut)):
all_days = []
all_days.extend(total_lecs)
all_days.append(day_tut[i])
bonus = bonus + (spread_bonus(number_activities, all_days) / len(day_tut))
malus = malus + bonus
return malus
def only_prac(day_pr, total_days, total_lecs, double_lec, number_activities):
"""
This function calculates bonus and malus points regarding the best spread
combinations of lectures and practica.
"""
malus = 0
double = 0
# if the lectures are on te same day it costs points
if double_lec == 1:
malus = malus + 10
day_pr = list(set(day_pr))
for i in range(len(day_pr)):
total_days.append(day_pr[i])
if day_pr[i] in total_lecs:
double = double + 1
double_frac = double / len(day_pr)
malus = malus + double_frac * 10
# count bonus points for perfectly spread activities
bonus = 0
for i in range(len(day_pr)):
all_days = []
all_days.extend(total_lecs)
all_days.append(day_pr[i])
bonus_this = (spread_bonus(number_activities, all_days) / len(day_pr))
bonus = bonus + bonus_this
malus = malus + bonus
return malus
def spread_malus(number_activities, diff_days):
"""
This function returns malus points if activities are not spread well
enough.
"""
malus = 0
if len(diff_days) == number_activities - 1:
malus = malus + 10
elif len(diff_days) == number_activities - 2:
malus = malus + 20
elif len(diff_days) == number_activities - 3:
malus = malus + 30
return malus
def spread_bonus(number_activities, diff_days):
"""
This function returns bonus points if activities are perfectly spread.
"""
malus = 0
if number_activities == 2:
if diff_days == [0, 3] or diff_days == [1, 4]:
malus = malus - 20
if number_activities == 3:
if diff_days == [0, 2, 4]:
malus = malus - 20
if number_activities == 4:
if diff_days == [0, 1, 3, 4]:
malus = malus - 20
return malus
|
e8ccaa13937f18d9f09a3484df5915e0506f1cc2 | 12389285/meps | /code/constraints/overlap_simulated.py | 1,275 | 4.0625 | 4 | def overlapping(activity, timelock, overlap_dict, roomlock):
"""
This function returns True if the is no overlap with courses given in the
overlap matrix. Otherwise, it returns False.
This function takes as input arguments:
- activity
- time lock and room lock
- overlap matrix
"""
# if it is None it is always true
if activity == None:
return True
else:
# check if two lectures are given in timelock
if '_lec' in activity:
for i in range(len(timelock)):
if i == roomlock:
continue
elif activity == timelock[i]:
return False
# check if no other overlap-course is given in the same time lock
activity = activity.split('_')
for i in range(len(timelock)):
activity_timelock = timelock[i]
if activity_timelock != None:
if i == roomlock:
continue
activity_timelock = timelock[i].split('_')
activity_timelock = activity_timelock[0]
if activity_timelock in overlap_dict[activity[0]]:
if activity_timelock != activity[0]:
return False
return True
|
ecc6ade6a296c0f1d2b4f6567eba9a4d13951e00 | michaelsong93/python-prac | /sep4-2.py | 598 | 3.75 | 4 | lst1 = [('a',1),('b',2),('c','hi')]
lst2 = ['x','a',6]
d = {k:v for k,v in lst1}
s = {x for x in lst2}
print(d)
print(s)
def f(n):
yield n
yield n+1
yield n*n
print([i for i in f(3)])
def merge(l,r):
llen = len(l)
rlen = len(r)
i = 0
j = 0
while i < llen or j < rlen:
if j == rlen or (i < llen and l[i] < r[j]):
yield l[i]
i += 1
else:
yield r[j]
j += 1
# g = merge([1,3,5],[2,4,6])
# while True:
# print(g.__next__())
# print(merge([1,3,5],[2,4,6]))
print([x for x in merge([1,2,5],[3,4,6])]) |
93f460a4b712f9b45b30382d5ffa6213db38d226 | lemacm/python | /loan.py | 2,819 | 4.03125 | 4 | name = input ("Name: ")
def takeincome(num):
if num < 500:
return 'payscale1'
elif num < 1000:
return 'payscale2'
else:
return 'payscale3'
def criteria1 ():
print('''Are you employed?)
- No
- Part time''')
employment = input ('Please choose one of the provided options: ')
if employment == 'No':
print ("Unfortunatelly we cannot lend you any money")
else:
print('''What will you use this money for?
- Debt
- Car
- Holiday''')
purpose = input ('Please choose one of the provided options: ')
criteria2(purpose)
def lencalc (money):
print('''How long do you want to borrow it for(in months)?
- 1
- 6
- 12''')
length = int(input(": "))
calculation = money*5/length
print("We have done our calculation and the good news is that you'll have to pay us back", money * 5,"over", length, "months.")
print("Your monthly rate will be £", calculation)
def criteria2 (strg):
amountborr = [100,200,300,400,500,600,700,800,900,1000]
income = int (input("What's your annual income?: "))
if takeincome(income)== 'payscale1':
if strg == 'Debt':
print ("you can borrow between £100 and £400.")
amount = int(input("How much would you like to borrow? (The amount has to be in hundreds): "))
if amount in amountborr[0:4]:
print ("Luky you, we can lend you", amount,"pounds straightaway.")
lencalc (amount)
else:
print("Sorry, it has to be between £100 and £400.")
else:
print ("you can borrow between £100 and £600.")
amount = int(input("How much would you like to borrow? "))
if amount in amountborr[0:6]:
print ("Luky you, we can lend you", amount,"pounds straightaway.")
lencalc (amount)
else:
print("Sorry, it has to be between £100 and £600.")
elif takeincome(income)== 'payscale2':
print ("you can borrow between £100 and £1000.")
amount = int(input("How much would you like to borrow? "))
if amount in amountborr[0:]:
print ("Luky you, we can lend you", amount,"pounds straightaway.")
lencalc (amount)
else:
print("Sorry, it has to be between £100 and £1000.")
else:
print(name,",you are making lots of money, you don't need a loan!")
def checkage():
age = int (input ("How old are you: "))
if age <=18:
print (name,",you are too young to get a loan!")
else:
criteria1()
checkage()
|
4c1e3608010a0b5c306c5fbd10bc00b07fc0e771 | sishu7/common-interview-questions | /ZeroDuplicates.py | 575 | 3.625 | 4 | #zeroes duplicates in a list, after first instance
def zero_duplicates(l):
dict1 = {}
for i in range(0, len(l)):
if l[i] in dict1: l[i] = 0
else: dict1[l[i]] = 1
return l
print zero_duplicates([1, 2, 2, 3, 4, 4, 5, 5, 6, 6])
#zeroes all duplicates in a list
def zero_duplicates2(l):
dict1 = {}
for i in range(0, len(l)):
if l[i] not in dict1: dict1[l[i]] = 1
else: dict1[l[i]] += 1
for j in range(0, len(l)):
if dict1[l[j]] > 1: l[j] = 0
return l
print zero_duplicates2([1, 2, 2, 3, 4, 4, 5, 5, 6, 6])
|
b73eef9b47783fca87f8bb1201a46bebd0cc1e3e | sishu7/common-interview-questions | /StringComparison.py | 388 | 3.84375 | 4 | #compares strings character by characters
def compare(str1, str2):
if len(str1) == len(str2):
for i in range(0, len(str1)):
if str1[i] != str2[i]:
return False
else:
return False
return True
print compare('abc', 'abc')
print compare('abd', 'abc')
print compare(' love you', 'I love you')
print compare('I love you', 'I love you')
|
6c3c5507ecf07b53bf40a1353ba04447ea80d882 | ErikWeisz5/chapter_work | /3/6.py | 149 | 3.765625 | 4 | d = int(input("your day"))
m = int(input("your month"))
y = int(input("your year"))
if d * m == y :
print("magic")
else :
print("not magic") |
84006abd27c93fcb1fd6fe813161f34ab0177e9f | ErikWeisz5/chapter_work | /4/3.py | 300 | 3.765625 | 4 | l = int(input("number of laps: "))
r = set()
a = 0
b = 0
while a < l:
seconds = int(input("Lap time: "))
r.add(seconds)
a += 1
r = list(r)
r.sort()
while b < l:
b += r[b]
average = b/l
print("fastest lap : ", r[0])
print("Slowest Lap : ", r[a-1])
print("average lap : ", average) |
1946e3e82bc870dc367c8d3b9b9c19536bb2aed4 | jruizvar/jogos-data | /aula/variable.py | 495 | 3.515625 | 4 | """
Variables in tensorflow
"""
import tensorflow as tf
"""
RANK 0
"""
a = tf.Variable(4, name='a')
b = tf.Variable(3, name='b')
c = tf.add(a, b, name='c')
print("Variables in TF\n")
print(a)
print(b)
print(c)
print()
with tf.Session() as sess:
sess.run(a.initializer)
sess.run(b.initializer)
a_val = a.eval()
b_val = b.eval()
c_val = c.eval()
print("The value of a:", a_val)
print("The value of b:", b_val)
print("The value of c:", c_val)
print()
|
5a748bacb223ad9de8620dd4ebcad3c457525ef8 | JuanSebastianOG/Analisis-Numerico | /Talleres/PrimerCorte/PrimerTaller/CuadraticaMejorada.py | 670 | 3.953125 | 4 | #Implementacion de una ecuación que mejora la ecuación cuadratica original
import math
def calculoOriginal( a, b, c ):
x0 = (-b - math.sqrt( b**2 - 4*a*c )) / (2*a)
x1 = (-b + math.sqrt( b**2 - 4*a*c )) / (2*a)
print("Los valores de las raices con la formula original son: Xo -> ", x0, " X1 -> ", x1)
def calculoMejorado( a, b, c ):
x0 = (2*c) / (-b - math.sqrt( b**2 - 4*a*c ))
x1 = (2*c) / (-b + math.sqrt( b**2 - 4*a*c ))
print("Los valores de las raices con la formula mejorada son: Xo -> ", x0, " X1 -> ", x1)
if __name__ == "__main__":
calculoOriginal( 3, 9 ** 12, -3 )
calculoMejorado( 3, 9 ** 12, -3 )
|
934bdc157134659f5fc834ea4bce96bd6df629a2 | JuanSebastianOG/Analisis-Numerico | /Talleres/PrimerCorte/PrimerTaller/Algoritmos/Metodo_Newton.py | 1,285 | 4.25 | 4 | #Implementación del método de Newton para encontrar las raices de una función dada
from matplotlib import pyplot
import numpy
import math
def f( x ):
return math.e ** x - math.pi * x
def fd( x ):
return math.e ** x - math.pi
def newton( a, b ):
x = (a + b) / 2
it = 0
tol = 10e-8
errorX = []
errorY = []
raiz = x - ( f(x) / fd(x) )
while abs( raiz - x ) > tol:
if it > 0:
errorX.append( abs( raiz - x ) )
it = it + 1
x = raiz
raiz = x - ( f(x) / fd(x) )
if it > 1:
errorY.append( abs( raiz - x ) )
print("La raiz que se encuentra en el intervalo ", a, ", ", b, " es aproximadamente: ", raiz )
print("El numero de iteraciones que se obtuvieron: ", it )
pol = numpy.polyfit(errorX, errorY, 2)
pol2 = numpy.poly1d( pol )
cX = numpy.linspace( errorX[0], errorX[len(errorX) - 1], 50 )
cY = pol2( cX )
pyplot.plot( cX, cY )
pyplot.xlabel("Errores X ")
pyplot.ylabel("Errores Y ")
pyplot.title("Metodo de Newton: \n Errores en X vs. Errores en Y")
pyplot.grid()
pyplot.show()
#------------------------MAIN------------------------------------------
if __name__ == "__main__":
newton( 0, 1 )
newton( 1, 2 )
|
72f12e63fbac4561a74211964ab031f5ffb29212 | derick-droid/pythonbasics | /files.py | 905 | 4.125 | 4 | # checking files in python
open("employee.txt", "r") # to read the existing file
open("employee.txt", "a") # to append information into a file
employee = open("employee.txt", "r")
# employee.close() # after opening a file we close the file
print(employee.readable()) # this is to check if the file is readable
print(employee.readline()) # this helps read the first line
print(employee.readline()) # this helps to read the second line after the first line
print(employee.readline()[0]) # accessing specific data from the array
# looping through a file in python
for employees in employee.readline():
print(employee)
# adding information into a file
employee = open("employee.txt", "a")
print(employee.write("\n derrick -- for ICT department"))
employee.close()
# re writing a new file or overwriting a file
employee = open("employee1.txt", "w")
employee.write("kelly -- new manager")
|
8cf687f5d815f6fc2b0940d55d30e46cd1c7355a | derick-droid/pythonbasics | /exponent functions.py | 184 | 3.765625 | 4 | def large_number(base_number, power_number):
result = 1
for index in range(power_number):
result = result * base_number
return result
print(large_number(3, 2))
|
16086860e6bf740354f6cdb0537fbbe3f39e85ae | derick-droid/pythonbasics | /nest2dic.py | 404 | 4.09375 | 4 | # creating nested dictionary with for loop
aliens = []
for alien_number in range (30):
new_alien = {
"color" : "green",
"point" : 7,
"speed" : "high"
}
aliens.append(new_alien)
print(aliens)
for alien in aliens[:5]:
if alien["color"] == "green":
alien["color"] == "red"
alien["point"] == 8
alien["speed"] == "very high"
print(alien) |
ea96c07f9845aca38a5011f1009a7dc4b8de30e9 | derick-droid/pythonbasics | /dictionary.py | 686 | 3.53125 | 4 | # returning dictionary in functionn
def user_dictionary (first_name, last_name):
full = {
"first_name" : first_name,
"last_name" : last_name
}
return full
musician = user_dictionary("ford", "dancan")
print(musician)
# using optinal values in dictionary
def dev_person(occupation, age, home_town = ""):
if home_town:
person = {
"occupation" : occupation,
"age" : age,
"home_town" : home_town
}
return person
else:
person = {
"occupation" : occupation,
"age" : age
}
return person
user = dev_person("software developer", "23", "Migori")
print(user)
|
95a9f725607b5acc0f023b0a0af2551bec253afd | derick-droid/pythonbasics | /dictexer.py | 677 | 4.90625 | 5 | # 6-5. Rivers: Make a dictionary containing three major rivers and the country
# each river runs through. One key-value pair might be 'nile': 'egypt'.
# • Use a loop to print a sentence about each river, such as The Nile runs
# through Egypt.
# • Use a loop to print the name of each river included in the dictionary.
# • Use a loop to print the name of each country included in the dictionary.
rivers = {
"Nile": "Egypt",
"Amazon": "America",
"Tana": "Kenya"
}
for river, country in rivers.items():
print(river + " runs through " + country)
print()
for river in rivers.keys():
print(river)
print()
for country in rivers.values():
print(country) |
dcf2b3140557d00145cdcbc2cddddedc08e6095d | derick-droid/pythonbasics | /listfunctions.py | 248 | 3.828125 | 4 | lucky_numbers = [1, 2, 3, 4, 5, 6, 7]
friends = ["derrick", "jim", "jim", "trump", "majani" ]
friends.extend(lucky_numbers) # to add another list on another list
print(friends)
print(friends.count("jim")) # to count repetitive objects in a list
|
6da039c504277c5a23ca5a744faa1f2341c58105 | derick-droid/pythonbasics | /persona.py | 446 | 3.78125 | 4 | class Robots:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
def introduce_yourself(self):
print("my name is " + self.name )
print("I am " + self.color )
print("I weigh " + self.weight)
r1 = Robots("Tom", "blue", "34kg")
r2 = Robots("Derrick", "yellow", "50kgs")
r1.introduce_yourself()
print(" ")
r2.introduce_yourself() |
448b01b0daa1f1cb13ac286d3f4c600318cf8a30 | derick-droid/pythonbasics | /module.py | 262 | 3.890625 | 4 | # from largest_number import largest_number
# biggest_number = largest_number(numbers)
# print(biggest_number)
from largest_number import find_biggest_number
numbers = [2, 3, 73, 83, 27, 7, ]
biggest_number = find_biggest_number(numbers)
print(biggest_number)
|
935e0579d7cbb2da005c6c6b1ab7f548a6694a86 | derick-droid/pythonbasics | /slicelst.py | 2,312 | 4.875 | 5 | # 4-10. Slices: Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that program’s list.
# • Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# • Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
numbers = [1, 3, 2, 4, 5, 6, 7, 8, 9]
slice1 = numbers[:3]
slice2 = numbers[4:]
slice3 = numbers[-3:]
print(f"The first three items in the list are:{slice1}")
print(f"The items from the middle of the list are:{slice2}")
print(f"The last three items in the list are:{slice3}")
print()
# 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1
# (page 60). Make a copy of the list of pizzas, and call it friend_pizzas .
# Then, do the following:
# • Add a new pizza to the original list.
# • Add a different pizza to the list friend_pizzas .
# • Prove that you have two separate lists. Print the message, My favorite
# pizzas are:, and then use a for loop to print the first list. Print the message,
# My friend’s favorite pizzas are:, and then use a for loop to print the sec-
# ond list. Make sure each new pizza is stored in the appropriate list.
print()
pizzas = ["chicago pizza", "new york_style pizza", "greek pizza", "neapolitans pizza"]
friends_pizza = pizzas[:]
pizzas.append("sicilian pizza")
friends_pizza.append("Detroit pizza")
print(f"my favourite pizzas are:{pizzas}")
print()
print(f"my friend favourite pizzas are:{friends_pizza}")
print()
print("my favourite pizzas are: ")
for pizza in pizzas:
print(pizza)
print()
print("my favourite pizzas are: ")
for items in friends_pizza:
print(items)
print()
#
# 4-12. More Loops: All versions of foods.py in this section have avoided using
# for loops when printing to save space. Choose a version of foods.py, and
# write two for loops to print each list of foods.
food_stuff = ["cake", "rice", "meat", "ice cream", "banana"]
food = ["goat meat", "pilau", "egg stew", "fried", "meat stew"]
for foodz in food_stuff:
print(foodz)
print()
for itemz in food:
print(itemz) |
5a827e2d5036414682f468fac5915502a784f486 | derick-droid/pythonbasics | /exerdic.py | 2,972 | 4.5 | 4 | # 6-8. Pets: Make several dictionaries, where the name of each dictionary is the
# name of a pet. In each dictionary, include the kind of animal and the owner’s
# name. Store these dictionaries in a list called pets . Next, loop through your list
# and as you do print everything you know about each print it
rex = {
"name" : "rex",
"kind": "dog",
"owner's name" : "joe"
}
pop = {
"name" :"pop",
"kind" : "pig",
"owner's name": "vincent"
}
dough = {
"name": "dough",
"kind" : "cat",
"owner's name" : "pamna"
}
pets = [rex, pop, dough ]
for item in pets:
print(item)
print()
# 6-9. Favorite Places: Make a dictionary called favorite_places . Think of three
# names to use as keys in the dictionary, and store one to three favorite places
# for each person. To make this exercise a bit more interesting, ask some friends
# to name a few of their favorite places. Loop through the dictionary, and print
# each person’s name and their favorite places.
favorite_places = {
"derrick": {
"nairobi", "mombasa", "kisumu"
},
"dennis":{
"denmark", "thika", "roman"
},
"john": {
"zambia", "kajiado", "suna"
}
}
for name, places in favorite_places.items(): # looping through the dictionary and printing only the name variable
print(f"{name} 's favorite places are :")
for place in places: # looping through the places variable to come up with each value in the variable
print(f"-{place}")
print()
# 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so
# each person can have more than one favorite number. Then print each person’s
# name along with their favorite numbers.
favorite_number = {
"derrick" : [1, 2, 3],
"don" : [3, 5, 7],
"jazzy" : [7, 8, 9]
}
for name, fav_number in favorite_number.items():
print(f"{name} favorite numbers are: ")
for number in fav_number:
print(f"-{number}")
# 6-11. Cities: Make a dictionary called cities . Use the names of three cities as
# keys in your dictionary. Create a dictionary of information about each city and
# include the country that the city is in, its approximate population, and one fact
# about that city. The keys for each city’s dictionary should be something like
# country , population , and fact . Print the name of each city and all of the infor-
# mation you have stored about it.
cities = {
"Nairobi" : {
"population" : "1400000",
"country" : "kenya",
"facts" : "largest city in East Africa"
},
"Dar-es-salaam" : {
"population" : "5000000",
"country" : "tanzania",
"facts" : "largest city in Tanzania"
},
"Kampala" : {
"population" : "1000000",
"country" : "Uganda",
"facts" : "The largest city in Uganda"
}
}
for city, information in cities.items():
print(f"{city}:")
for fact,facts in information.items():
print(f"-{fact}: {facts}")
|
d65f32a065cc87e5de526a718aeea6d601e1ac06 | derick-droid/pythonbasics | /iflsttry.py | 2,930 | 4.5 | 4 | # 5-8. Hello Admin: Make a list of five or more usernames, including the name
# 'admin' . Imagine you are writing code that will print a greeting to each user
# after they log in to a website. Loop through the list, and print a greeting to
# each user:
# • If the username is 'admin' , print a special greeting, such as Hello admin,
# would you like to see a status report?
# • Otherwise, print a generic greeting, such as Hello Eric, thank you for log-
# ging in again.
usernames = ["derick-admin", "Erick", "charles", "yusuf"]
for name in usernames:
if name == "derick-admin":
print(f"Hello admin , would you like to see status report")
else:
print(f"Hello {name} , thank you for logging in again")
#
# 5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is
# not empty.
# • If the list is empty, print the message We need to find some users!
# • Remove all of the usernames from your list, and make sure the correct
# message is printed.
users = ["deno", "geogre", "mulla", "naomi"]
users.clear()
if users:
for item in users:
print(f"hello {item}")
else:
print("we need at least one user")
print()
#
# 5-10. Checking Usernames: Do the following to create a program that simulates
# how websites ensure that everyone has a unique username.
# • Make a list of five or more usernames called current_users .
# • Make another list of five usernames called new_users . Make sure one or
# two of the new usernames are also in the current_users list.
# • Loop through the new_users list to see if each new username has already
# been used. If it has, print a message that the person will need to enter a
# new username. If a username has not been used, print a message saying
# that the username is available.
# •
# Make sure your comparison is case insensitive. If 'John' has been used,
# 'JOHN' should not be accepted.
web_users = ["derrick", "moses", "Raila", "john", "ojwang", "enock"]
new_users = ["derrick", "moses", "babu", "vicky", "dave", "denver"]
for user_name in new_users:
if user_name in web_users:
print("please enter a new user name ")
else:
print("the name already registered ")
print()
# 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such
# as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
# • Store the numbers 1 through 9 in a list.
# • Loop through the list.
# • Use an if - elif - else chain inside the loop to print the proper ordinal end-
# ing for each number. Your output should read "1st 2nd 3rd 4th 5th 6th
# 7th 8th 9th" , and each result should be on a separate line
ordinary_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in ordinary_numbers:
if number == 1:
print(f'{number}st')
elif number == 2:
print(f"{number}nd")
elif number == 3:
print(f"{number}rd")
else:
print(f"{number}th")
|
80bb7af9cb2b49a297419ccdd8d6ae2d486f244a | leticiasayuri/introducao-pandas | /introducao/dataframe.py | 1,541 | 3.75 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Aluno': ["Wilfred", "Abbie", "Harry", "Julia", "Carrie"],
'Faltas': [3, 4, 2, 1, 4],
'Prova': [2, 7, 5, 10, 6],
'Seminário': [8.5, 7.5, 9.0, 7.5, 8.0]})
print("DataFrame\n", df, "\n")
print("Tipos no DataFrame\n", df.dtypes, "\n")
print("Colunas\n", df.columns, "\n")
print("Valores da coluna Seminário\n", df["Seminário"], "\n")
print("Informações matemáticas\n", df.describe(), "\n")
# Ordenação de DataFrame
print("Ordenação pela coluna Seminário\n",
df.sort_values(by="Seminário"), "\n")
# Seleção de valores pelo index
print("Selação de valores por índice (índice 3)\n", df.loc[3], "\n")
# Seleção de acordo com critérios condicionais
# Boolean Indexing
# Seleção das linhas em que o valor da coluna Seminário seja acima de 8.0
print("Seleção por critérios condicionais\nSeleção das linhas em que o valor da coluna Seminário seja acima de 8.0\n",
df[df["Seminário"] > 8.0], "\n")
# Condições de múltiplas colunas (deve-se usar operadores bitwise)
# Seleção das linhas em que o valor da coluna Seminário seja acima de 8.0
# e o valor da coluna Prova não seja menor que 3
print("Seleção por critérios condicionais de múltiplas colunas\nSeleção das linhas em que o valor da coluna Seminário seja acima de 8.0 e o valor da coluna Prova não seja menor que 3\n",
df[(df["Seminário"] > 8.0) & (df["Prova"] > 3)], "\n")
|
dec5f53cc6965129b4eeea95ac949cd8fa2fa3ba | 781-Algorithm/JeonPanGeun | /Algo_python/[BOJ] 10773.py | 1,287 | 3.75 | 4 |
# 백준 10773 제로
# 첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000)
#
# 이후 K개의 줄에 정수가 1개씩 주어진다.
# 정수는 0에서 1,000,000 사이의 값을 가지며,
# 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경우 해당 수를 쓴다.
#
# 정수가 "0"일 경우에 지울 수 있는 수가 있음을 보장할 수 있다.
class Stack:
def __init__(self):
self.top = []
self.cnt = 0
def push(self, item):
self.top.append(item)
self.cnt += 1
def pop(self):
if not self.isEmpty():
self.cnt -= 1
return self.top.pop(-1)
else:
print("Stack underflow")
exit()
def peek(self):
if not self.isEmpty():
return self.top[-1]
else:
print("underflow")
exit()
def isEmpty(self):
return self.cnt == 0
# return len(self.top) == 0
def size(self):
return self.cnt
n = int(input())
stack = []
# stack2 = Stack()
for _ in range(n):
money = int(input())
if money != 0:
stack.append(money)
# stack2.push(money)
elif money == 0:
stack.pop(-1)
# stack2.pop()
print(sum(stack))
|
0ed70af907f37229379d7b38b7aaae938a7fc31a | adamkozuch/scratches | /scratch_4.py | 584 | 4.15625 | 4 | def get_longest_sequence(arr):
if len(arr) < 3:
return len(arr)
first = 0
second = None
length = 0
for i in range(1, len(arr)):
if arr[first] == arr[i] or (second and arr[second]== arr[i]):
continue
if not second:
second = i
continue
if i - first > length:
length = i - first
first = second
second = i
if len(arr) - first > length:
length = len(arr) - first
return length
print(get_longest_sequence([1]))
print(get_longest_sequence([5,1,2,1,2,5]))
|
286fe8a0f431330f9fc43b430646ff942254a602 | jiz148/blueprint_editor | /model/operation/implement/multiply.py | 732 | 3.828125 | 4 | """
Operation: Multiply
"""
def generate_code(json_dict, lang='python'):
result = ''
multiply_1, multiply_2, output = parse_json(json_dict)
if lang == 'python':
result = "{} = {} * {}".format(output, multiply_1, multiply_2)
return result
def parse_json(json_dict):
"""
@param json_dict: should have keys: multiply_1, multiply_2, output
@return: strings of multiply_1, multiply_2, output
"""
try:
return str(json_dict['multiply_1']), str(json_dict['multiply_2']), str(json_dict['output'])
except Exception:
raise KeyError('Error while paring: Multiply')
if __name__ == '__main__':
print(generate_code({'multiply_1': 'a', 'multiply_2': 'b', 'output': 'asd'}))
|
1bbb879b68e07c8c9b20612ef956ed3fdfd4da51 | FatherZosima/CLV-Wishing-Well | /sim.py | 5,108 | 3.546875 | 4 | import random
import matplotlib.pyplot as plt
import numpy as np
import enum
class GambleOutcomes(enum.Enum):
Won = 1
Lost = 2
NoPlay = 3
class Player:
def __init__(self, startingHoldings, playerID):
self.currentHoldings = startingHoldings
self.holdingHistory = [startingHoldings]
self.gameHistory = [[] for f in range(numRounds)]
self.gamesPlayed = 0
self.playerID = playerID
def gamble(self):
gambleStatus = GambleOutcomes.NoPlay
global currentPot
if(self.wouldGamble()):#check if this a gamble the player might make
moneyToGamble = self.gambleAmount()
#now to actually test if they won
likelihood = 2.0/np.pi * np.arctan(0.1*moneyToGamble/currentPot)#2.0/np.pi * np.arctan(0.1*moneyToGamble/currentPot)
if(likelihood < minimumProbability): likelihood = minimumProbability
# likelihood = np.round(likelihood,3)
# print("calculating likelihood for player",self.playerID,"-",likelihood)
winningNum = random.uniform(0,1.0)
if(winningNum <likelihood):
gambleStatus = GambleOutcomes.Won
currentPot += moneyToGamble
self.currentHoldings += currentPot*(1-bankSkim)
currentPot *= bankSkim
else:
gambleStatus = GambleOutcomes.Lost
self.currentHoldings -= moneyToGamble
currentPot += moneyToGamble
self.gamesPlayed +=1
self.gameHistory[currRound].append(gambleStatus)
return gambleStatus
#would the player gamble
def wouldGamble(self):
return (self.currentHoldings > 0.1) #gamble as long as they have at least $0.1
#how much would the player gamble
def gambleAmount(self):
rand = random.uniform(0,0.5) #bet betwen 0-50% of earnings
return min(rand*self.currentHoldings,10000) #never bet more than 1000 at a time
#add currentHoldings to history of holdings (occurs at end of rounds)
def updateHistory(self):
self.holdingHistory.append(self.currentHoldings)
def printHistory(self):
wins = 0
losses = 0
noplays =0
for game in self.gameHistory:
for attempt in game:
if attempt == GambleOutcomes.Won: wins+=1
elif attempt == GambleOutcomes.Lost: losses +=1
elif attempt == GambleOutcomes.NoPlay: noplays+=1
hist = str(wins)+"/"+str(losses)+"/"+str(noplays)+"/"+str(self.gamesPlayed)
print("Player",self.playerID,"Final Balance:",np.round(self.currentHoldings,2),"Wins/Losses/NoPlays/TotalPlays",hist)
bankHoldings = 0
bankHoldingHistory = [bankHoldings]
bankSkim = 0.05 #bank skims 5% to build big pot
bigPayoutFrequency = 100 #big pot happens every 100 times
numRounds = 500
currRound = 0
currentPot = 5 #start with a small pot first round
numPlayers = 500
defaultStartingMoney = 500 #amount each player starts with
minimumProbability = 0.005 #at least 1/100 chance for any player
#populate list of players
players = []
for i in range(numPlayers):
p = Player(defaultStartingMoney, i)
players.append(p)
for i in range(numRounds):
if(i%bigPayoutFrequency==0 and i!=0):
currentPot+= bankHoldings
bankHoldings = 0
print("**************************ROUND",i,"**************************")
#players spend money until someone wins or round ends
roundWon = False
attempts = 0
while(roundWon==False):
#pick random palyer
randPlayer = np.random.randint(numPlayers)
#print("P",randPlayer," ($",players[randPlayer].currentHoldings,") attempting gamble POT:",currentPot)
gambleStatus = players[randPlayer].gamble()
#print("outcome:",gambleStatus)
if(gambleStatus!=GambleOutcomes.NoPlay): attempts+=1
#if(gambleStatus==GambleOutcomes.NoPlay):
#print("P",randPlayer,"did not play this round,",i)
if(gambleStatus==GambleOutcomes.Won): #if player won
print("P",randPlayer, "won round",i,"after",attempts,"attempts")
bankHoldings += currentPot
currentPot = 5 #start next round with $5
roundWon = True
break
for p in players:
p.updateHistory()
bankHoldingHistory.append(bankHoldings)
currRound+=1
for p in players:
p.printHistory()
rounds = np.arange(currRound+1)
plt.figure()
for p in players:
plt.plot(rounds, p.holdingHistory)
plt.plot(rounds, bankHoldingHistory, label='Bank Holdings')
plt.xlabel("Round number")
plt.ylabel("Current $ owned")
title = "Holdings over rounds for "+str(numPlayers)+" players"
plt.title(title)
plt.legend()
finalHoldings = []
for p in players:
finalHoldings.append(p.currentHoldings)
plt.figure()
logbins = np.geomspace(min(finalHoldings), max(finalHoldings), 10)#split into 20 bins
plt.hist(finalHoldings, bins=logbins)
plt.xscale('log')
plt.ylabel("number of players owning amount")
plt.xlabel("final $ owned")
plt.title("Final holdings")
plt.show()
|
4c9029512a3446a50058a0d7099b71cfb3ad2574 | kKunov/Haskel_exam | /03-NameMatching.py | 1,786 | 3.90625 | 4 | def get_known_m_f():
known_m_f = [0, 0]
known_m_f[0] = input("Males names: ")
known_m_f[1] = input("females names: ")
known_m_f[0] = int(known_m_f[0]) # Tuk gi preobrazuvam za da moga
known_m_f[1] = int(known_m_f[1]) # sled tova da gi polzvam bez da go pravq
return known_m_f
def helper_get_names():
name = input("Input Name or 'no' for no more names: ")
is_ends_with_correct = (
name == 'no' or
name.endswith('ss') or
name.endswith('tta')
)
while is_ends_with_correct is False:
name = input("Its not valid name, try again:")
is_ends_with_correct = (
name == 'no' or
name.endswith('ss') or
name.endswith('tta')
)
return name
def get_names():
names = []
names.append(helper_get_names())
while names[len(names) - 1] != 'no':
names.append(helper_get_names())
names.pop() # tuk pop-vam posledniq element za da e po-chist
# masiva zashtoto realno posledniq element e "no"
return names
def name_maching(known_m_f, names):
num_males = 0
num_females = 0
for name in names:
if name.endswith('ss'):
num_males += 1
elif name.endswith('tta'):
num_females += 1
unknown_males = num_males - known_m_f[0]
unknown_females = num_females - known_m_f[1]
male_percentage = 1 / unknown_males
female_percentage = 1 / unknown_females
print("%s %s" % (male_percentage, female_percentage,))
percentage = 1 * male_percentage * female_percentage
percentage *= 100
print("%s percent" % (percentage,))
def main():
known_m_f = get_known_m_f()
names = get_names()
name_maching(known_m_f, names)
if __name__ == '__main__':
main()
|
e06f5970d225977b18877e7c40cbc04cc748aa09 | cvtorrisi93/cp1404practicals | /prac_04/list_exercises.py | 1,181 | 3.9375 | 4 | """
CP1404/CP5632 Practical - Christian Torrisi
List exercises
"""
USERNAMES = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn',
'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob']
def main():
numbers = get_numbers()
print_number_outputs(numbers)
username = input("Username: ")
check_username_access(username)
def check_username_access(username):
"""Check if user input matches any element in USERNAMES list"""
if username in USERNAMES:
print("Access granted")
else:
print("Access denied")
def print_number_outputs(lst):
print("The first number is {}".format(lst[1]))
print("The last number is {}".format(lst[-1]))
print("The smallest number is {}".format(min(lst)))
print("The largest number is {}".format(max(lst)))
print("The average of numbers is {}".format(sum(lst) / len(lst)))
def get_numbers(x=5):
"""Gets numbers based on above parameter from the user"""
numbers = []
for i in range(x):
number = int(input("Number: "))
numbers.append(number)
return numbers
main()
|
c5812e210bf7b92a7f46b90edab07feef8cc9fa1 | cvtorrisi93/cp1404practicals | /prac_03/scores.py | 1,118 | 4.0625 | 4 | """
CP1404/CP5632 - Practical
Scores program to determine what the score is based on value
"""
import random
MIN_SCORE = 0
MAX_SCORE = 100
def main():
output_file = open("results.txt", 'w')
number_of_scores = get_valid_integer("Enter a number of scores to generate: ")
for i in range(number_of_scores):
score = get_random_score()
result = determine_score(score)
print("{} is {}".format(score, result), file=output_file)
def get_random_score():
"""Produces a random int between the minimum and maximum score"""
score = random.randint(MIN_SCORE, MAX_SCORE)
return score
def get_valid_integer(prompt):
"""Get valid integer from user"""
valid_input = False
while not valid_input:
try:
number = int(input(prompt))
valid_input = True
except ValueError:
print("Error: not a valid integer")
return number
def determine_score(score):
"""Computes the score"""
if score >= 90:
return "Excellent"
elif score >= 50:
return "Passable"
else:
return "Bad"
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.