blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
437b86dfd60c3f9e73649c1c6c9af35abfc3ced1 | nicohnavarro/curso_python | /01_ejercicios_practicos/00_calculadora.pyw | 3,224 | 3.5625 | 4 | from tkinter import * #Importamos la biblioteca necesaria para crear GUI
root=Tk()
miFrame=Frame(root)
miFrame.pack()
operador=""
resultado=0
#-----------------Pantalla---------------------------
numeroPantalla=StringVar()
pantalla=Entry(miFrame,textvariable=numeroPantalla)
pantalla.grid(row=1,column=1,padx=4,pady=4,columnspan=4)
pantalla.config(background="black",fg="white",justify="right")
#Colspan funcion web
#-----------------Pulsaciones Teclado----------------
def numeroPulsado(num):
global operador
if operador!= "":
numeroPantalla.set(num)
operador=""
else:
numeroPantalla.set(numeroPantalla.get()+ num)
#-----------------Operaciones---------------------------
def suma(num):
global operador
global resultado
resultado+=int(num)
operador="suma"
numeroPantalla.set(resultado)
#-----------------Funcion resultado----------------
def el_resultado():
global resultado
numeroPantalla.set(resultado+int(numeroPantalla.get()))
resultado=0
#-----------------Fila 1---------------------------
btnSiete=Button(miFrame,text="7",width=3,background="grey",command=lambda:numeroPulsado("7"))
btnSiete.grid(row=2,column=1)
btnOcho=Button(miFrame,text="8",width=3,background="grey",command=lambda:numeroPulsado("8"))
btnOcho.grid(row=2,column=2)
btnNueve=Button(miFrame,text="9",width=3,background="grey",command=lambda:numeroPulsado("9"))
btnNueve.grid(row=2,column=3)
btnDiv=Button(miFrame,text="/",width=3,background="black",fg="green")
btnDiv.grid(row=2,column=4)
#-----------------Fila 2---------------------------
btnCuatro=Button(miFrame,text="4",width=3,background="grey",command=lambda:numeroPulsado("4")) #Funciones lambda -> Simplificar funciones
btnCuatro.grid(row=3,column=1)
btnCinco=Button(miFrame,text="5",width=3,background="grey",command=lambda:numeroPulsado("5"))
btnCinco.grid(row=3,column=2)
btnSeis=Button(miFrame,text="6",width=3,background="grey",command=lambda:numeroPulsado("6"))
btnSeis.grid(row=3,column=3)
btnMulti=Button(miFrame,text="*",width=3,background="black",fg="green")
btnMulti.grid(row=3,column=4)
#-----------------Fila 3---------------------------
btnUno=Button(miFrame,text="1",width=3,background="grey",command=lambda:numeroPulsado("1"))
btnUno.grid(row=4,column=1)
btnDos=Button(miFrame,text="2",width=3,background="grey",command=lambda:numeroPulsado("2"))
btnDos.grid(row=4,column=2)
btnTres=Button(miFrame,text="3",width=3,background="grey",command=lambda:numeroPulsado("3"))
btnTres.grid(row=4,column=3)
btnRest=Button(miFrame,text="-",width=3,background="black",fg="green")
btnRest.grid(row=4,column=4)
#-----------------Fila 4---------------------------
btnComa=Button(miFrame,text=",",width=3,background="black",fg="white",command=lambda:numeroPulsado(","))
btnComa.grid(row=5,column=1)
btnCero=Button(miFrame,text="0",width=3,background="white",command=lambda:numeroPulsado("0"))
btnCero.grid(row=5,column=2)
btnIgual=Button(miFrame,text="=",width=3,background="black",fg="yellow",command=lambda:el_resultado())
btnIgual.grid(row=5,column=3)
btnSuma=Button(miFrame,text="+",width=3,background="black",fg="green",command=lambda:suma(numeroPantalla.get()))
btnSuma.grid(row=5,column=4)
root.mainloop()
|
60470b2002802975c25a44a2f393a29a091e201c | BenjiKCF/Codewars | /day48.py | 419 | 3.765625 | 4 | def count_positives_sum_negatives(arr):
if arr != [] or sum(arr) != 0:
return [len([i for i in arr if i > 0]), sum(i for i in arr if i < 0)]
else:
return []
print count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]) #[10,-65]
def count_positives_sum_negatives(arr):
return [len([x for x in arr if x > 0])] + [sum(y for y in arr if y < 0)] if arr else []
|
2763ea01a72087e8035e4b335058a24a2531043c | JohnZ9865/practicingagain | /hello.py | 401 | 3.859375 | 4 | def pns(a, b): #prime numer searcher
primeNumbers = []
for i in range(a, b + 1):
isPrimeFlag = True
for loop in range(2, i):
if i % loop == 0:
isPrimeFlag = False
break
if isPrimeFlag == True:
primeNumbers.append(i)
print(primeNumbers)
i0 = int(input('Please enter the first integer: '))
i1 = int(input('Please enter the second integer: '))
pns(0, 12)
|
55ba6836e7c26cd3230a4f40e45d45c4d78b3109 | JpryHyrd/python_2.0 | /Lesson_7/1.py | 1,060 | 4.375 | 4 | """
1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив,
заданный случайными числами на промежутке [-100; 100). Выведите на экран
исходный и отсортированный массивы. Сортировка должна быть реализована в
виде функции. По возможности доработайте алгоритм (сделайте его умнее).
"""
import random
def bubble_sort(orig_list):
n = 1
while n < len(orig_list):
for i in range(len(orig_list)-n):
if orig_list[i] < orig_list[i+1]:
orig_list[i],orig_list[i+1] = orig_list[i+1],orig_list[i]
n += 1
return orig_list
orig_list = [random.randint(-100, 100) for _ in range(20)]
print("Исходный массив: ", end = "")
print(orig_list)
print("Массив после сортировки: ", end = "")
print(bubble_sort(orig_list))
|
9163dae3a5fb21224d2d3c9219714cc879ea6005 | lixiang2017/leetcode | /problems/0055.0_Jump_Game.py | 3,030 | 3.734375 | 4 | '''
DP
from left to right
Runtime: 496 ms, faster than 66.35% of Python3 online submissions for Jump Game.
Memory Usage: 15.4 MB, less than 35.35% of Python3 online submissions for Jump Game.
'''
class Solution:
def canJump(self, nums: List[int]) -> bool:
N = len(nums)
farmost = nums[0]
for i, x in enumerate(nums):
if i > farmost:
break
else:
farmost = max(farmost, i + x)
if farmost >= N - 1:
return True
return False
'''
Runtime: 819 ms, faster than 23.15% of Python3 online submissions for Jump Game.
Memory Usage: 15.4 MB, less than 11.93% of Python3 online submissions for Jump Game.
'''
class Solution:
def canJump(self, nums: List[int]) -> bool:
N = len(nums)
farmost = nums[0]
for i, x in enumerate(nums):
if i > farmost:
return False
else:
farmost = max(farmost, i + x)
if farmost >= N - 1:
return True
'''
Runtime: 460 ms, faster than 40.29% of Python online submissions for Jump Game.
Memory Usage: 14.6 MB, less than 25.06% of Python online submissions for Jump Game.
'''
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return reduce(lambda m, (i, x): max(m, i + x) * (i <= m), enumerate(nums, 1), 1) > 0
'''
Using parentheses to unpack the arguments in a lambda is not allowed in Python3. See PEP 3113 for the reason why.
https://stackoverflow.com/questions/15712210/python-3-2-lambda-syntax-error
Runtime: 544 ms, faster than 43.94% of Python3 online submissions for Jump Game.
Memory Usage: 15.4 MB, less than 35.35% of Python3 online submissions for Jump Game.
'''
class Solution:
def canJump(self, nums: List[int]) -> bool:
return reduce(lambda m, ix: max(m, ix[0] + ix[1]) * (ix[0] <= m), enumerate(nums, 1), 1) > 0
'''
go backwards
假设可以到达末尾,再从末尾反推。
Runtime: 476 ms, faster than 80.55% of Python3 online submissions for Jump Game.
Memory Usage: 15.4 MB, less than 11.93% of Python3 online submissions for Jump Game.
'''
class Solution:
def canJump(self, nums: List[int]) -> bool:
size = len(nums)
lastPos = size - 1
for i in range(size - 2, -1, -1):
if i + nums[i] >= lastPos:
lastPos = i
return not lastPos
'''
Runtime: 531 ms, faster than 81.08% of Python3 online submissions for Jump Game.
Memory Usage: 15.2 MB, less than 82.53% of Python3 online submissions for Jump Game.
'''
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
reachable = 0
i = 0
while i < n:
if i > reachable:
break
reachable = max(reachable, i + nums[i])
if reachable >= n - 1:
return True
i += 1
return False
|
d5a6ebe31b356e7aa1f111c85de2f0ebf5de8228 | AngelPedroza/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 229 | 3.890625 | 4 | #!/usr/bin/python3.4
def uppercase(str):
for i in range(len(str)):
y = str[i]
if ord(str[i]) > 96 and ord(str[i]) < 123:
y = chr(ord(str[i]) - 32)
print("{}".format(y), end='')
print()
|
a140b001f8bbc078a159c240c45f8ea33b55e151 | zhg5482/test | /python/20170814/list_test1.py | 529 | 4.0625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
classmates = ['Michael','Bob','Tracy']
#打印classmates
print('classmates = ',classmates)
#打印classmates 长度
print('len = ',len(classmates))
#list尾部追加元素
classmates.append('Adam')
print('classmates = ',classmates)
#list指定位置插入元素
classmates.insert(2,'Jack')
print('classmates = ',classmates)
#list删除末尾元素
classmates.pop()
print('classmates = ',classmates)
#list删除指定位置元素
classmates.pop(1)
print('classmates = ',classmates)
|
8e1efc4326ec6674906a8f00b13523771ab61e02 | benzitohhh/cs212-style | /week5/pig14_moreAnalysis.py | 6,416 | 3.890625 | 4 |
from functools import update_wrapper
def decorator(d):
"Make function d a decorator: d wraps a function fn."
def _d(fn):
return update_wrapper(d(fn), fn)
update_wrapper(_d, d)
return _d
@decorator
def memo(f):
"""Decorator that caches the return value for each call to f(args).
Then when called again with same args, we can just look it up."""
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
# some element of args can't be a dict key
return f(args)
return _f
other = {1:0, 0:1}
def roll(state, d):
"""Apply the roll action to a state (and a die roll d) to yield a new state:
If d is 1, get 1 point (losing any accumulated 'pending' points),
and it is the other player's turn. If d > 1, add d to 'pending' points."""
(p, me, you, pending) = state
if d == 1:
return (other[p], you, me+1, 0) # pig out; other player's turn
else:
return (p, me, you, pending+d) # accumulate die roll in pending
def hold(state):
"""Apply the hold action to a state to yield a new state:
Reap the 'pending' points and it becomes the other player's turn."""
(p, me, you, pending) = state
return (other[p], you, me+pending, 0)
def pig_actions(state):
"The legal actions from a state."
_, _, _, pending = state
return ['roll', 'hold'] if pending else ['roll']
goal = 40
##############################
# Utility fuctions
##############################
@memo
def Pwin(state):
"""The utility of a state; here just the probability that an optimal player
whose turn it is to move can win from the current state."""
# Assumes opponent also plays with optimal strategy.
(p, me, you, pending) = state
if me + pending >= goal:
return 1
elif you >= goal:
return 0
else:
return max(Q_pig(state, action, Pwin)
for action in pig_actions(state))
@memo
def win_diff(state):
"The utility of a state: here the winning differential (pos or neg)."
(p, me, you, pending) = state
if me + pending >= goal or you >= goal:
return (me + pending - you)
else:
return max(Q_pig(state, action, win_diff)
for action in pig_actions(state))
###############################################
# Quality function - this elegantly implements "minimax"
###############################################
def Q_pig(state, action, Pwin):
"The expected value of choosing action in state."
if action == 'hold':
# i.e. 1 - opponents chances of winning
return 1 - Pwin(hold(state))
if action == 'roll':
# i.e. if 1 it's a pigout, so return 1 - opponents chances of winning
# i.e. otherwise just the average of all 6 die results
return (1 - Pwin(roll(state, 1))
+ sum(Pwin(roll(state, d)) for d in (2,3,4,5,6))) / 6.
raise ValueError
###############################################
# Best action function
###############################################
def best_action(state, actions, Q, U):
"Return the optimal action for a state, given U."
def EU(action): return Q(state, action, U)
return max(actions(state), key=EU)
###############################################
# Strategies (these just call best_action on a particular utility)
###############################################
def max_diffs(state):
"""A strategy that maximizes the expected difference between my final score
and my opponent's."""
return best_action(state, pig_actions, Q_pig, win_diff)
def max_wins(state):
"The optimal pig strategy chooses an action with the highest win probability."
return best_action(state, pig_actions, Q_pig, Pwin)
from collections import defaultdict
import pprint
goal = 40
states = [(0, me, you, pending)
for me in range(41) for you in range(41) for pending in range(41)
if me + pending <= goal]
# print len(states)
r = defaultdict(int)
for s in states:
r[max_wins(s), max_diffs(s)] += 1
pprint.pprint(dict(r))
print
# should print something like:
# {('hold', 'hold'): 1204,
# ('hold', 'roll'): 381,
# ('roll', 'hold'): 3975,
# ('roll', 'roll'): 29741}
# i.e. this shows most of the time, these two strategies have similar results
# But suprisingly, max_diffs is LESS aggressive than max_wins
# But why? Could it be that max_diffs is more willing to lose?
# (i.e. sacrifice winning for a higher differential..)
# To find out... let's analyse the differing actions...
# grouping by pending points per (roll, hold) or (hold, roll)
# w d w d
def story():
r = defaultdict(lambda: [0, 0])
for s in states:
w, d = max_wins(s), max_diffs(s)
if w != d:
_, _, _, pending = s
i = 0 if (w == 'roll') else 1
r[pending][i] += 1
for (delta, (wrolls, drolls)) in sorted(r.items()):
print '%4d: %3d %3d' % (delta, wrolls, drolls)
story()
# should print something like this:
# 2: 0 40
# 3: 0 40
# 4: 0 40
# 5: 0 40
# 6: 0 40
# 7: 0 40
# 8: 0 40
# 9: 0 40
# 10: 0 28
# 11: 0 19
# 12: 0 12
# 13: 0 2
# 16: 11 0
# 17: 68 0
# 18: 128 0
# 19: 201 0
# 20: 287 0
# 21: 327 0
# 22: 334 0
# 23: 322 0
# 24: 307 0
# 25: 290 0
# 26: 281 0
# 27: 253 0
# 28: 243 0
# 29: 213 0
# 30: 187 0
# 31: 149 0
# 32: 125 0
# 33: 95 0
# 34: 66 0
# 35: 31 0
# 36: 22 0
# 37: 16 0
# 38: 11 0
# 39: 7 0
# 40: 1 0
# There's a story here!
# Most of the times, the actions agree.
# But when they differ for small pending values,
# it is max_diff that chooses to roll.
# Conversely, for higher pending values,
# it is max_wins that chooses to roll.
# Notice there is a crossover point between pending 13 and 16,
# where neither max_diffs or max_wins are willing to roll, and neither is
# For example, suppose pending points are 24,
# but the opponent is about to win.
# Max_wins will be willing to roll, just to stop the opponent
# from winning. But max_diffs will say hell no, I'm going to keep
# my 24 points (and be willing to lose)
# Here max_wins is |
932dccce30e2a3bbd66ae4ffb3424479ab13cceb | codork/competitive-coding | /4_NumberComplement.py | 852 | 3.578125 | 4 | '''
@author: codork
@date: 06-05-2020
@problem: Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
'''
class Solution:
def complement(self, n):
if n == 0:
return 1
elif n == 1:
return 0
def findComplement(self, num: int) -> int:
if num == 0:
return 1
elif num == 1:
return 0
binstack = []
rem = num
while (num != 0 and num != 1):
rem = num % 2
num = num // 2
binstack.append(rem)
binstack.append(num)
comp = list(map(self.complement, binstack))
result = 0
for i in range(len(comp)):
result = result + comp[i] * pow(2, i)
return result
|
5c0cc7e487986877dbfb63b29f0c0b644a07eff4 | FarmanAhmadov/Sudoku_game | /Sudoku game.py | 5,224 | 3.71875 | 4 | from tkinter import *
import time
import _thread
# THEME
line_color = 'gray'
text_color = 'blue'
background_color = 'white'
g = 9 # grid variable
active = (None, None)
board = [[0 for i in range(9)] for _ in range(9)]
#####################################################################################################
def solve(board):
draw_game(board)
find = find_empty()
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if is_valid(i, row, col):
board[row][col] = i
if solve(board):
return True
board[row][col] = 0
return False
def mouse_handler(event):
global active
row, col = get_grid(event)
w = float(canvas['height']) / g
if (row, col) != active:
canvas.delete('active')
x = col * w
y = row * w
canvas.create_rectangle(x, y, x+w, y+w, outline='green', fill='', tags='active', width=5)
active = (row, col)
else:
active = (None, None)
canvas.delete('active')
def key_handler(event):
try:
char = int(event.char)
if is_valid(char, *active):
s = float(canvas['width']) / g
row, col = active
if board[row][col] != 0: canvas.delete('last')
canvas.dtag('number', 'last')
canvas.create_text(col*s+s/2, row*s+s/2, text=char, font=('Arial', 20), fill=text_color, tags=('number', 'last'))
board[row][col] = char
except: pass
def move(x, y):
global active
row, col = active
w = float(canvas['height']) / g
col += x
row += y
if col == 9: col = 0
elif col == -1: col = 8
if row == 9: row = 0
elif row == -1: row = 8
canvas.delete('active')
x = col * w
y = row * w
canvas.create_rectangle(x, y, x + w, y + w, outline='green', fill='', tags='active', width=5)
active = (row, col)
def print_board(event):
for i in range(9):
for j in range(9):
print(f"{board[i][j]}", end=(' | ' if (j!=8 and (j+1)%3==0) else ' '))
print('\n---------------------' if i!=8 and (i+1)%3==0 else '')
print("\n\n")
def create_new():
global board
board = [[0 for i in range(9)] for _ in range(9)]
canvas.delete('number')
canvas.bind("<Button-1>", mouse_handler)
pen.bind("<Key>", key_handler)
pen.bind("<Left>", lambda e: move(-1, 0))
pen.bind("<Right>", lambda e: move(1, 0))
pen.bind("<Up>", lambda e: move(0, -1))
pen.bind("<Down>", lambda e: move(0, 1))
pen.bind("<space>", print_board)
def find_empty():
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return i, j
def draw_game(board):
canvas.delete('number')
for i in range(9):
for j in range(9):
write_number(board[i][j], i, j)
# time.sleep(0.1)
def draw_lines():
# horizontal lines
for i in range(1, g):
canvas.create_line(0, i*float(canvas['height'])/g,
float(canvas['width']), i*float(canvas['height'])/g,
fill=line_color, width=(1 if i%3!=0 else 3))
# vertical lines
for i in range(1, g):
canvas.create_line(i*float(canvas['width'])/g, 0,
i*float(canvas['width'])/g, float(canvas['height']),
fill=line_color, width=(1 if i%3!=0 else 3))
def write_number(n, row, col):
s = float(canvas['width'])/g
if board[row][col] != 0:
canvas.create_text(col*s+s/2, row*s+s/2, text=str(n), font=('Arial', 20), fill=text_color, tags='number')
def new_stage(n, row, col):
b = board.copy()
b[row][col] = n
return b
def get_grid(event):
col = int(event.x / (float(canvas['width']) / g))
row = int(event.y / (float(canvas['height']) / g))
return row, col
def check_in_horizontal(n, row, col):
# from left to right
for i in range(len(board[row])):
if i == col: continue
if board[row][i] == n:
return True
return False
def check_in_vertical(n, row, col):
# from top to bottom
for i in range(len(board)):
if i == row: continue
if board[i][col] == n:
return True
return False
def check_in_box(n, row, col):
# in 3x3 boxes
r = row // 3 * 3
c = col // 3 * 3
for i in range(3):
for j in range(3):
if r+i == row and c+j == col: continue
if board[r+i][c+j] == n:
return True
return False
def is_valid(n, row, col):
return not check_in_vertical(n, row, col) and not check_in_horizontal(n, row, col) and not check_in_box(n, row, col)
#####################################################################################################
pen = Tk()
pen.title("Sudoku")
####### MENU #########
menu = Menu(pen)
menu.add_command(label='Solve', command=lambda: _thread.start_new_thread(solve, (board,)))
menu.add_command(label='Create game', command=create_new)
pen.config(menu=menu)
canvas = Canvas(pen, width=400, height=400, bg=background_color)
canvas.pack()
draw_lines()
pen.minsize(400, 400)
pen.resizable(False, False)
pen.mainloop() |
5899bfb17f5eee7b395b124b28f3557b482bb355 | jackneer/my-leetcode | /no28_str_str.py | 448 | 3.75 | 4 | def str_str(haystack, needle):
if needle is None or len(needle) == 0:
return 0
found_index = -1
for i in range(0, len(haystack) - len(needle) + 1):
if haystack[i: i + len(needle)] == needle:
found_index = i
return found_index
def main():
print(str_str(haystack = 'hello', needle = 'll'))
print(str_str(haystack = 'aaaaa', needle = 'bba'))
pass
if __name__ == '__main__':
main() |
d2cae9d38d253e67ffb4bb8cc451c3ac92e53a89 | WilliamJCole/IS211_Assignment6 | /tests_next.py | 9,430 | 3.796875 | 4 | import conversions_refactored as con
#TEMPERATURE CONVERSION TESTS--------------------------------------------------------------------------------------
#TEST FOR convert Celsius To Kelvin
print "TEST FOR convert Celsius To Kelvin"
tests = [(500.00, 773.15), (490.00, 763.15), (450.00, 723.15), (410.00, 683.15), (380.00, 653.15)]
for i, o in tests:
c = con.convert("Celsius", "Kelvin", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert Celsius To Fahrenheit"
#TEST FOR convert Celsius To Fahrenheit
tests = [(500.00, 932.00), (490.00, 914.00), (450.00, 842.00), (410.00, 770.00), (380.00, 716.00)]
for i, o in tests:
c = con.convert("Celsius", "Fahrenheit", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert Fahrenheit To Celsius"
#TEST FOR convert Fahrenheit To Celsius
tests = [(500.00, 932.00), (490.00, 914.00), (450.00, 842.00), (410.00, 770.00), (380.00, 716.00)]
for o, i in tests:
c = con.convert("Fahrenheit", "Celsius", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR conver tFahrenheit To Kelvin"
#TEST FOR convert Fahrenheit To Kelvin
tests = [(932.00, 773.15), (914.00, 763.15), (842.00, 723.15), (770.00, 683.15), (716.00, 653.15)]
for i, o in tests:
c = con.convert("Fahrenheit", "Kelvin", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert Kelvin To Fahrenheit"
#TEST FOR convert Kelvin To Fahrenheit
tests = [(932.00, 773.15), (914.00, 763.15), (842.00, 723.15), (770.00, 683.15), (716.00, 653.15)]
for o, i in tests:
c = con.convert("Kelvin", "Fahrenheit", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert Kelvin To Celsius"
#TEST FOR convert Kelvin To Celsius
tests = [(500.00, 773.15), (490.00, 763.15), (450.00, 723.15), (410.00, 683.15), (380.00, 653.15)]
for o, i in tests:
c = con.convert("Kelvin", "Celsius", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
#END OF TEMPERATURE TESTS---------------------------------------------------------------------------------------
print "-------------------------------------------------------------------------------\n"
#DISTANCE CONVERSION TESTS--------------------------------------------------------------------------------------
print "TEST FOR convert meters to miles"
#TEST FOR convert meters to miles
tests = [(0.48, 773.15), (0.47, 763.15), (0.45, 723.15), (0.42, 683.15), (0.41, 653.15)]
for o, i in tests:
c = con.convert("meters", "miles", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert meters to Yards"
#TEST FOR convert meters to Yards
tests = [(845.52, 773.15), (834.58, 763.15), (790.84, 723.15), (747.09, 683.15), (714.28, 653.15)]
for o, i in tests:
c = con.convert("meters", "Yards", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert miles to meters"
#TEST FOR convert miles to meters
tests = [(0.48, 772.49), (0.47, 756.39), (0.45, 724.21), (0.42, 675.93), (0.41, 659.83)]
for i, o in tests:
c = con.convert("miles", "meters", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert miles to Yards"
#TEST FOR convert miles to Yards
tests = [(0.48, 844.79), (0.47, 827.19), (0.45, 791.99), (0.42, 739.19), (0.41, 721.59)]
for i, o in tests:
c = con.convert("miles", "Yards", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert Yards to meters"
#TEST FOR convert Yards to meters
tests = [(772.49, 844.79), (756.39, 827.19), (724.20, 791.99), (675.92, 739.19), (659.83, 721.59)]
for o, i in tests:
c = con.convert("Yards", "meters", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
print "TEST FOR convert Yards to miles"
#TEST FOR convert Yards to miles
tests = [(0.48, 844.79), (0.47, 827.19), (0.45, 791.99), (0.42, 739.19), (0.41, 721.59)]
for o, i in tests:
c = con.convert("Yards", "miles", i)
if o==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(i, o, c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(i, o, c)
print ""
#END DISTANCE CONVERSION TEST---------------------------------------------------------------
print "-------------------------------------------------------------------------------\n"
#SAME UNIT TYPE CONVERSION------------------------------------------------------------
tests = [10.00, 10.00]
print "celsius to celsius"
c = con.convert("celsius", "celsius", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
print "fahrenheit to fahrenheit"
c = con.convert("fahrenheit", "fahrenheit", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
print "kelvin to kelvin"
c = con.convert("kelvin", "kelvin", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
print "meters to meters"
c = con.convert("meters", "meters", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
print "miles to miles"
c = con.convert("miles", "miles", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
print "yards to yards"
c = con.convert("yards", "yards", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
#END SAME UNIT TYPE CONVERSION------------------------------------------------------------
print "-------------------------------------------------------------------------------\n"
#INCOMPATIBLE UNIT TYPE CONVERSION-------------------------------------------------------
tests = [10.00, 10.00]
print "celsius to yards"
c = con.convert("celsius", "yards", tests[0])
if tests[1]==c:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST PASS"%(tests[0], tests[1], c)
else:
print "Input given: %.2f | Expected output: %.2f | Resultant output: %.2f | TEST FAIL"%(tests[0], tests[1], c)
print ""
|
2025a9901e1173e89b760b5624071a9764e1006c | EruDev/Python-Practice | /菜鸟教程Python3实例/02.py | 228 | 3.65625 | 4 | # 以下实例为通过用户输入两个数字,并计算两个数字之和:
def add_num():
n1 = int(input('请输入第一个数字:'))
n2 = int(input('请输入第二个数字:'))
return n1 + n2
print(add_num())
|
b1125181aa2054f0ba2c33cd82377b5875fd274e | echoshihab/PyGameSims | /quiz_project/quiz_brain.py | 1,001 | 3.859375 | 4 | # ask the questions
# check if answer is correct
# check if we're at end of quiz
class QuizBrain:
def __init__(self, questions_list):
self.question_number = 0
self.score = 0
self.questions_list = questions_list
def still_has_questions(self):
return self.question_number <= len(self.questions_list)-1
def next_question(self):
question = self.questions_list[self.question_number]
self.question_number += 1
user_input = input(f"Q.{self.question_number}: {question.text}. (True/False)? ").lower()
self.check_answer(user_input, question.answer.lower())
return user_input
def check_answer(self, user_answer, actual_answer):
if user_answer == actual_answer:
self.score += 1
print("Correct!")
else:
print("Incorrect")
print(f"Correct Answer is {actual_answer}")
print(f"Your current score is {self.score}/{self.question_number}")
print()
|
9b522d5e1728fcd9a867f8e609d7f3f3bec7519c | lucasalvesso/ad1_2021_1 | /q4.py | 1,387 | 3.609375 | 4 | def calcCenter(values):
med = [0, 0]
for lin in range(len(values)):
med[0] += values[lin][0]
med[1] += values[lin][1]
return [med[0]/len(values), med[1]/len(values)]
def calcDist(firstValue, secondValue):
dist = (((secondValue[0] - firstValue[0]) ** 2) + ((secondValue[1] - firstValue[1]) ** 2)) ** (1/2)
return dist
def getDist(center, values):
closer = [0, center[0], center[1]]
further = [0, center[0], center[1]]
for lin in range(len(values)):
calc = calcDist(values[lin], center)
if calc >= further[0]:
further = [calc, values[lin][0], values[lin][1]]
else:
closer = [calc, values[lin][0], values[lin][1]]
return (closer, further)
values = []
while True:
try:
entry = input('Digite os valores: ').split(' ')
if len(entry) == 0:
continue
x = int(entry[0])
y = int(entry[1])
values.append([x,y])
except:
break
if len(values) == 0:
print('Nenhum ponto lido. Portanto, não há centróide!!!')
else:
center = calcCenter(values)
dist = getDist(center, values)
print('Centróide: ({}, {})'.format(center[0], center[1]))
print('Ponto mais próximo do centróide : ({}, {})'.format(dist[0][1], dist[0][2]))
print('Ponto mais distante do centróide : ({}, {})'.format(dist[1][1], dist[1][2])) |
313f7aac2671c6840b19a745fb851f0ca8582455 | GinnyGaga/My-Practice-backup | /py-pra/def_func.py | 375 | 3.78125 | 4 | import math
def quadratic(a,b,c):
L=[a,b,c]
for m in L:
if not isinstance(m,(int,float)):
raise TypeError('bad operandtype')
n=b*b-4*a*c
if a==0:
return Error
elif n>0:
x1=(-b+math.sqrt(n))/(2*a)
x2=(-b-math.sqrt(n))/(2*a)
return x1,x2
elif n==0 :
x=-b/(2*a)
return x
else:
return 'No answan'
print (quadratic(2, 3, 1))
print (quadratic(1, 3, -4))
|
bca28e1c709f82e5d540da25a7f334297780870a | 0ushany/learning | /python/python-crash-course/code/6_dictionary/practice/4_vocabulary2.py | 149 | 3.71875 | 4 | # 词汇表2
vacabularys = {'osy':22, 'oshany':14, 'apple':19, 'helen':20}
for key, value in vacabularys.items():
print(key + ":" + str(value))
|
117a7d876cae99062877af17fa4c5de28f7aef62 | hubbm-bbm101/lab5-exercise-solution-b2200356076 | /exercise2.py | 369 | 4.15625 | 4 | user_input = input("Please enter e-mail:")
def valid_or_not(x):
email_check = x
y = False
z = False
for i in email_check:
if i=="@":
y = True
elif i==".":
z=True
return y and z
if valid_or_not(user_input):
print("This is a valid e-mail.")
else:
print("This is not a valid e-mail.")
|
c8da19c16da19455f510a17e8504946a23447b25 | ruoyzhang/AI_public_perception_survey_data_analysis | /WE/clean_functions.py | 1,041 | 3.640625 | 4 | from answer_dict import answer_dicts
def recode_answers(dataset, q_num, lang, multi):
"""
Function to recode single choice questions from the questionaire
dataset: the dataset containing the responses, pandas dataframe
q_num: the question number to convert
lang: which language is the questionaire in, possible values: 'en', 'fr' and 'de'
multi: the type of question (whether single choice or multiple choice), boolean
"""
# determining which conversion dict to use
dict_to_use = answer_dicts[lang][q_num]
# reversing the dict
dict_to_use = {v:k for k,v in dict_to_use.items()}
# split answers if necessary
if multi:
# converting str to list
col = [ans.split(';') if isinstance(ans, str) else ans for ans in dataset[q_num]]
# recode
recoded = [[dict_to_use[an] if an in dict_to_use.keys() else an for an in ans] if isinstance(ans, list) else ans for ans in col]
else:
col = dataset[q_num]
# recode
recoded = [dict_to_use[ans] if ans in dict_to_use.keys() else ans for ans in dataset[q_num]]
return(recoded) |
9df7c5037360a46d4dfd66cff9ca95f2765812dd | RussellSB/mathematical-algorithms | /task8.py | 1,420 | 3.984375 | 4 | #Name: Russell Sammut-Bonnici
#ID: 0426299(M)
#Task: 8
import math #for pi
#recursive function for finding the factorial of a number x
def _factorial(x):
#base case, factorial of 0 is 1
if(x == 0):
return 1.0
# calls recursively until base case
return x * _factorial(x-1)
#function for calculating sin(x) through sum of first t terms
def sin(x,t):
sum=0.0 #initialised sum
#if x is out of the range from -2PI to 2PI, x modulo 2PI
if(x< -(2 * math.pi) or x>(2 * math.pi)):
x = x%(2*math.pi)
#for loop for evaluating sin(x) using MacLaurin's Theorem
for n in range(0,t+1):
numerator = ((-1)**n) * (x**((2*n)+1))
denominator = _factorial((2*n)+1)
sum += numerator/denominator
return sum #returns answer
#function for calculating cos(x) through sum of first t terms
def cos(x,t):
sum=0.0 #initialised sum
# if x is out of the range from -2PI to 2PI, x modulo 2PI
if (x < -(2 * math.pi) or x > (2 * math.pi)):
x = x % (2 * math.pi)
# for loop for evaluating cosx using MacLaurin's Theorem
for n in range(0,t+1):
numerator = ((-1)**n)*(x**(2*n))
denominator = _factorial(2*n)
sum += numerator/denominator
return sum #returns answer
a=50.0 #for x in radians
t=90 #for t trials
print("sin(%.4f) with %d trials = %.9f"%(a,t,sin(a,t)))
print("cos(%.4f) with %d trials = %.9f"%(a,t,cos(a,t)))
|
e3d6f28d5eab72b4c4c8c189f8adc8708fa3c6c2 | atsuhisa-i/Python_study1 | /if3.py | 77 | 3.515625 | 4 | number = input('Number:')
if number == '123456':
print('1st Prize:Money') |
0847f8ef5d73f6dc44088af0a915658aa04d4230 | sairamprogramming/python_book1 | /chapter4/programming_exercises/exercise2.py | 337 | 3.75 | 4 | # Calories Burned
# Named constant for calories burned per minute.
CALORIES_BURNED_PER_MINUTE = 4.2
# Calculating the total caloires burned
for minutes in range(10,31,5):
total_calories_burned = CALORIES_BURNED_PER_MINUTE * minutes
print("Calories burned after", minutes, "of running is", format(total_calories_burned, '.2f')) |
85331bb99489ad7edbd3b8670d320d32ea7d4ab5 | saisugeeta/intellify | /ML ALGO/demo1.py | 1,652 | 3.5625 | 4 | import pandas as pd
def missing_values(df):
mis_val=df.isnull().sum()
mis_val_percent=100*mis_val/len(df)
mis_val_table = pd.concat([mis_val, mis_val_percent], axis=1)
# Rename the columns
mis_val_table_ren_columns = mis_val_table.rename(
columns = {0 : 'Missing Values', 1 : '% of Total Values'})
# Sort the table by percentage of missing descending
mis_val_table_ren_columns = mis_val_table_ren_columns[
mis_val_table_ren_columns.iloc[:,1] != 0].sort_values('% of Total Values', ascending=False).round(1)
# Print some summary information
print ("Your selected dataframe has " + str(df.shape[1]) + " columns.\n""There are " + str(mis_val_table_ren_columns.shape[0]) +
" columns that have missing values.")
print(mis_val_table_ren_columns)
mydataset=pd.read_csv("city_hour.csv",parse_dates=['Datetime'])
#print(mydataset)
print(mydataset.head())
mydataset.interpolate(limit_direction="both",inplace=True)
print("After missing Values")
print(mydataset.tail())
#splitting the data set into dependent and independent
#handling missing values
missing_values(mydataset)
X=mydataset.iloc[:,:-2]
Y=mydataset.iloc[:,15:17]
print(X.tail())
print(Y.head())
cities = mydataset['City'].value_counts()
print(cities.index)
#mydataset['Datetime'] = pd.to_datetime(mydataset['Datetime'])
#print(mydataset.head())
#combining BTX
mydataset['BTX']=mydataset['Benzene']+mydataset['Toluene']+mydataset['Xylene']
print(mydataset.head())
mydataset.drop(['Benzene','Toluene','Xylene'],axis=1,inplace=True)
print(mydataset.head(1))
print(type(mydataset['Datetime'])) |
5acc6ed0e132fb7d280d78d11bab417da9577cb9 | reiniertromp/MITCourse | /oddTuple.py | 165 | 3.765625 | 4 | x = ('I', 'am', 'a', 'test', 'tuple');
def oddTuples(atuple):
return atuple[0::2]
print(type(('I', 'am', 'a', 'test', 'tuple'),))
print(x)
print(oddTuples(x))
|
578135050c3e197d231fe76f4e59c075088c7bf1 | NewtonFractal/Project-Euler-1 | /#2.py | 234 | 3.5625 | 4 | import time
import math
start = time.time()
a = math.floor(1000/3)
b = a * 3
c = math.floor(1000/5)
d = c * 5
e = math.floor(1000/15)
f = e * 15
print((((b+3)*a)/2)+(((d)*(c-1))/2)-(((f+15)*e)/2))
end = time.time()
print(end - start)
|
d19ebfbeca85cf41dbd0901602bac5045e855052 | neternefer/codewars | /python/projectPartners.py | 783 | 4.15625 | 4 | #Mrs. Frizzle is beginning to plan lessons for her science class next semester,
#and wants to encourage friendship amongst her students.
#To accomplish her goal, Mrs. Frizzle will ensure each student
#has a chance to partner with every other student in the class
#in a series of science projects.
#Mrs. Frizzle does not know who will be in her class next semester,
#but she does know she will have n students total in her class.
#Create the function projectPartners with the parameter n
#representing the number of students in Mrs. Frizzle's class.
#The function should return the total number of unique pairs
#she can make with n students.
#Dont' use arrays.Input greater than or equal to 2.
def projectPartners(n):
pairs = 0
for p in range(1, n):
pairs += (n - p)
return pairs
|
665709790fb3c8e3f787d45fbb942025c0e92054 | zdgeier/programming-problems | /find-peak2/find-peak.py | 374 | 3.625 | 4 | def findpeak(arr):
first = 0
last = len(arr)
while True:
mid = (first + last) // 2
if mid + 1 < len(arr) and arr[mid] < arr[mid + 1]:
first = mid + 1
elif arr[mid] < arr[mid - 1]:
last = mid - 1
else:
return mid
while True:
arr = list(map(int, input().split()))
print(findpeak(arr))
|
0342017f04a4994d0861be2d145fb00e1c99ebcc | BaoAdrian/interview-prep | /coding-problems/leetcode/arrays/word_search_i.py | 1,627 | 3.828125 | 4 | """
Word Search I
https://leetcode.com/problems/word-search/
Given a 2D board and a word, find if the word
exists in the grid.
The word can be constructed from letters of
sequentially adjacent cell, where "adjacent"
cells are those horizontally or vertically neighboring.
The same letter cell may not be used more than once.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
"""
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
"""
Time: 340ms (79.23%)
Mem: 13.7MB (100%)
"""
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == word[0] and self.dfs(board, i, j, 0, word):
return True
return False
def dfs(self, board, i, j, count, word):
# Found it
if count == len(word):
return True
# Bounds
if i < 0 or i >= len(board) or j < 0 or j >= len(board[i]) or board[i][j] != word[count]:
return False
# Store temp and replace with empty string for dfs
temp = board[i][j]
board[i][j] = " "
# Traverse the 4 corners
count += 1
found = self.dfs(board, i + 1, j, count, word) or self.dfs(board, i - 1, j, count, word) or self.dfs(board, i, j + 1, count, word) or self.dfs(board, i, j - 1, count, word)
board[i][j] = temp # restore back
return found
|
63370dc946ae4b0a0dcfd240c900d6c6442c1d5b | python-naresh/python | /8-2-function.py | 227 | 3.71875 | 4 | def tr(a,b=20,c=30):
# in function u can't give like (a=10,b=19,c) it will give u error
# u can leave left side values like a and u can give right side value like b,c
d=a+b+c
print(d)
tr(3)
tr(3,100)
tr(10,20,30) |
62be2010cb94106ca0bf9145dec9950a443dafae | dadafros/Harvard-CS50-Course | /pset6/mario/more/mario.py | 308 | 3.90625 | 4 | from cs50 import get_int
h = 0
while (h < 1 or h > 8):
h = get_int("Height: ")
for i in range(h):
for j in range(h - i - 1):
print(" ", end="")
for k in range(i + 1):
print("#", end="")
print(" ", end="")
for k in range(i + 1):
print("#", end="")
print()
|
603b917f9acecb3e426b3a979674d070b8fb92c7 | tkinoti/python-basics-class | /structures.py | 1,242 | 4.46875 | 4 | #structures - variables that hold multiple variables eg list, tuple and dictionary
#list - has square brackets []
person_l =["John", "Doe", 30, 65.54, "Mombasa", True]
print(person_l[0])
print(person_l[3])
print(person_l[1:5])
print(person_l[0:5])
print(person_l[2:4])
print(person_l[-4:-2])
person_l.append("employed")
person_l.remove(65.54)
person_l.pop(0)
print(person_l)
#tuple - has normal brackets () is immutable hence cannot change its contents. uses smaller space (days, months...)
person_t =("John", "Doe", 30, 65.54, "Mombasa", True)
print(person_t[0])
print(person_t[3])
print(person_t[1:5])
print(person_t[0:5])
print(person_t[2:4])
print(person_t[-4:-2])
# person_t[2]=31 , testing tuple immutability
# print(person_t)
#dictionaries - holds variables in key:value pairs uses curly braces
person_d = {"firstname" : "John", "surname" : "Doe", "weight": 65.57, "location": "mombasa", "activeuser": True}
print(person_d)
print(person_d["surname"])
print(person_d["surname"],person_d["location"])
#assignment
tasklist=[23,"jane",["lesson 23",560,{"currency": "kes"}],987,(76,"john")]
print(type(tasklist))
print(tasklist[2][2]["currency"])
print(tasklist[2][1])
print(len(tasklist))
print(tasklist)
|
76e0cfc6e03c20b9de1fc27e969da044776c92ae | mohasinac/Learn-LeetCode-Interview | /Arrays/Move Zeroes.py | 798 | 3.984375 | 4 | """
Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
lastNonZeroFoundAt = 0
cur = 0
while (cur < len(nums)):
if (nums[cur] != 0):
temp = nums [lastNonZeroFoundAt]
nums [lastNonZeroFoundAt] = nums[cur]
nums[cur] = temp
lastNonZeroFoundAt += 1
cur +=1 |
bf01f19aee74a48dce8f090f5abde253e3718727 | diego-go/taller_python_PROTECO | /1er semana/estacionar.py | 296 | 3.8125 | 4 | entrada=int(input("Cuantas horas estuviste estacionado?: "))
total=entrada*8
print("Debes de pagar un total de:",total,"pesos")
monedas=[1,2,5,10]
valorMoneda=int(input("\nIngresa las monedas para pagar: "))
if valorMoneda in monedas:
print("Continua")
pago=valorMoneda+total
elif:
pago=total |
4749cc8b750915657663f61d524874507738a3d3 | daftstar/learn_python | /03_Google_Python/foobar_challenges/01_prison_labor_dodgers.py | 3,809 | 3.59375 | 4 |
# Python Constraints
# ======
# Your code will run inside a Python 2.7.6 sandbox.
# Standard libraries are supported except for:
# bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal,
# termios, thread, time, unicodedata, zipimport, zlib.
# ########################################
# Prison Labor Dodgers
# ########################################
# Commander Lambda is all about efficiency,
# including using her bunny prisoners for manual labor.
# But no one's been properly monitoring the labor shifts
# for a while, and they've gotten quite mixed up.
# You've been given the task of fixing them, but after you wrote
# up new shifts, you realized that some prisoners had been
# transferred to a different block and aren't available for their
# assigned shifts.
# And manually sorting through each shift list to compare against
# prisoner block lists will take forever -
# remember, Commander Lambda loves efficiency!
# Given two almost identical lists of prisoner IDs x and y
# where one of the lists contains an additional ID,
# write a function answer(x, y) that compares the lists and
# returns the additional ID.
# For example, given the lists
# x = [13, 5, 6, 2, 5]
# y = [5, 2, 5, 13]
# the function answer(x, y) would return 6 because
# the list x contains the integer 6 and the list y doesn't.
# Given the lists
# x = [14, 27, 1, 4, 2, 50, 3, 1]
# y = [2, 4, -4, 3, 1, 1, 14, 27, 50],
# the function answer(x, y) would return -4 because the list y
# contains the integer -4 and the list x doesn't.
# In each test case, the lists x and y will always contain n non-unique
# integers where n is at least 1 but never more than 99,
# and one of the lists will contain an additional unique integer
# which should be returned by the function.
# The same n non-unique integers will be present on both lists,
# but they might appear in a different order, like in the examples
# above. Commander Lambda likes to keep her numbers short,
# so every prisoner ID will be between -1000 and 1000.
# ##################################################
# OPTIMIZED WAY - PROOF OF CONCEPT
# Runs in 40 steps
# http://www.pythontutor.com/live.html#mode=edit
# ##################################################
x = [14, 27, 1, 4, 2, 50, 3, 1]
y = [2, 4, -4, 3, 1, 1, 14, 27, 50]
def answer(x, y):
""" compares values of x against y
and vice versa to find the unique value """
# this solution only works for the last unique value found
# use list comprehension to store multiple unique values
# create a single list to look for unique values
z = (x + y)
# assumes that "unique" = 1 instance of a value
for i in z:
if z.count(i) % 2 != 0:
new_value = i
return (new_value)
print (answer(x, y))
# ##################################################
# ORIGINAL WAY - PROOF OF CONCEPT
# Runs in 163 steps
# http://www.pythontutor.com/live.html#mode=edit
# ##################################################
# def answer(x, y):
# """ compares values of x against y
# and vice versa to find the unique value """
# for i in y:
# if i not in x:
# abnormal_value = i
# else:
# for i in x:
# if i not in y:
# abnormal_value = i
# return (abnormal_value)
# Test cases
# ==========
# Inputs:
# (int list) x = [13, 5, 6, 2, 5]
# (int list) y = [5, 2, 5, 13]
# Output:
# (int) 6
# Inputs:
# (int list) x = [14, 27, 1, 4, 2, 50, 3, 1]
# (int list) y = [2, 4, -4, 3, 1, 1, 14, 27, 50]
# Output:
# (int) -4
# Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder.
|
7119d2ebed8b800d0ca37942dd70b426f9364205 | fsnuth98/Computer-Science-Coursework | /Computer Science 1 (Freshman, Python)/CSC101 Lab/Labs/lab06_fixedangle_spiral123/lab06_average.py | 410 | 4.1875 | 4 | '''
Franklin Nuth
Idrissa Jalloh
CSC101 Lab 6
Part 4: Average Value
February 24 2017
'''
N= int(input("Enter number of items you want to purchase: "))
total= 0
if N <= 0:
print("Cannot calculate average.")
else:
for i in range(N):
item= int(input("Enter the price for the item"))
total += item
average= total/N
print("The average is:", average) |
25e4a5607a77c592a8240f88de9e6a351ec91675 | Erika001/CYPErikaGG | /libro/problemas_resueltos/capitulo3/problema3_12.py | 398 | 3.84375 | 4 | MASUE = 0
N = int(input("Determine el numero de empleados: "))
i = 1
for i in range(i,N,1):
NUMEMP = int(input("Determine el numero del empleado: "))
SUE = int(input("Determine el sueldo del empleado: "))
if SUE > MASUE:
MASUE = SUE
MANUM = NUMEMP
i = i + 1
print(f"El empleado con mayor sueldo es: {MANUM}, el mayor sueldo es: {MASUE}")
print("Fin del programa")
|
c319b4f31cadb23409e79287524b73c09fc77604 | rapidcode-technologies-private-limited/Python | /jayprakash/assignment2/Q8. program to check whether an alphabet is a vowel or consonant.py | 171 | 3.515625 | 4 | while True:
n=input('Enter any alphabate=')
if(n=='a')|(n=='e')|(n=='i')|(n=='o')|(n=='u'):
print(n,'is vowle')
else:
print(n,'is consonent')
|
351104e9d94677b9830f4de306ef299c6a419836 | dangulod/PyCourse | /samples/primeros_pasos.py | 1,861 | 4.15625 | 4 | '''
Comentando nuestros scripts, Python permite comentar de dos formas diferentes,
1. Para comentarios más largos entre una triple comilla
2. Con #
'''
print('Hello World!')
# Nuestra primera funcion
def hw():
print('Hello World')
hw()
# Asignar variables
x = [1, 'Hi', 3.14, ['a', 'b', 3]]
x[0]
x[3]
x[3][1]
x[3][1] = 1
x[3][1] += 2
x[3][1] *= 2
x[3][1] **= 2
x[3][1] /= 2
type(x)
_
y = (1, 'Hi', 3.14)
y[0] = 2
del(y)
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
knights.keys()
knights.values()
knights.items()
# Operadores logicos
1 < 0
"car" != "car"
'car' in ('pet', 'house', 'sun')
'car' in ('pet', 'house', 'sun', 'car')
# Dos formas de definir una funcion
exponencial_1 = lambda x, y: x ** y
exponencial_1(2, 3)
def exponencial_2(x, y):
return(x ** y)
exponencial_2(2, 3)
# Bucles for
# 1 loop
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
# 2 loop
for i in range(5):
print(i)
# 3 loop
for i in range(len(words)):
print(words[i])
# 4 loop
x = 0
for i in range(0, 10):
if (i == 5):
continue
else:
x += i
x == 0 + 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9
# 5 loop
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')
# 6 loop
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
# 7 loop
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
# 8 loop
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# while
i = 0
while i < 10:
print(i)
i += 1
# importacion de librerias
from datetime import date
hoy = date.today()
hoy
hoy.__class__
date.today().strftime("%Y-%m-%d")
|
bfe57ba2b35b097dbbde25fa8a72b889a41da5f2 | perolajanice/Python-random-builds | /circle.py | 421 | 4.15625 | 4 | import turtle
def drawPolygon(t, sideLength, numSides):
turnAngle = 360 / numSides
for i in range(numSides):
t.forward(sideLength)
t.right(turnAngle)
def drawCircle(anyTurtle, radius):
circumference = 2 * 3.1415 * radius
sideLength = circumference / 360
drawPolygon(anyTurtle, sideLength, 360)
wn = turtle.Screen()
wheel = turtle.Turtle()
drawCircle(wheel, 20)
wn.exitonclick()
|
74a76cbc642be7af06f31a3438c0a23cc88d3df8 | bill-filler/python-examples | /exceptions.py | 526 | 3.8125 | 4 | #generic catch, no full error
try:
file = open('xxyz.txt', 'r')
print(file.read())
except:
print("File doesn't exist")
#generic catch, put print specific exception
try:
file = open('xxyz.txt', 'r')
print(file.read())
except Exception as err:
print("File doesn't exist", err)
#specific exceptions to catch
#http://go.codeschool.com/python-exceptions
price = input("Enter the price: ")
try:
price = float(price)
print('Price =', price)
except ValueError as err:
print('Not a number!', err)
|
e302dc2afeabb4483eec5607615dd25a5a5579be | Yiting916/Python | /0128_p04_dict.py | 429 | 3.84375 | 4 | Keys = 'P', 'M', 'H'
values = 'Pikachu', 'Mickey Mouse', 'Hello kitty'
dc = dict(zip(Keys, values))
while True:
qkey = input()
if qkey == '-1':
break
if qkey == '-2':
print(dc.keys())
print(dc.values())
continue
elif qkey not in dc:
print(qkey,'does not exist. Enter a new one:')
dc[qkey] = input()
else:
print(dc[qkey])
|
d970802864d3471a28fd2a3a63f006dc6a1d6635 | chrisyarel117/guessnumber | /guessnumber.py | 734 | 4.21875 | 4 | import random
firstname = input("Enter Your First Name: ")
lastname = input("Enter Your Last Name: ")
attempts = 0
number = random.randint(0,10) ###this has the program choose a randome integer number between a & b.
print("Welcome to Guess the Secret Number Game.")
print("Start now!")
while (attempts < 7):
guess = int(input("Enter the secret number: "))
attempts += 1
if (guess > number):
print("Number is too high, it is less than 10.")
print("Try Again!")
elif (guess < number):
print("Number is too low, number is more than 1.")
print("Try Again!")
elif (guess == number):
print("You have won the Game!")
break
if (attempts == 7):
print("You have lost the game. The selected number is: ", number)
|
26cb10aed8375dec3dcb67fe95b561e64d831071 | BeatrizCastex/data-treatment | /aut_fg2.py | 2,576 | 3.8125 | 4 | """ TESTE AUTÔMATO 2
Beatriz de Camargo Castex Ferreira - 10728077 - USP São Carlos - IFSC
05/2020
Nesse programa representamos autômatos probabilisticos como matrizes
e os utilizamos para gerar padões que serão salvos em arquivos para análise.
O objetivo é ser capaz de gerar padrões com qualquer** autômato
probabilistico usando esse programa.
Consulta para método de escolha de estado:
https://www.datacamp.com/community/tutorials/markov-chains-python-tutorial
Consulta para escrita de arquivo:
https://docs.python.org/2/library/csv.html
** muito cuidado ao dizer qualquer, pode ser que tenha algum não testado
que não funcione.
"""
import numpy as np
import csv
# abrir o arquivo para onde vamos importar os padrões
with open('aut_fg2_1000.csv', 'w') as csvfile:
file = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
# Quais são os possíveis estados?
possible_states = np.array([0, 1, 2, 3])
# Criar a matriz de transição de probabilidade que representa o autômato:
# No caso essa matriz mostra as chances de mudar de estado como a seguir:
# [ (0 ficar no 0) (1 ir pra o 0)]
# [ (0 ir pra o 1) (1 ficar no 1)]
auto = np.array([[0.5, 0.0, 0.0, 0.7],
[0.5, 0.1, 0.0, 0.0],
[0.0, 0.9, 0.6, 0.0],
[0.0, 0.0, 0.4, 0.3]])
N = 200 # Quantos padrões você quer gerar?
L = 1000 # Quantos passos você quer que o padrão tenha?
start = 0 # Nódulo inicial
for step in range(N):
# Definir condições iniciais
walk = [start] # Vetor onde será guardado o caminho
state = [1,0,0,0] # Estado inicial
for step in range(L):
# Definir a probabilidade de ir para cada estado:
prob = auto.dot(state) # multiplicamos o autômato com o estado atual
# Escolher um caminho:
# Para isso usamos a função de escolha aleatória do numpy para escolher um
# dos possíveis estados com as probabilidades definidas.
i = np.random.choice(possible_states, replace=True, p=prob)
# marcamos o nódulo em que estamos no caminho:
walk.append(i)
# Definir novo estado:
if (i == 0):
state = [1, 0, 0, 0]
elif (i == 1):
state = [0, 1, 0, 0]
elif (i == 2):
state = [0, 0, 1, 0]
else:
state = [0, 0, 0, 1]
# Agora salvamos o caminho num arquivo:
file.writerow(walk)
|
66195bb93f5514fbe43bb8345f44519590b97d67 | rosspeckomplekt/interpersonal | /interpersonal/classes/interaction.py | 1,859 | 4.40625 | 4 | """
An Interaction describes the interaction between
two Persons
"""
class Interaction:
"""
An Interaction describes the interaction between
two Persons
"""
def __init__(self, person_a, person_b):
"""
Initialize an Interaction object for two Persons
So we can compute the various Interaction functions
:param person_a: A Person
:param person_b: Another Person
"""
self.person_a = person_a
self.person_b = person_b
def find_dominator(self):
"""
Find which Person in the Interaction has the higher dominance
"""
a_dominance = self.person_a.get_personality().dominance
b_dominance = self.person_b.get_personality().dominance
print("The dominator is: ")
if a_dominance > b_dominance:
print(self.person_a.name)
return self.person_a
else:
print(self.person_b.name)
return self.person_b
def is_alliance(self):
"""
Find the magnitude with which the two Persons
are likely to be allies
"""
a_friendliness = self.person_a.get_personality().friendliness
b_friendliness = self.person_b.get_personality().friendliness
if a_friendliness * b_friendliness >= 0:
print(self.person_a.name + " and " + self.person_b.name + " are friends")
return True
else:
print(self.person_a.name + " and " + self.person_b.name + " are enemies")
return False
def get_alliance(self):
"""
Find the magnitude with which the two Persons are predicted to be
allied or enemies
"""
a = self.person_a.get_personality().friendliness
b = self.person_b.get_personality().dominance
return (a * b) * (abs(a) + abs(b)) / 20
|
4756e52f362441b67bbd967979a58e6fdb4f772e | abhisek08/python-dictionary | /dict empty.py | 109 | 3.984375 | 4 | '''
Write a Python program to check a dictionary is empty or not.
'''
d={}
if not bool(d):
print('empty') |
784786b8e3d235c9f08b324e58b1f8ef1b0cb278 | wssir/practice | /py.py | 1,053 | 4.03125 | 4 | #ceasor cipher
def encrypt(key, message):
message = message.upper()
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ''
for letter in message:
if letter in alpha:
letter_index = (alpha.find(letter)+ key) % len(alpha)
result = result + alpha[letter_index]
else:
result = result + letter
return result
def decrypt(key,message):
message = message.upper()
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ''
for letter in message:
if letter in alpha:
letter_index = (alpha.find(letter) - key) %len(alpha)
result = result +alpha[letter_index]
else:
result = result + letter
return result
def main():
text = input("enter the text: ")
shift = int(input("enter the shift key: "))
encrypted = encrypt(shift,text)
print("your text is now encrypted : ", encrypted)
decrypted = decrypt(shift,encrypted)
print("Original text is :",decrypted)
if __name__ == "__main__":
main()
|
2466f41fc2a493ee6eb3748370f6e213ca23a42b | 15zhazhahe/LeetCode | /Python/326. Power of Three.py | 199 | 3.765625 | 4 | class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
tmp = 1
while tmp < n:
tmp *= 3
return tmp == n
|
194cfc2e24370a1035bebc6a477ba58e107b222b | skshiwali30/code-chef | /mahasena.py | 316 | 3.578125 | 4 | totalSoldier = int(input())
soldier_list = list(map(int, input().split()))
evenCount, oddCount = 0, 0
for soldier in soldier_list:
if soldier % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
if evenCount > oddCount:
print("READY FOR BATTLE")
else:
print("NOT READY") |
1a6d7319c8e619790a2a4650a2e9f09cac8fddb1 | svarogjk/algorithms_completed | /heap_sort.py | 2,745 | 3.703125 | 4 | from math import log2
class Heap():
def __init__(self, array: list):
self.array = array
self.heap_height = log2(len(self.array))
def parent(self, i: int)->int:
return i // 2
def left(self, i: int)->int:
return 2 * i + 1
def right(self, i: int)->int:
return 2 * i + 2
def max_heap_prop(self):
for i in range(len(self.array)):
_parent = self.parent(i)
if self.array[_parent] < self.array[i]:
return False
return True
def max_heapify(self, array, i):
l = self.left(i)
r = self.right(i)
if l <= len(array) - 1 and array[l] > array[i]:
largest = l
else:
largest = i
if r <= len(array) - 1 and array[r] > array[largest]:
largest = r
if largest != i:
array[i], array[largest] = array[largest], array[i]
self.max_heapify(array, largest)
def build_max_heap(self):
for i in range(len(self.array) // 2 - 1, -1, -1):
self.max_heapify(self.array, i)
def heap_sort(self):
self.build_max_heap()
for i in range(len(self.array) - 1, 0, -1):
self.array[0], self.array[i] = self.array[i], self.array[0]
_array = self.array[:i]
self.max_heapify(_array, 0)
self.array = _array + self.array[i:]
print(self.array)
class HeapQueue(Heap):
def heap_maximum(self):
return self.array[0]
def heap_extract_max(self):
if self.array == []:
raise ValueError("empty array!!!")
self.array[0], self.array[len(self.array) - 1] = self.array[len(self.array) - 1], self.array[0]
_max = self.array.pop()
self.max_heapify(self.array, 0)
return _max
def heap_increase_key(self):
i = len(self.array) - 1
while i > 0 and self.array[self.parent(i)] < self.array[i]:
self.array[i], self.array[self.parent(i)] = self.array[self.parent(i)], self.array[i]
i = self.parent(i)
def max_heap_insert(self, key):
self.array.append(key)
self.heap_increase_key()
if __name__ == '__main__':
from unittest import TestCase, main
# array = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
array = [15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1]
h = HeapQueue(array)
# h.max_heapify(h.array, 1)
# h.heap_sort()
h.build_max_heap()
print(h.array)
insert_array = [20, 2, 25, 3, 26, 5]
for e in insert_array:
h.max_heap_insert(e)
print(h.array)
# class SimpleTest(TestCase):
#
# def test(self):
# self.assertEqual(h.array, sorted(A))
#
# main() |
f24af4dd313bdba85bf4f679411bc56b6fe52ba0 | beckysteele/python_projects | /phys650/gamma_exercise/gamma.py | 403 | 3.890625 | 4 | import math as m
user_input = input('Input a number >> ')
# Check for fraction input
if "/" in user_input:
temp = user_input.split('/')
# print(len(temp))
if len(temp) == 2:
real_input = float(temp[0])/float(temp[1])
# For normal decimal inputs
else: real_input = float(user_input)
result = m.gamma(real_input)
print('The Gamma function of ', user_input, ' is equal to: ', result) |
372e0e86c7ade80a796de88d9400299442a42229 | fluTN/influenza | /models/models_utils.py | 13,897 | 3.5 | 4 | import os
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import cross_val_score
##### UTILITIES #######
def generate_keywords(keywords = "../data/keywords/keywords_italy.txt"):
"""
Generate a list of keywords (Wikipedia's pages) which are used to
select the columns of the dataframe we are going to use as dataset
to train our model.
:param keywords: the path to a file containing \n separated Wikipedia's
page names.
:return: a keyword list.
"""
selected_columns = []
file_ = open(keywords, "r")
for line in file_:
if line != "Week":
selected_columns.append(line.replace("\n", "").replace("\\", ""))
return selected_columns
def generate_features(year_a, year_b, number_a, number_b):
if not year_a.empty:
if (number_a != 2007):
first_part= year_a.copy()[41:52]
else:
first_part= year_a.copy()[48:52]
else:
first_part = pd.DataFrame()
if not year_b.empty and number_b != 2007:
second_part= year_b.copy()[0:15]
else:
second_part = pd.DataFrame()
return first_part.append(second_part)
def generate(stop_year, exclude, path_features="./../data/wikipedia_italy/new_data"):
"""
Generate a dataframe with as columns the Wikipedia's pages and as rows
the number of pageviews for each week and for each page. The dataframe
contains all the influenza season without the one specified by stop_year.
:param stop_year: The influenza seasosn which will not be inserted into
the final dataframe.
:param path_features: the path to the directory containing all the files
with the data.
:return: a dataframe containing all influenza season, which can be used to
train the model.
"""
# The stop year must not be in the exclude list
assert (stop_year not in exclude)
# Generate an empty dataframe
dataset = pd.DataFrame()
# Get all features files and sort the list
file_list = os.listdir(path_features)
file_list.sort()
for i in range(0, len(file_list)-1):
# If the file's year is equal than stop_year then do anything
if int(file_list[i].replace(".csv", "")) != stop_year-1:
tmp_a = pd.read_csv(os.path.join(path_features, file_list[i]), encoding = 'utf8', delimiter=',')
else:
tmp_a = pd.DataFrame()
if int(file_list[i+1].replace(".csv", "")) != stop_year:
tmp_b = pd.read_csv(os.path.join(path_features, file_list[i+1]), encoding = 'utf8', delimiter=',')
else:
tmp_b = pd.DataFrame()
# Do not add years which are in the exclude list
if int(file_list[i+1].replace(".csv", "")) in exclude:
continue
# If the dataset is empty the generate a new dataframe.
# Append a new dataframe if the dataset is not empty.
if dataset.empty:
dataset = generate_features(tmp_a, tmp_b, int(file_list[i].replace(".csv", "")), int(file_list[i+1].replace(".csv", "")))
else:
dataset = dataset.append(generate_features(tmp_a, tmp_b, int(file_list[i].replace(".csv", "")), int(file_list[i+1].replace(".csv", ""))))
return dataset
def generate_one_year(year, path_features="./../data/wikipedia_italy/new_data"):
"""
Generate a dataframe containing the data of only one influenza season.
The dataframe contains, for each week, the pageview of a each Wikipedia's page
of the dataset.
:param year: the year we want to generate the dataset of.
:param path_features: the path where the data files are store.
:return: a dataframe which can be used to validate the trained model.
"""
# Generate an empty dataframe
dataset = pd.DataFrame()
# Get all features files and sort the list
file_list = os.listdir(path_features)
file_list.sort()
for i in range(0, len(file_list)-1):
if int(file_list[i].replace(".csv", "")) == year-1:
tmp_a = pd.read_csv(os.path.join(path_features, file_list[i]), encoding = 'utf8', delimiter=',')
else:
tmp_a = pd.DataFrame()
if int(file_list[i+1].replace(".csv", "")) == year:
tmp_b = pd.read_csv(os.path.join(path_features, file_list[i+1]), encoding = 'utf8', delimiter=',')
else:
tmp_b = pd.DataFrame()
# If the dataset is empty the generate a new dataframe.
# Append a new dataframe if the dataset is not empty.
if dataset.empty:
dataset = generate_features(tmp_a, tmp_b, int(file_list[i].replace(".csv", "")), int(file_list[i+1].replace(".csv", "")))
else:
dataset = dataset.append(generate_features(tmp_a, tmp_b, int(file_list[i].replace(".csv", "")), int(file_list[i+1].replace(".csv", ""))))
return dataset
def generate_labels(stop_year, exclude, path_labels="./../data/italy/new_data"):
"""
Generate a dataframe with all the ILI incidence data for every influenza
season, except for the one specified by stop_year.
:param stop_year: the influenza season we want to exclude.
:param path_labels: the path to the data files which store the incidence data.
:return: a dataframe containing, for each week, the incidence value.
"""
# The stop year must not be in the exclude list
assert (stop_year not in exclude)
dataset = pd.DataFrame()
# Get all features files and sort the list
file_list = os.listdir(path_labels)
file_list.sort()
for i in range(0, len(file_list)):
if (file_list[i] != "tabula-2006_2007.csv"):
# Read the file
_file = pd.read_csv(os.path.join(path_labels, file_list[i]), engine="python")
# Append data without the stop year
years = file_list[i].split("_")
# Do not add years which are in the exclude list
if int(years[1].replace(".csv", "")) in exclude:
continue
if int(years[1].replace(".csv", "")) != stop_year:
if int(years[0]) == 2007:
dataset = dataset.append(_file[7:11])
else:
dataset = dataset.append(_file[0:11])
if int(years[0]) != stop_year-1:
dataset = dataset.append(_file[11:26])
return dataset
def generate_labels_one_year(stop_year, path_labels="./../data/italy/new_data"):
"""
Generate a dataframe with the incidence data for a single influenza season.
:param stop_year: the influenza season we want to get the data of.
:param path_labels: the path to the files which store the incidence data.
:return: a dataframe containing the incidence value for the specified influenza seasons.
"""
dataset = pd.DataFrame()
# Get all features files and sort the list
file_list = os.listdir(path_labels)
file_list.sort()
for i in range(0, len(file_list)):
if (file_list[i] != "tabula-2006_2007.csv"):
# Read the file
_file = pd.read_csv(os.path.join(path_labels, file_list[i]))
# Append data without the stop year
years = file_list[i].replace("tabula-", "").split("_")
if int(years[1].replace(".csv", "")) == stop_year:
if int(years[0]) == 2007:
dataset = dataset.append(_file[7:11])
else:
dataset = dataset.append(_file[0:11])
if int(years[0]) == stop_year-1:
dataset = dataset.append(_file[11:26])
return dataset
def generate_labels_sum():
# Get all features files and sort the list
file_list = os.listdir("./../data/austria")
file_list.sort()
for i in range(0, len(file_list)):
_file = pd.read_csv(os.path.join("./../data/austria", file_list[i]))
_file_2 = pd.read_csv(os.path.join("./../data/germany", file_list[i]))
total = pd.DataFrame()
total['week'] = _file['week']
total['incidence'] = _file['incidence'] + _file_2['incidence']
total.to_csv(file_list[i])
def standardize_data(train, test):
"""
Standardize between [-1, 1] the train and test set by applying this
formula for each feature:
x_new = (x-dataset_mean)/(dataset_max - dataset_min)
:param train: the training dataset (represented with a Pandas dataframe).
:param test: the testing dataset (represented with a Pandas dataframe).
:return: the train and test dataset standardized
"""
dmean = train.mean(axis=0)
#dmax = train.max(axis=0)
#dmin = train.min(axis=0)
dstd = train.std(axis=0)
#ddenom= dmax - dmin
ddenom = dstd
dataset_imp = (train - dmean) / ddenom
data_imp = (test - dmean) / ddenom
dataset_imp.fillna(method="pad", inplace=True)
data_imp.fillna(method="pad", inplace=True)
data_imp.replace([np.inf, -np.inf], np.nan, inplace=True)
dataset_imp.replace([np.inf, -np.inf], np.nan, inplace=True)
dataset_imp.fillna(method="pad", inplace=True)
data_imp.fillna(method="pad", inplace=True)
dataset_imp[np.isnan(dataset_imp)] = 0.0
data_imp[np.isnan(data_imp)] = 0.0
return (dataset_imp, data_imp)
def standardize_week(train, test, column_list):
# Concatenate together the dataframes
data_total = pd.concat([train, test])
# Get all the unique weeks
unique_weeks = data_total["week"].unique()
# Build some temporary dataframes
train_tmp = pd.DataFrame(columns=column_list)
test_tmp = pd.DataFrame(columns=column_list)
total_means = pd.DataFrame(columns=column_list)
# Generate a matrix with all the means for each week
for c in unique_weeks:
mean = data_total.loc[data_total.week == c, column_list].mean()
mean.loc["week"] = c
total_means = total_means.append(mean, ignore_index=True)
# Generate scaled train data.
for index, row in train.iterrows():
train_tmp = train_tmp.append(row-total_means[total_means.week == row["week"]])
# Generated scaled test data.
for index, row in test.iterrows():
test_tmp = test_tmp.append(row-total_means[total_means.week == row["week"]])
# Reconstruct month column
train_tmp = train_tmp.drop(["month"], axis=1)
train_tmp["month"] = train["month"].tolist()
test_tmp = test_tmp.drop(["month"], axis=1)
test_tmp["month"] = test["month"].tolist()
# Reconstruct week columns
#train_tmp.update(train["week"])
#test_tmp.update(test["week"])
return (train_tmp, test_tmp)
def stz(data):
"""
Standardize between [-1, 1] the data give by applying this
formula to each feature:
x_new = (x-dataset_mean)/(dataset_max - dataset_min)
:param data: the data we want to standardize
:return: the standardized data
"""
dmean = data.mean(axis=0)
dmax = data.max(axis=0)
dmin = data.min(axis=0)
dmax_min = dmax - dmin
dataset_imp = (data - dmean) / dmax_min
dataset_imp[np.isnan(dataset_imp)] = 0
return dataset_imp
def stz_zero(data):
"""
Standardize between [-1, 1] the data give by applying this
formula to each feature:
x_new = (x-dataset_mean)/(dataset_max - dataset_min)
:param data: the data we want to standardize
:return: the standardized data
"""
dmax = data.max(axis=0)
dmin = data.min(axis=0)
dmax_min = dmax - dmin
dataset_imp = (data - dmin) / dmax_min
dataset_imp[np.isnan(dataset_imp)] = 0
return dataset_imp
def get_important_pages(important_pages, top=10):
"""
Get the most important feature selected by the model.
:param important_pages: a dictionary with, for each of the features,
a list of their weights in each of the models.
:param top: how many feature we want to return.
:return: the top feauture
"""
imp_pages_avg = dict((k, sum(v) / float(len(v))) for k, v in important_pages.items())
_terms_avg_top = sorted(sorted(imp_pages_avg.items(),
key=lambda value: value[0]),
key=lambda value: value[1],
reverse=True
)
return _terms_avg_top[0:top]
def correlation_matrix(df, title, labels, output_name):
"""
Print the correlation matrix from the dataframe given.
(Code taken from https://datascience.stackexchange.com/questions/10459/
calculation-and-visualization-of-correlation-matrix-with-pandas)
:param df: dataframe used
:param title: the title of the graph
:param labels: the labels used for naming rows/columns
:return: print on screen the correlation matrix
"""
from matplotlib import pyplot as plt
fig = plt.figure(10, figsize=(15, 15))
ax1 = fig.add_subplot(111)
cax = ax1.matshow(df.corr(), vmin=-1, vmax=1)
plt.title(title, fontsize=18)
ax1.xaxis.set_ticks_position('bottom')
plt.xticks(range(0, len(labels)), labels, rotation=45, fontsize=17)
plt.yticks(range(0, len(labels)), labels, fontsize=17)
fig.colorbar(cax)
plt.savefig(output_name, dpi=150)
def add_month(dataset_zero):
"""
Add a month column to the dataset
:param dataset_zero: the original dataset, it must have a two column, one named
year and the other named week
:return: dataframe with added month column and removed week column
"""
dataset_zero["week"] = dataset_zero["week"].apply(pd.to_numeric)
dataset_zero["year"] = dataset_zero["year"].apply(pd.to_numeric)
dataset_zero["full_date"] = pd.to_datetime(dataset_zero.year.astype(str), format='%Y') + \
pd.to_timedelta(dataset_zero.week.mul(7).astype(str) + ' days')
dataset_zero["month"] = pd.DatetimeIndex(dataset_zero['full_date']).month
dataset_zero = dataset_zero.drop(["full_date"], axis=1)
return dataset_zero
|
cdad8f217abc3b34c2b8806595e348f43eff05f9 | zeziba/bmp280_pine64 | /src/combiner_csv.py | 767 | 3.53125 | 4 | """
This file is intended to add all the csv entries into the main sqlite file.
"""
import database
import csv
import os
#_path_ = '/home/ubuntu/pybmp180/pyscript/data'
_path_ = 'data'
with database.DatabaseManager('data') as db:
for file in os.listdir(_path_):
if 'csv' in file:
_p = os.path.join(_path_, file)
print(_p)
with open(_p, 'rt', encoding='utf-8') as _csv:
dr = csv.DictReader(_csv)
for line in dr:
db.add_data(line['Time(date)'], line[' degree'], line[' df'],
line[' pascals'], line[' hectopascals'], line[' humidity'])
if len(db) > 500:
db.commit()
db.commit()
|
082a05a1923010746e4bf68c3ecdd8cb70efa183 | paik11012/Algorithm | /study/d2/1986_zigzag_num.py | 257 | 3.53125 | 4 | tc = int(input())
for tcc in range(1, tc+1):
num = int(input())
result = 0
for i in range(1, num+1): # 1 2 3 4 5
if i % 2 == 1 :
result += i
else:
result += (-1 * i)
print('#{} {}'.format(tcc, result)) |
a0e74f58899f9c6468f7a2b4bd077349e4eb6e48 | victoraugusto6/Exercicios-Python | /Programas/Mundo 2/ex056.py | 850 | 3.578125 | 4 | from datetime import date
somaIdade = 0
mediaIdade = 0
maiorIdadeHomem = 0
nomeVelho = ''
totMulher20 = 0
for p in range(1, 5):
print('-=-'*8)
print(f'----- {p} Pessoa -----')
print('-=-'*8)
nome = input('Nome: ').strip()
idade = int(input('Idade: '))
somaIdade += idade
sexo = (input('Sexo [M/F]: ')).upper().strip()
if p == 1 and sexo in 'Mm':
maiorIdadeHomem = idade
nomeVelho = nome
if sexo in 'Mm' and idade > maiorIdadeHomem:
maiorIdadeHomem = idade
nomeVelho = nome
if sexo in 'Ff' and idade < 20:
totMulher20 += 1
mediaIdade = somaIdade/4
print(f'A média de idade do grupo é: {mediaIdade}')
print(
f'O homem mais velho do grupo tem {maiorIdadeHomem} anos e se chama {nomeVelho}')
print(f'Ao todo, são {totMulher20} mulheres menores de 20 anos')
|
3646911498cba7627ec5d93654ca853de8b3da0d | scottsuk0306/rcCarEndtoEnd | /catkin_ws/src/control/src/test.py | 291 | 3.734375 | 4 | #! /usr/bin/env python
from curtsies import Input
def main():
with Input(keynames='curses') as input_generator:
for e in input_generator:
if e=='w': print("go front")
if e=='s': print("go back")
print()
if __name__ == '__main__':
main() |
2fc385f1d8f3ec3aa7a3f3da252303dc3637314a | jamortegui/Personal-projects | /OrdenarArchivos.py | 8,495 | 3.6875 | 4 | from FilesManagement import *
def readDirectorys():
'''Reads the content of directorys.txt file and returns a
dictionary fordelName:forderRoute with the folders contained
in the file
'''
directorys = {} #Dictionary that will contain the names and routes of the objective folders
with open("directorys.txt") as file:
for line in file.readlines(): #Iterates over the lines of the file
line = line.strip() #Remove the \n character
if line != "": #If the line is not empy, saves the content of the line in the dictionary
line = line.split(",")
directorys[line[0]]=line[1]
if not isdir(line[1]):
create_dir(line[1]) #Creates the directory if it doesn´t exist
return directorys #Returns the filled dictionary
def print_directorys():
'''Imprime el contenido del diccionario directorys en forma de tabla
'''
toPrint = "Nombre\t|Ruta\n"
for directory in directorys:
toPrint += "{}\t|{}\n".format(directory,directorys[directory])
print(toPrint)
def mover_archivo(ruta,ruta_destino= ""):
'''Mueve el archivo ruta a la carpeta ruta_destino
Si ruta destino no se especifica al momento de llamar la funcion se le pregunta
al usuario a donde quiere mover la carpeta
ruta: Posicion actual del archivo que se desea mover
ruta_destino: Ruta a la cual se desea mover el archivo'''
nombre_archivo = get_filename(ruta) #Nombre del archivo
if ruta_destino != "":
ruta_destino = unir_ruta(ruta_destino,nombre_archivo) #Crea la ruta de destino del archivo
else:
print_directorys()
showMessage("Por favor seleccione una carpeta",type="hand") #Displays a message to let the user know that the code needs his interaction
choise = input ("Por favor ingrese la carpeta a la cual desea mover la carpeta:")
while choise not in directorys.keys(): #Verifica que la entrada del usuario sea valida
choise = input ("Por favor ingrese un nombre valido")
ruta_destino = unir_ruta(directorys[choise],nombre_archivo) #Crea la ruta de destino del archivo
move_file(ruta,ruta_destino) #Mueve el archivo a la ruta de destino
def unzip_all(path):
'''looks for all the zipfiles in a directory and ask the user if he wants to unzip them one by None
path: The absolute path of the folder that contains the zip files'''
files = lista_archivos(path) #List of all the files in the path folder
called = False #Aux variable that indicates if the user have been notified already about the need of interaction
for file in files:
filePath = unir_ruta(path,file)
if file_type(filePath).lower() == "zip":
if not called:
showMessage("Do you like to unzip this file?",type="question") #Notifies the user about the need of interaction if has not been notified before
called=True #States that the user have already been notified
choise = input("Would you like to uncompress the file {}? [y/n]".format(get_filename(filePath))) #Ask the usr if he want to unzip the file
while choise not in ["y","n"]: #Validates the selecction of a valid option
choise = "Please select a valid option [y/n]"
if choise == "y":
unzip(filePath,remove=True) #unzips the file
def ordenar_archivos(ruta,indice=0):
'''Funcion que organiza los archivos de la carpeta especificada en ruta
El parametro indice sirve para determinar la impresion del progreso del ordenador de archivos'''
unzip_all(ruta) #Unzips all the zip files if there is any
archivos = lista_archivos(ruta) #Crea una lista con los nombres de los archivos que se encuentran en la carpeta
archivos = ordenar_por_fecha(ruta,archivos) #Ordena los archivos de la carpeta por fecha y retorna una lista con las rutas absolutas de los archivos
categorias = list(map(clasificar_Archivo,archivos)) #Categorias de los archivos que hay en la carpeta
if categorias.count("folder") >= 1: #Verifica si existen sub carpetas en la carpeta actual
choise = input("La carpeta: {} tiene {} carpetas adentro, desea...\n(0) clasificar los archivos de las subcarpetas\n(1) mover la carpeta completa\n".format(ruta,categorias.count("folder"))) #Le pregunta al usuario si desea mover la carpeta con subcarpetas o calsificar los archivos que hay dentro
while choise not in ["0","1"]: #Verifica que el usuario ingrese una opcion valdia
choise = input("Por favor ingrese una opcion valida")
if choise == "1":
mover_archivo(ruta) #Mueve la carpeta, le pregunta al usuario la carpeta de destino
return #Acaba la ejecucion de la funcion una vez de mueve la carpeta
if categorias.count("folder") == 0: #Verifies again if there is any subfolder
images = categorias.count("imagen") #Number of images in the folder
videos = categorias.count("video") #Number of videos in the folder
books = categorias.count("libro") #Number of books in the folder
others = categorias.count("otro") #Number of "other" files in the folder
if images >= minFiles and videos <= minFiles and books <= minFiles and others <= minFiles: #Moves the full folder if it contains mostly images and if the number of images is superior to minFiles
mover_archivo(ruta,ruta_destino=directorys["images"]) #Moves the complete folder to the images folder
return #Finish the function
if videos >= minFiles and images <= minFiles and books <= minFiles and others <= minFiles: #Moves the full folder if it contains mostly videos and if the number of videos is superior to minFiles
mover_archivo(ruta,ruta_destino=directorys["videos"]) #Moves the complete folder to the videos folder
return #Finish the function
if books >= minFiles and images <= minFiles and videos <= minFiles and others <= minFiles: #Moves the full folder if it contains mostly books and if the number of books is superior to minFiles
mover_archivo(ruta,ruta_destino=directorys["books"]) #Moves the complete folder to the books folder
return #Finish the function
if others >= minFiles and images <= minFiles and videos <= minFiles and books <= minFiles: #Moves the full folder if it contains mostly other files and if the number of these files is superior to minFiles
mover_archivo(ruta,ruta_destino=directorys["others"]) #Moves the complete folder to the others folder
return #Finish the function
for i in range(len(archivos)): #Iterates over all the indexis of the files list in the folder
file = archivos[i] #Retrieves the file from the files list
filePath = unir_ruta(ruta,file) #Absolute path of the current file
if isdir(filePath):
ordenar_archivos(filePath,indice=indice+1) #If the current file is a dir, recoursively calls this function over that directory, augmenting the index by one
elif clasificar_Archivo(filePath) == "imagen":
mover_archivo(filePath,ruta_destino=directorys["images"]) #Moves the file to the images folder if it is an image
elif clasificar_Archivo(filePath) == "video":
mover_archivo(filePath,ruta_destino=directorys["videos"]) #Moves the file to the videos folder if it is a video
elif clasificar_Archivo(filePath) == "libro":
mover_archivo(filePath,ruta_destino=directorys["books"]) #Moves the file to the books folder if it is a book
elif clasificar_Archivo(filePath) == "ejecutable":
mover_archivo(filePath,ruta_destino=directorys["exe"]) #Moves the file to the exe folder if it is a windows executable
else:
mover_archivo(filePath,ruta_destino=directorys["others"]) #Moves the file to the others folder if its type does not correspond to any file type mentioned above
print("{}Procesando... {}% [{}/{}]".format(">"*indice,i*100/len(archivos),i,len(archivos))) #Prints the progress of the program
minFiles = 3 #Minimum number of files to move a complete folder
directorys = readDirectorys() #Diccionario que contiene los directorios a los que se moveran los archivos
ruta=input("Ingrese la ruta absoluta de la carpera que desea analizar:\n")
while not isdir(ruta):
ruta=input("No ha ingresado una ruta valida, por favor intente de nuevo:\n")
ordenar_archivos(ruta)
|
50cf4eb13f42bbe2a7bc94ef610deea10fea1192 | mohamedlafiteh/strath-uni-problems-and-solution | /python-programming-examples-master/01/python/Dicts.py | 854 | 3.828125 | 4 | #!/usr/bin/env python3
def dicts(dictValues):
print(">> Start of dicts")
dictValues.clear()
dictValues["localhost"] = "127.0.0.1"
dictValues["googleDNS1"] = "8.8.8.8"
dictValues["googleDNS2"] = "8.8.4.4"
dictValues["myMachine"] = "192.168.1.66"
print(dictValues)
dictValues.pop("myMachine")
print(dictValues)
keys = list(dictValues.keys())
print("Keys : " + str(keys))
values = list(dictValues.values())
print("Values : " + str(values))
print(">> End of dicts")
if __name__ == "__main__":
dictValues = {}
dictValues["AnotherMachine"] = "10.0.0.12"
copyDict = dictValues.copy()
print("Dictionary values before: " + str(dictValues))
dicts(dictValues)
print("Dictionary values after: " + str(dictValues))
print("Copy of original dictionary: " + str(copyDict)) |
d30bbd4981e5e8c7da525d3dd432d3722006028a | AKSHAY-KR99/luminarpython | /languageFundamental/flowcontrols/dicisionmaking/scnd_Largst_sort.py | 850 | 4.25 | 4 | num1=int(input("Enter no1 "))
num2=int(input("Enter no2 "))
num3=int(input("Enter no3 "))
if((num1>num2)&(num1>num3)):
if num2>num3:
print(num2," is second largest")
print("Sorted order is ",num1,num2,num3)
else:
print(num3," is second largest")
print("Sorted order is ", num1, num3, num2)
elif((num2>num1)&(num2>num3)):
if num1>num3:
print(num1," is second largest")
print("Sorted order is ",num2,num1,num3)
else:
print(num3," is second largest")
print("Sorted order is ", num2, num3, num1)
elif((num3>num2)&(num3>num1)):
if num2>num1:
print(num2," is second largest")
print("Sorted order is ",num3,num2,num1)
else:
print(num1," is second largest")
print("Sorted order is ", num3, num1, num2)
else:
print("Numbers are equal") |
3b1456cf2503a6e55bb6d1e88c859061cb84fc0b | alvarillo89/UGR-MachineLearning | /Práctica 1/codigo.py | 15,323 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Trabajo 1
Álvaro Fernández García.
Grupo 3.
"""
import numpy as np
import matplotlib.pyplot as plt
def simula_unif(N=2, dims=2, size=(0, 1)):
m = np.random.uniform(low=size[0],
high=size[1],
size=(N, dims))
return m
def label_data(x1, x2):
y = np.sign((x1-0.2)**2 + x2**2 - 0.6)
idx = np.random.choice(range(y.shape[0]), size=(int(y.shape[0]*0.1)), replace=True)
y[idx] *= -1
return y
def coef2line(w):
if(len(w)!= 3):
raise ValueError('Solo se aceptan rectas para el plano 2d. Formato: [<a0>, <a1>, <b>].')
a = -w[0]/w[1]
b = -w[2]/w[1]
return a, b
def plot_data(X, y, w):
#Preparar datos
a, b = coef2line(w)
min_xy = X.min(axis=0)
max_xy = X.max(axis=0)
border_xy = (max_xy-min_xy)*0.01
#Generar grid de predicciones
xx, yy = np.mgrid[min_xy[0]-border_xy[0]:max_xy[0]+border_xy[0]+0.001:border_xy[0],
min_xy[1]-border_xy[1]:max_xy[1]+border_xy[1]+0.001:border_xy[1]]
grid = np.c_[xx.ravel(), yy.ravel(), np.ones_like(xx).ravel()]
pred_y = grid.dot(w)
pred_y = np.clip(pred_y, -1, 1).reshape(xx.shape)
#Plot
f, ax = plt.subplots(figsize=(8, 6))
contour = ax.contourf(xx, yy, pred_y, 50, cmap='RdBu',
vmin=-1, vmax=1)
ax_c = f.colorbar(contour)
ax_c.set_label('$w^tx$')
ax_c.set_ticks([-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1])
ax.scatter(X[:, 0], X[:, 1], c=y, s=50, linewidth=2,
cmap="RdYlBu", edgecolor='white', label='Datos')
ax.plot(grid[:, 0], a*grid[:, 0]+b, 'black', linewidth=2.0, label='Solucion')
ax.set(
xlim=(min_xy[0]-border_xy[0], max_xy[0]+border_xy[0]),
ylim=(min_xy[1]-border_xy[1], max_xy[1]+border_xy[1]),
xlabel='Intensidad promedio', ylabel='Simetria')
ax.legend()
plt.title('Solucion ejercicio 2.1')
plt.show()
#Coloca los pesos como es necesario para la funcion anterior:
def permutateWeight(w):
w2 = w.copy()
aux = np.float64(0)
aux = w2[0]
w2[0] = w2[1]
w2[1] = w2[2]
w2[2] = aux
return w2
# Fijar la semilla:
np.random.seed(8)
########################################################################################################################
# 1:
# Ejercicio sobre la búsqueda iterativa de óptimos
########################################################################################################################
# EJERCICIO 1.1
# Implementación del Gradiente Descendente:
def GD1(X, w, n, gd_func, MAX_ITERS):
index = -1 #Si no supera el umbral
for i in range(MAX_ITERS):
w = w - n * gd_func(X, w)
if(E(w[0], w[1]) < 10**(-14)):
index = i
break
return index, w[0], w[1]
#--------------------------------------------------------------------------
# EJERCICIO 1.2:
#Definición de la función E(u,v):
def E(u,v):
return (((u**3) * np.exp(v-2)) - (4 * (v**3) * np.exp(-u))) **2
# Cálculo del gradiente para la función del ejercicio 1.2 b):
def gd_E(X, w):
u = w[0]
v = w[1]
# Como esta parte es igual para ambas, la calculamos una sola vez:
aux = 2 * ((u**3) * np.exp(v-2) - 4 * (v**3) * np.exp(-u))
du = aux * (3 * np.exp(v-2) * (u**2) + 4 * (v**3) * np.exp(-u))
dv = aux * ((u**3) * np.exp(v-2) - 12 * (v**2) * np.exp(-u))
return np.array([du, dv], np.float64)
"""
Apartados b) y c):
nu = 0.05
Maximo de iteraciones = 10000
"""
print("Parte 1: Ejercicio 2: Apartados b) y c)")
X = np.array([0,0], np.float64)
w = np.array([1,1], np.float64)
i,u,v = GD1(X, w, 0.05, gd_E, 10000)
print("Iteraciones: {}\nu: {}\nv: {}\nE(u,v): {}".format(i,u,v, E(u,v)))
z = input()
#--------------------------------------------------------------------------
# EJERCICIO 1.3
# Implementación de f(x,y)
def f(x,y):
return (x-2)**2 + 2*(y+2)**2 + 2*np.sin(2*np.pi*x)*np.sin(2*np.pi*y)
# Cálculo del gradiente para la función del ejercicio 1.3:
def gd_f(X, w):
x = w[0]
y = w[1]
dx = 2*x - 4 + (4 * np.pi * np.cos(2*np.pi*x) * np.sin(2*np.pi*y))
dy = 4*y + 8 + (4 * np.pi * np.sin(2*np.pi*x) * np.cos(2*np.pi*y))
return np.array([dx, dy], np.float64)
# Implementación del GD pero con las gráficas y los mínimos incorporados:
def GD2(X, w, n, gd_func, MAX_ITERS):
out = []
minval = 1000000
minx = 0
miny = 0
#Añadir el valor inicial:
out.append(f(w[0], w[1]))
for i in range(MAX_ITERS):
w = w - n * gd_func(X, w)
out.append(f(w[0], w[1]))
if(f(w[0], w[1]) < minval):
minval = f(w[0], w[1])
minx = w[0]
miny = w[1]
return out, minx, miny
"""
Apartado a):
Numero de iteraciones: 50
1ª ejecucion: nu = 0.01
2ª ejecucion: nu = 0.1
"""
print("Parte 1: Ejercicio 3: Apartado a)")
X = np.array([0,0], np.float64)
w = np.array([1,1], np.float64)
out1,a,b = GD2(X, w, 0.01, gd_f, 50)
w = np.array([1,1], np.float64)
out2,a,b = GD2(X, w, 0.1, gd_f, 50)
# Dibujar la gráfica:
X_AXIS = range(0, 51)
plt.plot(X_AXIS, out1, label='n=0.01')
plt.plot(X_AXIS, out2, label='n=0.1')
plt.xlabel("Iteraciones")
plt.ylabel("f")
plt.legend()
plt.show()
"""
Apartado b):
Como no se mencionan que valores de nu e iteraciones utilizar
realizare las ejecuciones con los ultimos valores enunciados:
nu = 0.1
Numero iteraciones = 50
"""
print("Parte 1: Ejercicio 3: Apartado b)")
n = 0.1
MAX_ITERS = 50
w = np.array([2.1,-2.1], np.float64)
tmp1,x1,y1 = GD2(X, w, n, gd_f, MAX_ITERS)
w =np.array([3,-3], np.float64)
tmp2,x2,y2 = GD2(X, w, n, gd_f, MAX_ITERS)
w = np.array([1.5,1.5], np.float64)
tmp3,x3,y3 = GD2(X, w, n, gd_f, MAX_ITERS)
w = np.array([1,-1], np.float64)
tmp4,x4,y4 = GD2(X, w, n, gd_f, MAX_ITERS)
# Generar la tabla:
table1 = "| x0=2.1 | y0=-2.1 | x={} | y={} | f={} |".format(x1, y1, f(x1, y1))
table2 = "| x0= 3 | y0= -3 | x={} | y={} | f={} |".format(x2, y2, f(x2, y2))
table3 = "| x0=1.5 | y0= 1.5 | x={} | y={} | f={} |".format(x3, y3, f(x3, y3))
table4 = "| x0= 1 | y0= -1 | x={} | y={} | f={} |".format(x4, y4, f(x4, y4))
# Imprimir:
print(table1)
print(table2)
print(table3)
print(table4)
z = input()
########################################################################################################################
# 2:
# Ejercicio sobre Regresión Lineal
########################################################################################################################
# EJERCICIO 2.1:
# Implementacion del algoritmo de la pseudoinversa:
# w = Pseduo-Inv(X) * y
def PseudoInverse(X, y):
# Calcular la pseudoinversa de X:
pseudoIvn = np.linalg.pinv(X)
# Clacular w:
w = pseudoIvn.dot(y)
return w
# Error en el conjunto de aprendizaje:
# Simplemente calcula la formula del Ein para unos datos de
# entrada y unos pesos: 1/N * Sum(wt*Xn - yn)**2
def Ein(X, y, w):
out = np.float64(0)
for n in range(X.shape[0]):
out += ((w.transpose()).dot(X[n]) - y[n])**2
return (1/X.shape[0]) * out
# Error en las predicciones del test:
# Calcula el error en los datos predichos con la formula:
# 1/N * Sum(ypn - yn)**2
def Eout(Yorig, Ypredd):
out = np.float64(0)
for n in range(X.shape[0]):
out += (Ypredd[n] - Yorig[n])**2
return (1/Yorig.shape[0]) * out
# Funcion que dado un array de predicciones reales lo etiqueta:
def tag(Y):
Ytag = []
for i in range(Y.shape[0]):
if(Y[i] < 0):
Ytag.append(-1)
else:
Ytag.append(1)
return np.array(Ytag, np.float64)
# Funcion para predecir:
# Contiene un array con todos los elementos a predecir:
# Implementacion de la funcion h(x) = wt*x
# Aplica esa funcion a todos los datos de X y devuelve un
# array con las predicciones
def predict(X, w):
y = [] # Predicciones
for n in range(X.shape[0]):
y.append((w.transpose()).dot(X[n]))
return np.array(y, np.float64)
# Calcula el error de clasificacion:
# Devuelve los errores en las predicciones de la clase -1 y los de la 1
def ErrClass(X, w, y):
Ytemp = predict(X, w)
Y = tag(Ytemp) #Predicciones:
err_1 = 0
err1 = 0
for i in range(Y.shape[0]):
if (Y[i] == 1 and y[i] == -1):
err_1+=1
elif (Y[i] == -1 and y[i] == 1):
err1+=1
return err_1, err1
# Funcion de perdida:
# Es el gradiente, se trata de la derivada de Ein:
# 2/N * Sum(Xnj * (wt*xn -yn))
def lossF(X, y, w):
out = []
pre_grad = X.dot(w) - y
for j in range(w.shape[0]):
val = (X[:,j] * pre_grad).sum()
val *= 2/float(X.shape[0])
out.append(val)
return np.array(out, np.float64)
# Implementacion del gradiente desdendente estocastico:
def SGD(X, y, w, n, gd_func, MAX_ITERS, BATCHSIZE):
for _ in range(MAX_ITERS):
# Barajar la muestra
idx = np.arange(X.shape[0])
np.random.shuffle(idx)
X = X[idx]
y = y[idx]
# Iterar en los batches
for i in range(0, X.shape[0], BATCHSIZE):
w = w - n * gd_func(X[i:i+BATCHSIZE], y[i:i+BATCHSIZE], w)
return w
# Cargar los datos:
X = np.load("data/X_train.npy")
y = np.load("data/y_train.npy")
# Elegir aquellos que utilizaremos, solo 1 y 5:
X = X[(y==1) + (y==5)]
y = y[(y==1) + (y==5)]
# Sustituir la etiqueta 5, por -1
y[y==5] = -1
#Añadir una columna de 1 al principio de X para el termino independiente:
Xorig = X.copy() #Guardamos la matriz sin los unos, ya que sera necesaria para el plot
X = np.c_[np.ones(X.shape[0]), X]
print("Parte 2: Ejercicio 1:")
"""
Entrenar los algoritmos:
Para el gradiente descendente estocastico se ha elegido:
learning rate = 0.01
Numero iteraciones = 100
Tamaño de los batches = 128
"""
w_pi = PseudoInverse(X,y)
w_sgd = SGD(X, y, np.array([0,0,0], np.float64), 0.01, lossF, 100, 128)
print("w segun la pseudoinversa: {}".format(w_pi))
print("w segun el gradiente descendente estocastico: {}".format(w_sgd))
#Calcular el error del ajuste:
print("RESUMEN TRAINING:")
print("Ein para el ajuste de la pseudoinversa: {}".format(Ein(X,y,w_pi)))
print("Ein para el ajuste del gradiente: {}".format(Ein(X,y,w_sgd)))
#Calcular el error de clases:
err_pi = ErrClass(X, w_pi, y)
err_sgd = ErrClass(X, w_sgd, y)
erroresTotales_pi = err_pi[0] + err_pi[1]
erroresTotales_sgd = err_sgd[0] + err_sgd[1]
print("Error de clases para el ajuste de la pseudoinversa:")
print("\tPredicciones de -1 erroneas {}".format(err_pi[0]))
print("\tPredicciones de 1 erroneas {}".format(err_pi[1]))
print("\tTotal de errores: {} de {} muestras".format(erroresTotales_pi, X.shape[0]))
print("Error de clases para el ajuste del gradiente:")
print("\tPredicciones de -1 erroneas {}".format(err_sgd[0]))
print("\tPredicciones de 1 erroneas {}".format(err_sgd[1]))
print("\tTotal de errores: {} de {} muestras".format(erroresTotales_sgd, X.shape[0]))
#Dibujar las graficas de Training
waux = permutateWeight(w_pi)
plot_data(Xorig, y, waux)
waux = permutateWeight(w_sgd)
plot_data(Xorig, y, waux)
# Cargar los datos para el test:
X = np.load("data/X_test.npy")
y = np.load("data/y_test.npy")
# Elegir aquellos que utilizaremos:
X = X[(y==1) + (y==5)]
y = y[(y==1) + (y==5)]
# Sustituir la etiqueta 5, por -1
y[y==5] = -1
#Añadir una columna de 1 al principio de X para el termino independiente:
Xorig = X.copy()
X = np.c_[np.ones(X.shape[0]), X]
# Predecir con los pesos de la pseudoinversa:
yp_pi = predict(X, w_pi)
# Predecir con los pesos del gradiente:
yp_sgd = predict(X, w_sgd)
# Etiquetar los resultados predichos:
yptag_pi = tag(yp_pi)
yptag_sgd = tag(yp_sgd)
# Calcular el Eout:
print("RESUMEN TEST:")
print("Eout para el ajuste de la pseudoinversa: {}".format(Eout(y,yp_pi)))
print("Eout para el ajuste del gradiente: {}".format(Eout(y,yp_sgd)))
#Calcular el error de clases:
err_pi = ErrClass(X, w_pi, y)
err_sgd = ErrClass(X, w_sgd, y)
erroresTotales_pi = err_pi[0] + err_pi[1]
erroresTotales_sgd = err_sgd[0] + err_sgd[1]
print("Error de clases para el ajuste de la pseudoinversa:")
print("\tPredicciones de -1 erroneas {}".format(err_pi[0]))
print("\tPredicciones de 1 erroneas {}".format(err_pi[1]))
print("\tTotal de errores: {} de {} muestras".format(erroresTotales_pi, X.shape[0]))
print("Error de clases para el ajuste del gradiente:")
print("\tPredicciones de -1 erroneas {}".format(err_sgd[0]))
print("\tPredicciones de 1 erroneas {}".format(err_sgd[1]))
print("\tTotal de errores: {} de {} muestras".format(erroresTotales_sgd, X.shape[0]))
#Dibujar las graficas de Test:
waux = permutateWeight(w_pi)
plot_data(Xorig, y, waux)
waux = permutateWeight(w_sgd)
plot_data(Xorig, y, waux)
z = input()
#--------------------------------------------------------------------------
# EJERCICIO 2.2:
print("Parte 2: Ejercicio 2")
# Apartados a) y b):
X = simula_unif(N=1000, dims=2, size=(-1, 1))
y = label_data(X[:, 0], X[:, 1])
# Dibujar los datos:
plt.scatter(X[:, 0], X[:, 1])
plt.title("Mapa de puntos 2D")
plt.xlabel("Primera caracteristica")
plt.ylabel("Segunda caracteristica")
plt.show()
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.title("Mapa de etiquetas")
plt.xlabel("Primera caracteristica")
plt.ylabel("Segunda caracteristica")
plt.show()
# Apartado c)
#Añadir a la muestra la columna de unos inicial:
X = np.c_[np.ones(X.shape[0]), X]
"""
Ajuste utilizando SGD
learning rate = 0.01
Numero iteraciones = 100
Tamaño de los batches = 128
"""
w = SGD(X, y, np.array([0,0,0], np.float64), 0.01, lossF, 100, 128)
print("Estimacion de los pesos: {}".format(w))
print("Ein obtenido: {}".format(Ein(X, y, w)))
z = input()
"""
Apartado d)
"""
# Declarar variables:
MeanEin = [] #Guardara los Ein
MeanEout = [] #Eout
errneg1In = [] #Numero de predicciones de -1 erroneas
errneg1Out = []
err1In = [] #Numero de predicciones de 1 erroneas
err1Out = []
print("Parte 2: Ejercicio 2, apartado d)")
print("Iniciando 1000 experimentos...")
for _ in range(1000):
#Generar muestra:
X = simula_unif(N=1000, dims=2, size=(-1, 1))
y = label_data(X[:, 0], X[:, 1])
#Añadir a la muestra la columna de unos inicial:
X = np.c_[np.ones(X.shape[0]), X]
#Realizar el ajuste:
# nu = 0.01, 30 iteraciones, 128 de batchsize
w = SGD(X, y, np.array([0,0,0], np.float64), 0.01, lossF, 30, 128)
#Calcular los Errores:
MeanEin.append(Ein(X, y, w))
err = ErrClass(X,w,y)
errneg1In.append(err[0])
err1In.append(err[1])
#Generar muestra para test:
X = simula_unif(N=1000, dims=2, size=(-1, 1))
y = label_data(X[:, 0], X[:, 1])
X = np.c_[np.ones(X.shape[0]), X]
#Predecir:
yp = predict(X, w)
#Calcular los errores:
MeanEout.append(Eout(y, yp))
err = ErrClass(X,w,y)
errneg1Out.append(err[0])
err1Out.append(err[1])
#Calcular la media:
aux = np.array(MeanEin, np.float64)
mean = aux.mean()
print("Ein medio: {}".format(mean))
aux = np.array(MeanEout, np.float64)
mean = aux.mean()
print("Eout medio: {}".format(mean))
aux = np.array(errneg1In, np.float64)
mean1 = aux.mean()
print("Media de predicciones erroneas de -1 en el train: {}".format(mean1))
aux = np.array(err1In, np.float64)
mean2 = aux.mean()
print("Media de predicciones erroneas de 1 en el train: {}".format(mean2))
aux = mean1 + mean2
print("Media de errores totales en el train: {}".format(aux))
aux = np.array(errneg1Out, np.float64)
mean1 = aux.mean()
print("Media de predicciones erroneas de -1 en el test: {}".format(mean1))
aux = np.array(err1Out, np.float64)
mean2 = aux.mean()
print("Media de predicciones erroneas de 1 en el test: {}".format(mean2))
aux = mean1 + mean2
print("Media de errores totales en el test: {}".format(aux)) |
5ec5d76a0ae8bab0e0ff2b85778a2fc3856c5e00 | jan1o/Gerador-de-numeros-jogo-do-bicho-teste- | /main.py | 732 | 3.609375 | 4 | from random import *
import sqlite3
import os
from bd import *
def inicio():
op = opcao()
if op == 1:
sorteador()
elif op == 2:
adicionador()
else:
pass
def opcao():
x = int(input("Digite sua escolha: \n 1 - Sortear 10 bichos \n 2 - Adicionar resultados \n 3 - Sair \n"))
return x
def sorteador():
lista = bd.getBichos()
for x in range(10):
print(lista[x])
def adicionador():
os.system("cls")
num = "x"
while num != 's':
num = input("Digite um numero, ou s para sair:\n")
if num != 's':
bd.addPeso(int(num),1)
inicio()
|
39a576878500256697496ac4363103af4400e6b7 | PiperPimientos/CursoBasicoPython | /Listas.py | 2,055 | 4.3125 | 4 | #Vamos a ver las LISTAS en python
# #Como guardar distintos tipos de datos en una sola variable? Es a través de las listas, las listas pertenecen a un conjunto llamado estructuras de datos que son formas que nos brindan los lenguajes de programación para guardar varios valores en una variable, pero con diferente formato.
# 1. Creamos un archivo llamado Listas.py
# 2. Las listas se expresan con la siguiente sintaxis, si por ejemplo queremos una variable llamada números que contenga varios números
# numeros = [ ] igual que como hacíamos los índices de strings, y adentro colocaremos los numeros ordenadamente, separados por comas
# 3. Si imprimimos, nos mostrara esa misma lista entre los corchetes.
# 4. A la vez, podríamos crear listas que contengan distintos tipos de datos, como strings, boleanos, enteros, flotantes, etc..
# objetos = [‘Hola’, 1, True, False, 2.3]
# 5. Para acceder a cada dato, tengo que llamar entre corchetes el numero en el que esta asignado, por ejemplo si en el ejemplo anterior queremos llamar Hola
# objetos = [0]
# 6. Si yo quiero agregar otro objeto a esa lista, puedo hacerlo con un método, recordemos que los métodos nos permiten traer funciones que ya están construidas y, que las listas tienen distintos tipos de métodos
# Para este caso utilizaremos .append() y si por ejemplo queremos agregar otro booleano False, lo hacemos asi
# objetos.append(False)
# 7. Si quiero borrar algo, lo hago con el método .pop() y entre paréntesis especificando el índice del elemento que queremos borrar. Por ejemplo si queremos borrar Hola
# objetos.pop(0)
# 8. Si por ejemplo quiero recorrer toda la lista, lo haremos con el ciclo For, imprimiéndonos un elemento en cada línea de impresión.
# for elemento in objetos:
# print(elemento)
# 9. E incluso podría utilizar los slices en las listas, para poder por ejemplo invertir el orden de la lista.
# objetos[::-1]
# o ir desde el índice X al índice Y por ejemplo
# objetos[1:3]
|
2ed99e39569b5e0da79a0972251cf1725ac0667e | cdvalenzuelas/daf_selector | /main.py | 2,956 | 3.59375 | 4 | import pandas as pd
import numpy as np
from auxiliar_funtions import temp_plus
from response import response
def main():
degree = input("Seleccione °C [1] o °F [2]:" ) #Seleccionar entre grados centígrados o grados farenheit
letter = 'F' if degree == 2 else 'C' #Seleccionar la letra adecuada para el mensaje
temp = float(input(f'Ingrese la temperatura máxima del recinto [{letter}]: ')) # Ingreso de la temperatura
f_tem, c_tem = (None, None)
if letter == 'F':
f_temp = temp
c_temp = round((temp-32)*5/9, 2)
else:
c_temp = temp
f_temp = round(32+9*temp/5, 2)
nfpa_72_requirement = input("El detector debe cumplir con NFPA 72 (es dispositivo de iniciación) [s/n]: ") #Debe ser un dispositivo de iniciación?
min_temp_set = round(temp_plus(temp=temp, degree=degree), 2) #Establecer una temperatura mínima de seteo
df1 = pd.read_csv('vertical.csv') #Leer tabla de temperaturas de seteo
df2 = pd.read_csv('vertical_specifications.csv') #Leer tabla de especificaciones técnicas
df1 = df1.loc[:,:][df1['f_setting'] >= min_temp_set].head(1) #Seleccionado la temperaura de seteo más cercana
if df1['f_setting'].values[0] >= 600: #tener cuiddo con las temperaturas de setero grandes
print('El modelo únicamnte está disponibe como detector normalmente abierto')
if nfpa_72_requirement == 's': #Filtrando los detectores para ver si son dispositivos iniciadores
df2 = df2[df2['contact_operation'] != 'normally closed (open on rise)']
#Seleccionar el material
materials = df2['head_material'].unique() #Mostrando que materiales hay disponibles
heads = df2['head'].unique() #Mostrando que cabeza hay disponibles
#Seleccionar el material
material = input(f'Selecciones el material deseado {materials}: ')
head = input(f'Selecciones el material deseado {heads}: ')
df2 = df2[(df2['head_material']==material)&(df2['head']==head)]
#Preguntar en caso de que haya más de una solución
if df2.shape[0] > 1:
df2.reset_index(drop=True, inplace=True)
print('----------------------------------------------------------------------------------------------------')
print(df2)
print('----------------------------------------------------------------------------------------------------')
index = int(input('Sellecciones una de las opciones permitidas: '))
selected = df2.loc[index,:]
with open('response.txt', 'w', encoding='utf-8') as f: #With es un manejador contextual(maneja el flujo del archivo y evita que se rompa)
f.write(response(temp=df1, model = df2, f_temp=f_temp, c_temp=c_temp, nfpa_72_requirement=nfpa_72_requirement, head=head, material=material))
print('----------------------------------------------------------------------------------------------------')
print('Hecho')
print('----------------------------------------------------------------------------------------------------')
if __name__ == '__main__':
main()
|
0c9124b7aed57705785f1f69799299a837e7d0ff | Zircon-X/BaseRPG | /astar.py | 3,982 | 4.1875 | 4 | #This program is going to be testing an astar algorithm of our own device.
from graphics import *
import random
'''
Width and height are variables used to calculate co-ordinates as well as set the size of the window
gridsize is used to space gridlines as used in drawGrid, win simply sets the co-ordinates of the
window as well as its title. coord is a placeholder variable that will be reset at certain parts
of the program.
'''
Width = 1000
Height = 1000
gridsize = 100
win = GraphWin('Grid', Width, Height) # give title and dimensions
coord = Point(0, 0)
startCoords = Point(0, 0)
goalCoords = Point(0, 0)
obstacleCoords=[]
'''
randomcoords is a function that produces a random co-ordinate when called. It returns the Point
to the calling function at the end of the function.
'''
def randomcoords():
xmax = Width/gridsize #Calculates maximum x co-ordinate by dividing window width by gridsize in pixels
ymax = Height/gridsize #Calculates maximum y co-ordinate by dividing window width by gridsize in pixels
xcomponent = random.randrange(0, xmax, 1) #chooses random x co-ordinate on grid.
ycomponent = random.randrange(0, ymax, 1) #chooses random y co-ordinate on grid.
finalxcoord = xcomponent * gridsize #converts co-ordinate back to pixels
finalycoord = ycomponent * gridsize #converts coordinate back to pixels
randpoint = Point(finalxcoord, finalycoord) #assigns x and y co-ordinate to a Point to be returned to calling function
return randpoint
def drawGrid():
currentGridX = 0 #variable used to hold current grid position on x axis.
currentGridY = 0 #variable used to hold current grid position on y axis.
while currentGridX <= Height: #This while loop draws the vertical lines to represent x co-ordinate
gridlineX = Line(Point(currentGridX, 0), Point(currentGridX, Height))
gridlineX.setOutline("Black")
gridlineX.setFill("Black")
gridlineX.draw(win)
currentGridX += gridsize
while currentGridY <= Width: #This while loop draws the horizontal lines to represent x co-ordinate
gridlineY = Line(Point(0, currentGridY), Point(Width, currentGridY))
gridlineY.setOutline("Black")
gridlineY.setFill("Black")
gridlineY.draw(win)
currentGridY += gridsize
def placeStart(): #This function places the start node at a random location on the grid.
startCoords = randomcoords() #retrieve a random set of co-ordinates
Start = Circle(startCoords, 20) #place a circle of a 20 pixel radius at previously created co-ordinates
Start.setOutline("Green")
Start.setFill("Green")
Start.draw(win) #draw circle of Green outline and fill.
def placeGoal(): #This function places the Goal Node at a random location on the grid.
goalCoords = randomcoords() #retrieves a random set of co-ordinates
Goal = Circle(goalCoords, 20) #places a circle of a 20 pixel radius at previously created co-ordinates.
Goal.setOutline("Blue")
Goal.setFill("Blue")
Goal.draw(win) #draw circle of Blue outline and fill.
def placeObstacles(): #This function places between 1 and 5 obstacles on the grid. A star will mark these as non-traversable.
obstaclesPlaced = 0 #counter used in while loop to keep track of placed obstacles.
numOfObstacles = random.randrange(1, 5, 1) #chooses number of obstacles.
while obstaclesPlaced <= numOfObstacles: #This loop will run until the predetermined number of obstacles is placed.
obstacleCoords = randomcoords() #Obtain random co-ordinates for obstacle.
Obstacle = Circle(obstacleCoords, 20) #Places a circle with a radius of 20 pixels at co-ordinates
Obstacle.setOutline("Red")
Obstacle.setFill("Red")
Obstacle.draw(win) #draw the circle with Red outline and fill.
obstaclesPlaced += 1 #increment the number of obstacles placed.
def main():
drawGrid() #draws Grid
placeStart() #places Start Node
placeGoal() #places Goal Node
placeObstacles() #places Obstacle Nodes
win.getMouse() #wait until click inside window to end. Without this, window closes immediately after last function call.
main()
|
21b71ed7b8f53f4dd9b3a48c1c4200ec07d024f2 | oliveiralecca/cursoemvideo-python3 | /arquivos-py/CursoEmVideo_Python3_AULAS/aula-19c.py | 289 | 4.0625 | 4 | pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
for k in pessoas.keys(): #MOSTRA SÓ O NOME DAS CHAVES
print(k)
print()
for v in pessoas.values():
print(v)
print()
for k, v in pessoas.items(): # SUBSTITUI O "ENUMERATE" DAS TUPLAS E LISTAS
print(f'{k} = {v}')
|
712d2a7928918fc90a0dfe166bb24100da8d3882 | Sundarasettysravanilakshmi/sravani | /pgm5.py | 173 | 3.953125 | 4 | number1=1
number2=2
number3=3
if((number1>number2) and (number1>number3)):
print number1
elif((number2>number1) and (number2>number3)):
print number2
else:
print number3
|
dd7845b62c385a0b76676c643165fd552bab67fa | TatsumakiSombra/IPB2017 | /Tkinter.py | 705 | 3.65625 | 4 | from Tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text="Brown", fg="brown")
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)
text = Text (root)
text.insert( INSERT, "Hello my baby hello my honey hello my rag time gal")
text.tag_config("Hello", fg="purple")
text. pack()
root.mainloop()
#program will run endlessly until ended
|
5b9e9ba657042b3732c729f817b524fc070ea18f | leilalu/algorithm | /剑指offer/第五遍/65.不用加减乘除做加法.py | 659 | 3.90625 | 4 | """
写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
示例:
输入: a = 1, b = 1
输出: 2
提示:
a, b 均可能是负数或 0
结果不会溢出 32 位整数
"""
class Solution:
def add(self, a, b):
while b != 0: # 进位不为0
temp = a ^ b
b = (a & b) << 1
a = temp & 0xFFFFFFFF # 若是负数,则将其变为正数,最终结果要减去4294967296
return a if a >> 31 == 0 else a - 4294967296
if __name__ == '__main__':
a = 1
b = 1
res = Solution().add(a, b)
print(res)
|
4fb98af6016d3c196b75ecb143b76ed00f0eade0 | Germanc/fisicacomputacional2017 | /0321/collatz.py | 364 | 3.640625 | 4 | #!/usr/bin/python3
def funcion(n):
if n%2 == 0:
n = n/2
else:
n = 3*n+1
return n
mayor = 13
contador2 = 0
for i in range(13, 1000000):
print(i)
contador = 0
n = i
while n != 1:
n = funcion(n)
contador = contador + 1
if contador > contador2:
mayor = i
contador2=contador
print(mayor) |
2d2096f165dbea93e864cd8e40841d4f857f586b | Aplex2723/Introduccion-en-Python | /Basicos/LecturaPorTeclado.py | 331 | 3.984375 | 4 | print("Escribe un texto")
valor = input()
print("El texto escrito fue: " + valor)
valor = input("\nEscribe un valor: ")
print("El valor escrito es " + valor)
valor = input("\nIntroduce un numero entero: ")
valor = int(valor)
print(valor + 100)
valor = float(input("Introduce un valor entero o decimal: "))
print(valor) |
2b641d5c158e45f52ea37f0523bfd534aa93b68a | daniel-reich/ubiquitous-fiesta | /gdzS7pXsPexY8j4A3_2.py | 129 | 3.578125 | 4 |
def count_digits(lst, t):
k = {'odd': '13579', 'even': '24680'}
return [sum([str(x).count(i) for i in k[t]]) for x in lst]
|
484c5407e4ccbaccb2ec47c12123a7078653eb84 | bharat-kadchha/tutorials | /python-pandas/Python_Pandas/seriesfunctions/FunctionDrop.py | 484 | 3.921875 | 4 | import pandas as pd
import numpy as np
# Return Series with specified index labels removed
# Remove elements of a Series based on specifying the index labels. When using a
# multi-index, labels on different levels can be removed by specifying the level
s = pd.Series(data=np.arange(1, 4), index=list('ABC'))
print("<---- Series ---->")
print(s)
print("<---- Drop label C ---->")
# you can pass multiple labels here
print(s.drop(labels=['C']))
# after multiindex check documentation
|
bf7f142aa2870a247de77a89b4a6ca077dc4072e | IrinaEvsei/Python | /lab1/lab1task2.py | 1,557 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from pip._vendor.distlib.compat import raw_input
def main():
s = raw_input("Введите последовательность: ")
array = map(int, s.split())
print(array)
sec_smallest = second_smallest(array)
sec_larges = second_largest(array)
print("Второй минимальный элемент: {}".format(sec_smallest))
find_entries(sec_smallest, array)
print("Второй максимальный элемент: {}".format(sec_larges))
find_entries(sec_larges, array)
def second_smallest(array):
min_x = array[0]
sec_min_x = array[1]
for i in range(2, len(array)):
if array[i] < min_x:
sec_min_x = min_x
min_x = array[i]
elif array[i] < sec_min_x:
sec_min_x = array[i]
return sec_min_x
def second_largest(array):
max_x = array[0]
sec_max_x = array[1]
for i in range(2, len(array)):
if array[i] > max_x:
sec_max_x = max_x
max_x = array[i]
elif array[i] > sec_max_x:
sec_max_x = array[i]
return sec_max_x
def find_entries(number, array):
index = -1
count = 0
for i in range(len(array)):
if array[i] == number and index == -1:
index = i + 1
if array[i] == number:
count += 1
print("Количество вхождений числа {} в массив: {}".format(number, count))
print("Индеск элемента {} в массиве: {}".format(number, index))
main() |
f8114ad8cef888c1ebb6ef33622dc2a1f65de3d6 | quoner80/project-euler | /euler0088_wrong_1.py | 2,862 | 4.1875 | 4 | # Product-sum numbers
# Problem 88
#
# A natural number, N, that can be written as the sum and product of a given set of at least two natural numbers, {a1, a2, ... , ak} is called a product-sum number: N = a_1 + a_2 + ... + a_k = a_1 x a_2 x ... x a_k.
#
# For example, 6 = 1 + 2 + 3 = 1 x 2 x 3.
#
# For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.
# k = 2: 4 = 2 x 2 = 2 + 2
# k = 3: 6 = 1 x 2 x 3 = 1 + 2 + 3
# k = 4: 8 = 1 x 1 x 2 x 4 = 1 + 1 + 2 + 4
# k = 5: 8 = 1 x 1 x 2 x 2 x 2 = 1 + 1 + 2 + 2 + 2
# k = 6: 12 = 1 x 1 x 1 x 1 x 2 x 6 = 1 + 1 + 1 + 1 + 2 + 6
#
# Hence for 2 <= k <= 6, the sum of all the minimal product-sum numbers is 4 + 6 + 8 + 12 = 30; note that 8 is only counted once in the sum.
#
# In fact, as the complete set of minimal product-sum numbers for 2 <= k <= 12 is {4, 6, 8, 12, 15, 16}, the sum is 61.
#
# What is the sum of all the minimal product-sum numbers for 2 <= k <= 12000?
import math;
import time;
import sys;
start_time = time.time();
K = 6;
K = 12;
K = 12000;
R = 1 + int(math.log(K, 2));
S_k_r = [None] * (K + 1);
for k in range(K + 1):
S_k_r[k] = [None] * (R + 1);
for r in range(R + 1):
S_k_r[k][r] = [];
def print_execution_time():
print "Execution time = %f seconds." % (time.time() - start_time);
def calculate_S_k_r(k, r):
if len(S_k_r[k][r]) > 0:
return;
if r == 2:
d_max = int(math.sqrt(k - 1));
for d in range(1, d_max + 1):
if (k - 1) % d == 0:
S_k_r[k][r].append([d + 1, ((k - 1) / d) + 1]);
return;
j_max = (k - (3 * r) + 2) / 2;
j_min = (2 ** (r - 2)) - r;
if j_min > j_max:
return;
for j in (j_max, j_min - 1, -1):
for array in S_k_r[j + r][r - 1]:
numerator = k - r - j;
denominator = sum(array) + j;
if numerator % denominator == 0:
new_array = sorted(array + ([1 + (numerator / denominator)]));
if not new_array in S_k_r[k][r]:
S_k_r[k][r].append(new_array);
for k in range(2, K + 1):
r_max = 1 + int(math.log(k, 2));
for r in range(r_max, 1, -1):
calculate_S_k_r(k, r);
v_min = [sys.maxint] * (K + 1);
for k in range(len(S_k_r)):
for r in range(len(S_k_r[k])):
ones = k - r;
for array in S_k_r[k][r]:
v = ones + sum(array);
if v < v_min[k]:
v_min[k] = v;
v_min_unique = set();
for i in range(2, len(v_min)):
v_min_unique.add(v_min[i])
# print i, v_min[i], S_k_r[i];
# print len(v_min_unique);
# print sorted(v_min_unique);
print "sum of minimal product-sum numbers for (2 <= k <= %d) = %d." % (K, sum(v_min_unique));
print_execution_time();
|
fd77f4e2981eed1f0d080bda4e0291264e484039 | vincentleeuwen/python-cooking-with-objects | /13/kitchen.py | 420 | 3.609375 | 4 | from storage import Storage
class Kitchen:
def __init__(self):
self.storage = Storage()
def order(self, dish):
print("KITCHEN: Order received for {0}".format(dish.name))
print("I'm gonna need some:")
for ingredient in dish.ingredients:
print("{0} - {1}".format(ingredient.amount, ingredient.name))
return self.storage.fetch(ingredients=dish.ingredients)
|
0b4c50f1dacf86c5d10462465a452be3e492c375 | saetar/pyEuler | /bib/cybib/cy_amazon_prime.pyx | 6,476 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# JESSE RUBIN - Biblioteca
from bisect import bisect_right, bisect_left
from itertools import count, chain
from math import log
from bib import xrange
from bib.maths import divisors_gen
from bib.decorations import cash_it
def prime_gen(plim=0, kprimes=None):
"""
infinite (within reason) prime number generator
My big modification is the pdiv_dictionary() function that recreats the
dictionary of divisors so that you can continue to generate prime numbers
from a (sorted) list of prime numbers.
BASED ON:
eratosthenes by David Eppstein, UC Irvine, 28 Feb 2002
http://code.activestate.com/recipes/117119/
and
the thread at that url
:param plim: upper limit of numbers to check
:param kprimes: known primes list
:return:
"""
if kprimes is None: kprimes = [2, 3, 5, 7, 11]
def _pdiv_dictionary():
"""
Recreates the prime divisors dictionary used by the generator
"""
div_dict = {}
for pdiv in kprimes: # for each prime
multiple = kprimes[-1] // pdiv * pdiv
if multiple % 2 == 0:
multiple += pdiv
else:
multiple += 2 * pdiv
while multiple in div_dict:
multiple += pdiv * 2
div_dict[multiple] = pdiv
return div_dict
# [1]
# See if the upper bound is greater than the known primes
if 0 < plim <= kprimes[-1]:
for p in kprimes:
if p <= plim:
yield p
return # return bc we are done
# [2]
# Recreate the prime divisibility dictionary using kprimes;
# Set start and yield first 4 primes
divz = _pdiv_dictionary()
start = kprimes[-1] + 2 # max prime + 2 (make sure it is odd)
if start == 13:
yield 2
yield 3
yield 5
yield 7
yield 11
# use count or range depending on if generator is infinite
it = count(start, 2) if plim == 0 else xrange(start, plim, 2)
for num in it:
prime_div = divz.pop(num, None)
if prime_div:
multiple = (2 * prime_div) + num
while multiple in divz:
multiple += (2 * prime_div)
divz[multiple] = prime_div
else:
divz[num * num] = num
yield num
def pfactorization_gen(n):
"""
Args:
n:
Returns:
"""
return (n for n in chain.from_iterable([p] * int(log(n, p))
for p in pfactors_gen(n)))
def pfactors_gen(n):
"""
Returns prime factorization as a list
:param n:
:return:
"""
return (p for p in divisors_gen(n) if is_prime(p))
@cash_it
def is_prime(number):
"""
Returns True if number is prime
>>> is_prime(37)
True
>>> is_prime(100)
False
>>> is_prime(89)
True
"""
if number == 2 or number == 3:
return True
if number < 2 or number % 2 == 0:
return False
if number < 9:
return True
if number % 3 == 0:
return False
r = int(number**0.5)
step = 5
while step <= r:
if number % step == 0:
return False
if number % (step + 2) == 0:
return False
step += 6
return True
class OctopusPrime(list):
"""
OctopusPrime, the 8-leg autobot, here to help you find PRIMES
______OCTOPUS_PRIME ACTIVATE______
░░░░░░░▄▄▄▄█████████████▄▄▄░░░░░░░
████▄▀████████▀▀▀▀▀▀████████▀▄████
▀████░▀██████▄▄░░░░▄▄██████▀░████▀
░███▀▀█▄▄░▀▀██████████▀▀░▄▄█▀▀███░
░████▄▄▄▀▀█▄░░░▀▀▀▀░░░▄█▀▀▄▄▄████░
░░██▄▄░▀▀████░██▄▄██░████▀▀░▄▄██░░
░░░▀████▄▄▄██░██████░██▄▄▄████▀░░░
░░██▄▀▀▀▀▀▀▀▀░░████░░▀▀▀▀▀▀▀▀▄██░░
░░░██░░░░░░░░░░████░░░░░░░░░░██░░░
░░░███▄▄░░░░▄█░████░█▄░░░░▄▄███░░░
░░░███████░███░████░███░███████░░░
░░░███████░███░▀▀▀▀░███░███████░░░
░░░███████░████████████░███████░░░
░░░░▀█████░███░▄▄▄▄░███░█████▀░░░░
░░░░░░░░▀▀░██▀▄████▄░██░▀▀░░░░░░░░
░░░░░░░░░░░░▀░██████░▀░░░░░░░░░░░░
"""
def __init__(self, n=10, savings_n_loads=True, save_path=None):
list.__init__(self, list(prime_gen(plim=n)))
self.max_loaded = self[-1]
def transform(self, n=None):
"""
Args:
n:
"""
n = n if n is not None else self[-1] * 10
self.extend(list(prime_gen(plim=n, kprimes=self)))
def is_prime(self, number):
"""Ask Octopus Prime if a number is prime
Args:
number: the number you are inquiring about
Returns:
Bool: True if the number is prime and False otherwise
"""
if number > self[-1]:
self.transform(number + 1)
if number in self:
return True
else:
return False
def primes_below(self, upper_bound):
"""
Args:
upper_bound:
Returns:
"""
return self.primes_between(1, upper_bound)
def primes_between(self, lower_bound, upper_bound):
"""
Args:
lower_bound:
upper_bound:
Returns:
"""
if upper_bound > self[-1]:
self.transform(upper_bound)
return self[bisect_right(self, lower_bound):bisect_left(
self, upper_bound)]
|
346b461aae98aa2bd607ba70645749b5bea8d512 | RunnerMom/Exercise06 | /wordcount_excr.py | 975 | 3.9375 | 4 | #Exercise 6 in hackbright GIT curriculum
# week two, day one
#write a program that opens a file and counts how many times each space -separated wod
# occurs in that file.
# dictionary with word, counter pairs
# if word in dictionary -> increment counter
# else add word, 1 to dictionary
from sys import argv
import string
script, filename = argv
txt = open(filename)
our_dict = {}
for line in txt: #creates the our_dict from the file txt
#takes in string, lowercases it, then strips new lines and punctuation
for word in line.lower().strip('\n').replace(".", "").replace(",", "").replace("?","").split():
#sets word that doesn't exist to zero
our_dict[word]=our_dict.get(word,0) - 1
# sorts by values, starting with the largest
for key, value in sorted(our_dict.iteritems(), key=lambda (k,v): (v,k)):
#WORKS, except last sort ->>for key, value in sorted(our_dict.iteritems(), key=lambda (k,v): (v,k), reverse=True):
print "%s: %s" % (key, -value)
|
df41014cf9eebbaed88097a308f4681216e9ce7e | ClauMaj/pyHomework | /deDub.py | 223 | 3.953125 | 4 |
myList = [1,1, 2, 3, 4, 5, 3, 5]
deDub = []
for i in range(len(myList)): # i is the index
if myList[i] not in deDub:
deDub.append(myList[i])
# for item not in myList
# deDub.append(item)
print(deDub)
|
a9d6c493d3f7dab4b33dc9253fe094a6f3b21a02 | sacsachin/programing | /zigzag_str.py | 555 | 3.6875 | 4 | # !/usr/bin/python3
"""
https://leetcode.com/problems/zigzag-conversion/
"""
def solve(s, row):
if row == 1:
return s
n = len(s)
rows = ["" for _ in range(min(row, n))]
is_down = False
curr_row = 0
for i in range(n):
rows[curr_row] += s[i]
if curr_row in (0, row-1):
is_down = not is_down
curr_row += 1 if is_down else -1
ans = ""
for each in rows:
ans += each
return ans
if __name__ == "__main__":
s = input()
row = int(input())
print(solve(s, row))
|
62bc6c11e32ce625ff4bba9b163b0011c235f344 | mingjingz/ga-examples | /chromosome.py | 3,029 | 3.609375 | 4 | import random
import string
class Population(object):
def __init__(self, target, size, mutate_prob, mate_percent):
self.members = [Chromosome(len(target)) for _ in range(size)]
self.target = target
self.size = size
self.i_generation = 0
self.mutate_prob = mutate_prob
self.mate_percent = mate_percent # The percent of population that has the mating privilege
self.calc_all_cost()
self.sort()
def sort(self):
self.members.sort(key=lambda x: x.cost)
def calc_all_cost(self):
for m in self.members:
m.calcCost(self.target)
def next_generation(self):
if self.i_generation > 0:
self.sort()
# First, mate the top 4% population
n_mates = int(self.size * self.mate_percent / 2)
# Kill the unfit ones
self.members = self.members[:-n_mates*2]
for i in range(n_mates):
sp1 = self.members[i*2]
sp2 = self.members[i*2+1]
child1, child2 = sp1.mate(sp2, self.mutate_prob)
self.members.append(child1)
self.members.append(child2)
self.calc_all_cost()
self.sort()
self.i_generation += 1
def display(self):
print("Iteration {0}".format(self.i_generation))
for i in range(6):
print("{0} -> {1}".format(self.members[i].genes, self.members[i].cost))
print()
def is_solved(self):
return self.members[0].genes == self.target
class Chromosome(object):
def __init__(self, length, genes=''):
if genes:
self.genes = genes
else:
self.genes = ''.join(random.choice(string.printable[0:-5]) for _ in range(length))
self.cost = float("inf")
def calcCost(self, target):
total = 0
for gene, target_gene in zip(self.genes, target):
total += (ord(target_gene) - ord(gene)) ** 2
total += abs(len(target) - len(self.genes)) * 255 # If the chromosomes are of different sizes
total /= min(len(target), len(self.genes))
self.cost = total
return total
def mutate(self, mutate_prob):
self.genes = ''.join([
g if random.random() > mutate_prob
else random.choice(string.printable[0:-5])
for g in self.genes
])
def mate(self, spouse, mutate_prob):
pivot = 3; #min(len(self.genes), len(spouse.genes)) // 2
child1 = Chromosome(0, genes=self.genes[0:pivot] + spouse.genes[pivot:])
child1.mutate(mutate_prob)
child2 = Chromosome(0, genes=spouse.genes[0:pivot] + self.genes[pivot:])
child2.mutate(mutate_prob)
return child1, child2
if __name__ == '__main__':
c = Chromosome(13)
d = Chromosome(13)
c1, c2 = c.mate(d, 0)
print("c=" + c.genes, "d="+d.genes)
print("c1=" + c1.genes, "c2="+c2.genes)
print("c.cost={}".format(c.calcCost("Hello, World!")))
|
2437de8c85f5bdf02101fa0fd682c9d4153f244d | mtan22/CPE202 | /labs/lab8/sep_chain_ht.py | 2,782 | 3.75 | 4 | from typing import Any, Tuple, List
class MyHashTable:
def __init__(self, table_size: int = 11):
self.table_size = table_size
self.hash_table: List = [[] for _ in range(table_size)] # List of lists implementation
self.num_items = 0
self.num_collisions = 0
def insert(self, key: int, value: Any) -> None:
"""Takes a key, and an item. Keys are valid Python non-negative integers.
If key is negative, raise ValueError exception
The function will insert the key-item pair into the hash table based on the
hash value of the key mod the table size (hash_value = key % table_size)"""
if key < 0:
raise ValueError
hash_value = key % self.table_size
bool = False
vals = self.hash_table[hash_value]
size = self.table_size
lista: List = []
for i in vals:
if i[0] == key:
bool = True
if bool is False:
tuple = (key, value)
vals.append(tuple)
if 1 < len(self.hash_table[hash_value]):
self.num_collisions += 1
self.num_items += 1
def get_item(self, key: int) -> Any:
"""Takes a key and returns the item from the hash table associated with the key.
If no key-item pair is associated with the key, the function raises a LookupError exception."""
hash_value = key % self.table_size
vals = self.hash_table[hash_value]
if self.hash_table[hash_value] is None or not self.hash_table[hash_value]:
raise LookupError
for i in vals:
if i[0] == key:
return i[1]
raise LookupError
def remove(self, key: int) -> Tuple[int, Any]:
"""Takes a key, removes the key-item pair from the hash table and returns the key-item pair.
If no key-item pair is associated with the key, the function raises a LookupError exception.
(The key-item pair should be returned as a tuple)"""
hash_value = key % self.table_size
vals = self.hash_table[hash_value]
for i in vals:
if i[0] == key:
val = i
vals.remove(i)
self.num_items -= 1
return val
else:
raise LookupError
def load_factor(self) -> float:
"""Returns the current load factor of the hash table"""
return self.num_items / self.table_size
def size(self) -> int:
"""Returns the number of key-item pairs currently stored in the hash table"""
return self.num_items
def collisions(self) -> int:
"""Returns the number of collisions that have occurred during insertions into the hash table"""
return self.num_collisions
|
dff2ca8c5efa8e8f9fe4a13e3738bbb08a8331f1 | JoeOlafs/FCCPyInt | /Lists.py | 1,550 | 4.125 | 4 | #Lists: ordered, mutable, allows duplicate elements
mylist = ["banana", "cherry", "apple"]
print(mylist)
mylist2 = [5, 4, 3, 2, 1, 0]
print(mylist2)
print(mylist[2])
print(mylist[-1])
# Iterate through list
for i in mylist:
print(i)
if 'orange' in mylist:
print("yes")
else:
print('no')
# Add to end of list
mylist.append("lemon")
print(mylist)
print(len(mylist))
# Add to a specific location in list
mylist.insert(0, "orange")
print(mylist)
# Remove last item
item = mylist.pop()
print(item)
# Remove specific item from list
mylist.remove("cherry")
print(mylist)
# Reverse list
mylist.reverse()
print(mylist)
# Remove all items
mylist.clear()
print(mylist)
# Sorting lists
sorted_list = sorted(mylist2)
print(sorted_list)
print(mylist2)
mylist2.sort()
print(mylist2)
# List with same item multiple times
mylist = [0] * 5
print(mylist)
# Concatination
new_list = mylist + mylist2
print(new_list)
# Splicing
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = mylist[1:5]
b = mylist[:5]
c = mylist[4:]
d = mylist[1::2]
rev = mylist[::-1]
print(a)
print(b)
print(c)
print(d)
print(rev)
# Copy list
list_org = ["banana", "cherry", "apple"]
# This method refers to the original place in memory so any changes made to the copy will be applied to the original
#list_cpy = list_org
list_cpy = list(list_org)
list_cpy2 = list_org[:]
print(list_cpy)
list_cpy.append("Lemon")
print(list_org)
print(list_cpy)
print(list_cpy2)
# Create new list with functoin applied to each item
a = [1, 2, 3, 4, 5, 6]
b = [i*i for i in a]
print(a)
print(b) |
e301564b994712f9af17f26ec094ef0ddff48cfd | rossoskull/python-beginner | /lcm.py | 289 | 3.90625 | 4 | a = int(input("Enter a number : "))
b = int(input("Enter another number : "))
if a < b:
c = a
a = b
b = c
lcm = a
cond = 1
while cond == 1:
if lcm % a == 0 and lcm % b == 0:
break
lcm += 1
print("The L.C.M of %d and %d is %d." % (a, b, lcm))
|
4375c4549479a09c3f57ad3c5ec960d2b4262429 | NickmBall1/Python | /textsamplea06.py | 596 | 4.40625 | 4 | '''Use nested for loops to print triangles with ***'''
#nested for loops
n = 1
m = 10
for x in range(n, m+1):
for y in range(1, x):
print('*', end = ' ')
print('\n')
'''How to use for loop with list'''
sum = 0
numbers = [2, 3, 12, 34, 19]
for x in numbers:
if x%3 == 0:
print(x)
'''How to check for vowels in a string'''
count = 0
text = "This is to count the number of vowels"
for x in text:
if x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u':
count = count + 1
print(count)
|
4825dafe05e00415768d559bb19eaadf006e757d | jonasc/constant-workspace-algos | /geometry/trapezoid.py | 8,220 | 3.984375 | 4 | """Defines a trapezoid class with various helper classes and methods."""
from typing import Any, List, Optional, Tuple, Union
from .polygon_helper import Edge, PolygonPoint
class IntersectionPoint(PolygonPoint):
"""A polygon point with additional information about the edge it lies on."""
def __init__(self, *args, **kwargs):
"""Initialize a new intersection point."""
self.edge = None
if 'edge' in kwargs:
assert isinstance(kwargs['edge'], int) or kwargs['edge'] is None
self.edge = kwargs['edge']
del kwargs['edge']
super(IntersectionPoint, self).__init__(*args, **kwargs)
def __repr__(self) -> str:
"""Return nice string representation for console."""
return '{class_}({x!r}, {y!r}, {index!r}, edge={edge!r})'.format(class_=self.__class__.__name__, x=self.x,
y=self.y, index=self.index, edge=self.edge)
class Trapezoid(object):
"""Defines a trapezoid in R^2."""
def __init__(self, x_left: Union[int, float], x_right: Union[int, float], y_left1: Union[int, float],
y_right1: Union[int, float], y_left2: Union[int, float], y_right2: Union[int, float],
top_edge_ix: int, bot_edge_ix: int,
top_left_ix: int = None, bot_left_ix: int = None, top_right_ix: int = None, bot_right_ix: int = None):
"""Initialize a new trapezoid.
This is a trapezoid with the left and right edges being parallel to the
y-axis.
Additionally indices of the points and top and bottom edges
corresponding to the vertices and edges of the polygon are stored.
"""
# TODO: Add assertions about parameters
# x-value of the left vertical boundary
self.x_left = x_left
# x-value of the right vertical boundary
self.x_right = x_right
# y-value of the top left vertex
self.y_left1 = y_left1
# y-value of the top right vertex
self.y_right1 = y_right1
# y-value of the bottom left vertex
self.y_left2 = y_left2
# y-value of the bottom right vertex
self.y_right2 = y_right2
# edge index of the top edge
self.top_edge_ix = top_edge_ix
# edge index of the bottom edge
self.bot_edge_ix = bot_edge_ix
self.top_left_ix = top_left_ix
self.bot_left_ix = bot_left_ix
self.top_right_ix = top_right_ix
self.bot_right_ix = bot_right_ix
def as_polygon_tuple(self) -> List[Tuple[Union[int, float], Union[int, float]]]:
"""Return the four vertex points as a list of (x,y)-tuples."""
return [
(self.x_left, self.y_left1),
(self.x_left, self.y_left2),
(self.x_right, self.y_right2),
(self.x_right, self.y_right1),
]
def is_triangle(self) -> bool:
"""Check whether the trapezoid actually is a triangle."""
return self.y_left1 == self.y_left2 or self.y_right1 == self.y_right2
def is_right_of(self, t: 'Trapezoid') -> bool:
"""Return true if from t we go to the right to reach this trapezoid."""
assert isinstance(t, Trapezoid)
if t.top_edge_ix > t.bot_edge_ix:
return (
t.top_edge_ix >= self.top_edge_ix >= t.bot_edge_ix and
t.top_edge_ix >= self.bot_edge_ix >= t.bot_edge_ix
)
else:
return not (
t.top_edge_ix < self.top_edge_ix < t.bot_edge_ix or
t.top_edge_ix < self.bot_edge_ix < t.bot_edge_ix
)
def is_left_of(self, t: 'Trapezoid') -> bool:
"""Return true if from t we go to the left to reach this trapezoid."""
assert isinstance(t, Trapezoid)
if t.top_edge_ix < t.bot_edge_ix:
return (
t.top_edge_ix <= self.top_edge_ix <= t.bot_edge_ix and
t.top_edge_ix <= self.bot_edge_ix <= t.bot_edge_ix
)
else:
return not (
t.top_edge_ix > self.top_edge_ix > t.bot_edge_ix or
t.top_edge_ix > self.bot_edge_ix > t.bot_edge_ix
)
def intersection(self, trapezoid: 'Trapezoid') -> Optional[Edge]:
"""Return the edge between two trapezoids if it exists, else None."""
assert isinstance(trapezoid, Trapezoid)
if self.x_right == trapezoid.x_left:
first_edge = None
if trapezoid.y_left1 < self.y_right1:
first_index = trapezoid.top_left_ix
if first_index is None:
first_edge = trapezoid.top_edge_ix
else:
first_index = self.top_right_ix
if first_index is None:
first_edge = self.top_edge_ix
second_edge = None
if trapezoid.y_left2 > self.y_right2:
second_index = trapezoid.bot_left_ix
if second_index is None:
second_edge = trapezoid.bot_edge_ix
else:
second_index = self.bot_right_ix
if second_index is None:
second_edge = self.bot_edge_ix
first = IntersectionPoint(
self.x_right,
min(self.y_right1, trapezoid.y_left1),
first_index,
edge=first_edge
)
second = IntersectionPoint(
self.x_right,
max(self.y_right2, trapezoid.y_left2),
second_index,
edge=second_edge
)
return Edge(first, second)
if self.x_left == trapezoid.x_right:
first_edge = None
if trapezoid.y_right1 < self.y_left1:
first_index = trapezoid.top_right_ix
if first_index is None:
first_edge = trapezoid.top_edge_ix
else:
first_index = self.top_left_ix
if first_index is None:
first_edge = self.top_edge_ix
second_edge = None
if trapezoid.y_right2 > self.y_left2:
second_index = trapezoid.bot_right_ix
if second_index is None:
second_edge = trapezoid.bot_edge_ix
else:
second_index = self.bot_left_ix
if second_index is None:
second_edge = self.bot_edge_ix
first = IntersectionPoint(
self.x_left,
min(self.y_left1, trapezoid.y_right1),
first_index,
edge=first_edge
)
second = IntersectionPoint(
self.x_left,
max(self.y_left2, trapezoid.y_right2),
second_index,
edge=second_edge
)
return Edge(first, second)
return None
def __repr__(self) -> str:
"""Return nice string representation for console."""
return (
'{class_}(x_left={x_left!r}, y_left1={y_left1!r}, y_left2={y_left2!r}, x_right={x_right!r}, '
'y_right1={y_right1!r}, y_right2={y_right2!r}, top_edge_ix={top_edge_ix!r}, bot_edge_ix={bot_edge_ix!r}, '
'top_left_ix={top_left_ix!r}, bot_left_ix={bot_left_ix!r}, bot_right_ix={bot_right_ix!r}, '
'top_right_ix={top_right_ix!r})').format(
class_=self.__class__.__name__, x_left=self.x_left, y_left1=self.y_left1, y_left2=self.y_left2,
x_right=self.x_right, y_right1=self.y_right1, y_right2=self.y_right2, top_edge_ix=self.top_edge_ix,
bot_edge_ix=self.bot_edge_ix, top_left_ix=self.top_left_ix, bot_left_ix=self.bot_left_ix,
bot_right_ix=self.bot_right_ix, top_right_ix=self.top_right_ix)
def __eq__(self, t: Any) -> bool:
"""Check equality of two trapezoids."""
return (
isinstance(t, Trapezoid) and
self.x_left == t.x_left and self.x_right == t.x_right and
self.y_left1 == t.y_left1 and self.y_left2 == t.y_left2 and
self.y_right1 == t.y_right1 and self.y_right2 == t.y_right2
)
|
9ede796a964562f7fc81d26bd3f2a4af3a5f4e7d | Dhrumil1808/deep-learning | /Assignment1/code/error.py | 161 | 4.0625 | 4 | a=100
b=100
if( a < b):
print "a is less than b"
else:
print " a is greater than b" #logical error as it prints "a is greater than b" even though a=b |
5a4df054cb3a2edf3ef633a19680debfe438b536 | KARTHIK-KG/Data-Structures-Lab | /Virtual LMS/Exp 8.py | 214 | 4.28125 | 4 | # Write a Python program to check whether the given character is vowel or consonant.
ch=input()
if(ch in('a','A','e','E','i','I','o','O','u','U')):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant") |
9a0e2ae9603588e31e4a52c42a68efab8dfe219e | Chekoo/Core-Python-Programming | /8/8-7.py | 449 | 3.890625 | 4 | def getfactors(num):
list1 = [1]
for i in range(1, num + 1):
if num % 2 == 0:
list1.append(2)
num = num / 2
else:
list1.append(num)
break
return list1
def isperfect(num):
if sum(getfactors(num)) == num:
return 1
else:
return 0
if __name__ == '__main__':
while True:
num = int(raw_input('Enter a number: '))
print isperfect(num) |
6da6f9e94b8af2b6a4f9f92440886ef799c8ad65 | sglyon/pytools | /matstat/chi_square.py | 7,778 | 3.6875 | 4 | """
Created July 19, 2012
Author: Spencer Lyon
"""
from __future__ import division
import numpy as np
from math import sqrt
from scipy.special import gamma, chdtr, chdtri
import matplotlib.pyplot as plt
class Chi_square:
def __init__(self, k=2):
"""
Initializes an object of chi-squared distribution type. We instantiate
the object as well as some common statistics about it. This will make
sure k has acceptable values and raise a ValueError if it doesn't.
Methods
-------
pdf(x): pdf evaluated at each entry in x.
cdf(x): cdf evaluated at each entry in x.
rand_draw(n): n random draws from the distribution
sf(x): survival function (1 - CDF) at x
ppf(x): percent point function (inverse of cdf)
plot_pdf(low, high): plots pdf with x going from low to high.
plot_cdf(low, high): plots cdf with x going from low to high.
Notes
-----
This class is dependent on matplotlib, scipy, math, and numpy.
References
----------
[1]: www.http://mathworld.wolfram.com/Chi-SquaredDistribution.html
[2]: www.http://en.wikipedia.org/wiki/Chi-squared_distribution
[3]: scipy.stats.distributions
"""
if k < 0 or type(k) != int:
raise ValueError('k must be a positive iteger')
self.k = k
self.support = '[0, inf)'
self.mean = k
self.median = k * (1 - 2 / (9 * k)) ** 3
self.mode = max(k - 2, 0)
self.variance = 2 * k
self.skewness = sqrt(8. / k)
self.ex_kurtosis = 12. / k
def pdf(self, x):
"""
Computes the probability density function of the distribution
at the point x. The pdf is defined as follows:
f(x|k) =(1 / (2**(k/2) * gamma(k/2))) * x**(k / 2 - 1) * exp(-x/2)
Parameters
----------
x: array, dtype=float, shape=(m x n)
The value(s) at which the user would like the pdf evaluated.
If an array is passed in, the pdf is evaluated at every point
in the array and an array of the same size is returned.
Returns
-------
pdf: array, dtype=float, shape=(m x n)
The pdf at each point in x.
"""
if (x<0).any():
raise ValueError('at least one value of x is not in the support of \
the dist. X must be non-negative.')
k = self.k
pdf = (1. / (2 ** (k / 2) * gamma(k / 2.))) * \
x ** (k / 2. - 1.) * np.exp(- x / 2.)
return pdf
def cdf(self, x):
"""
Computes the cumulative distribution function of the
distribution at the point(s) x. The cdf is defined as follows:
F(x|k) = gammainc(k/2, x/2) / gamma(k/2)
Where gammainc and gamma are the incomplete gamma and gamma functions,
respectively.
Parameters
----------
x: array, dtype=float, shape=(m x n)
The value(s) at which the user would like the cdf evaluated.
If an array is passed in, the cdf is evaluated at every point
in the array and an array of the same size is returned.
Returns
-------
cdf: array, dtype=float, shape=(m x n)
The cdf at each point in x.
"""
cdf = chdtr(self.k, x)
return cdf
def rand_draw(self, n):
"""
Return a random draw from the distribution
Parameters
----------
n: number, int
The number of random draws that you would like.
Returns
-------
draw: array, dtype=float, shape=(n x 1)
The n x 1 random draws from the distribution.
"""
draw = np.random.chisquare(self.k, n)
return draw
def sf(self, x):
"""
Computes the survival function of the normal distribution at the
point(s) x. It is simply (1 - CDF(x))
Parameters
----------
x: array, dtype=float, shape=(m x n)
The value(s) at which the user would like the sf evaluated.
If an array is passed in, the sf is evaluated at every point
in the array and an array of the same size is returned.
Returns
-------
sf: array, dtype=float, shape=(m x n)
The sf at each point in x.
"""
vals = self.cdf(x)
sf = 1 - vals
return sf
def ppf(self, x):
"""
Computes the percent point function of the distribution at the point(s)
x. It is defined as the inverse of the CDF. y = ppf(x) can be
interpreted as the argument y for which the value of the cdf(x) is equal
to y. Essentially that means the random varable y is the place on the
distribution the CDF evaluates to x.
Parameters
----------
x: array, dtype=float, shape=(m x n), bounds=(0,1)
The value(s) at which the user would like the ppf evaluated.
If an array is passed in, the ppf is evaluated at every point
in the array and an array of the same size is returned.
Returns
-------
ppf: array, dtype=float, shape=(m x n)
The ppf at each point in x.
"""
if (x <=0).any() or (x >=1).any():
raise ValueError('all values in x must be between 0 and 1, \
exclusive')
ppf = chdtri(self.k, 1. - x)
return ppf
def plot_pdf(self, low, high):
"""
Plots the pdf of the distribution from low to high.
Parameters
----------
low: number, float
The lower bound you want to see on the x-axis in the plot.
high: number, float
The upper bound you want to see on the x-axis in the plot.
Returns
-------
None
Notes
-----
While this has no return values, the plot is generated and shown.
"""
x = np.linspace(low, high, 300)
plt.figure()
plt.plot(x, self.pdf(x))
plt.title(r'$\chi^2$ (%.1f): PDF from %.2f to %.2f' %(self.k, low, high))
plt.show()
return
def plot_cdf(self, low, high):
"""
Plots the cdf of the distribution from low to high.
Parameters
----------
low: number, float
The lower bound you want to see on the x-axis in the plot.
high: number, float
The upper bound you want to see on the x-axis in the plot.
Returns
-------
None
Notes
-----
While this has no return values, the plot is generated and shown.
"""
x = np.linspace(low, high, 400)
plt.figure()
plt.plot(x, self.cdf(x))
plt.title(r'$\chi^2$ (%.1f): PDF from %.2f to %.2f' %(self.k, low, high))
plt.show()
return
if __name__ == '__main__':
x = np.array([1.2, 1.5, 2.1, 5.4])
x2 = np.array([.1, .3, .5, .9])
k = 4
chi2 = Chi_square(k)
print 'support = ', chi2.support
print 'mean = ', chi2.mean
print 'median= ', chi2.median
print 'mode = ', chi2.mode
print 'variance = ', chi2.variance
print 'skewness = ', chi2.skewness
print 'Excess kurtosis = ', chi2.ex_kurtosis
print 'x = ', x
print 'pdf at x = ', chi2.pdf(x)
print 'cdf at x = ', chi2.cdf(x)
print 'ppf at x = ', chi2.ppf(x2)
print 'sf at x = ', chi2.sf(x)
print '6 random_draws ', chi2.rand_draw(6)
print 'Plot of pdf from %.2f to %.2f ' % (0, 10)
print 'Plot of cdf from %.2f to %.2f ' % (0, 10)
chi2.plot_pdf(0, 10)
chi2.plot_cdf(0, 10)
|
58eea405f6f87429565aaf6bb19662549f151000 | mccarvik/cookbook_python | /2_strings_and_text/2_17_handling_html_xml.py | 549 | 3.53125 | 4 | import html
from html.parser import HTMLParser
from xml.sax.saxutils import unescape
s = 'Elements are written as "<tag>text</tag>".'
print(s)
# replaces special characters such as < and >
print(html.escape(s))
# same but without quotes
print(html.escape(s, quote=False))
s = 'Spicy Jalapeño'
# emit texts as ascii
print(s.encode('ascii', errors='xmlcharrefreplace'))
s = 'Spicy "Jalapeño".'
p = HTMLParser()
# converts html into text
print(p.unescape(s))
# converts xml into text
t = 'The prompt is >>>'
print(unescape(t)) |
b1c5f03253572c3d9a55029de48d5723c1aa9692 | danielicapui/lua | /src/main.py | 621 | 3.625 | 4 | from Calc import Calc
import script
def main(c):
op=int(input("Digite 1 para somar:\nDigite 2 para subtrair:\nDigite 3 para multiplique:\nDigite 4 para dividir:\n"))
if op==1:
print(c.some())
elif op==2:
print(c.subtraia())
elif op==3:
print(c.multiplique())
elif op==4:
print(c.divida())
else:
print("Erro")
return -1
if __name__=="__main__":
script.say_hi("Mundo!")
print("Calculadora utilizando Lua e python")
a=float(input("Digite 1 número:"))
b=float(input("Digite 1 número:"))
c=Calc(a,b)
main(c) |
3d8f8e0f7a2d7742c139650c0e567f439dcc44d6 | Kanika-Mittal15/RecursionProblems | /fibonacci number.py | 165 | 4.09375 | 4 | def fibonacci(n):
#base case
if n==0 or n==1:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
n = int(input())
print(fibonacci(n)) |
31bfb72fe0fe4fa95bf566d0fa8483fe610f487f | iron-bun/project-euler | /problem_022.py | 862 | 4.03125 | 4 | #!/usr/bin/env python3
#Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
#For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
#What is the total of all the name scores in the file?
def score_name(name):
return sum([ord(l)-64 for l in name])
with open('data/p022_names.txt') as f:
lines = f.readline().split(",")
lines = sorted(lines)
ans = 0
for line_no, line in enumerate(lines):
ans += score_name(line.strip("\"")) * (line_no + 1)
print(ans)
|
1b47674d1348feb419352925577cf3686e586a04 | Muniah-96/PA-WiT-Python-S21 | /week_1/age_given_year_example.py | 344 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 22:06:37 2020
@author: aliciachen
"""
# code that gives your age, given year you were born!
birth_year = int(input("What year were you born?"))
current_year = int(input("What year is it right now?"))
age = current_year - birth_year
print("Your age is: " + str(age))
|
3d57715dfdf2bc4bd1e7f0a7dbf9f8b2cc9a7eb1 | jon-tow/CARP | /eval/check_contrastive_scores.py | 456 | 3.515625 | 4 | from testing_util import compute_logit
while True:
passages = []
reviews = []
print("Write -1 to specify you're finished")
print("PASSAGES:")
while True:
passage = input()
if passage == "-1": break
passages.append(passage)
print("REVIEWS:")
while True:
review = input()
if review == "-1": break
reviews.append(review)
print("SCORES:")
compute_logit(passages, reviews)
|
2b5359a3ab53970b4f0b4c4571bbc5edd25cfebe | Rockson-c/smartninja | /homework_6_1.py | 1,874 | 3.765625 | 4 | # Kako v eno od definiranih funkcij vstavit slovarje iz drugih definiranih funkcij in jih zdruziti?
# Kaj spremeniti, da playerje dodane preko 'input' doda v file.txt/class (append) in ne zbrise prejsnjega vnosa?
# Ali je kakšen line za ustavit program - quit?
from HW61funkc import football_p_enter
from HW61funkc import basketball_p_enter
class Player():
def __init__(self, first_name, last_name, height_cm, weight_kg):
self.first_name = first_name
self.last_name = last_name
self.height_cm = height_cm
self.weight_kg = weight_kg
def weight_to_lbs(self):
pounds = self.weight_kg * 2.20462262
return pounds
class BasketballPlayer(Player):
def __init__(self, first_name, last_name, height_cm, weight_kg, points, rebounds, assists):
super().__init__(first_name=first_name, last_name=last_name,
height_cm=height_cm, weight_kg=weight_kg) # dostopam do razreda katerega dedujem
self.points = points
self.rebounds = rebounds
self.assists = assists
class FootballPlayer(Player):
def __init__(self, first_name, last_name, height_cm, weight_kg, goals, yellow_cards, red_cards):
super().__init__(first_name=first_name, last_name=last_name, height_cm=height_cm, weight_kg=weight_kg)
self.goals = goals
self.yellow_cards = yellow_cards
self.red_cards = red_cards
while True:
while True:
borf = input("Enter players data. A) footbal B) basketball >").lower()
if borf == "a":
football_p_enter(FootballPlayer)
elif borf == "b":
basketball_p_enter(BasketballPlayer)
else:
break
quit = input("ENTER new player or QUIT? ").upper()
if quit == "Q":
break
elif quit == "QUIT":
break |
d78e243375dbc4ec3d8e56a144ae3fa07fa09d3a | midas87/myFirstOdd_Even | /Even_Odd.py | 324 | 3.84375 | 4 | import random
name = input('What is your name: ')
print('Welcome', name,', Please pick a number between 1 to 1000')
print('What number are you thinking')
num = int(input())
ran = random.randint(1,1000)
print(ran)
if ran % num == 0:
print('This is an even number')
else:
print('That is an Odd number')
|
3de0634efdff135eac083be42c6e7a9690da398c | xy008areshsu/Leetcode_complete | /python_version/pascal_triangle_2.py | 813 | 3.984375 | 4 | """
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
"""
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
rowIndex += 1
if rowIndex == 0:
return []
if rowIndex == 1:
return [1]
if rowIndex == 2:
return [1, 1]
last_level = [1, 1]
for i in range(2, rowIndex):
this_level = [1]
for j in range(1, i ):
this_level.append(last_level[j - 1] + last_level[j])
this_level.append(1)
last_level = this_level
return this_level
if __name__ == '__main__':
sol = Solution()
print(sol.getRow(3))
|
dfb4e7059e0e193408cb80c6a3ef40e23ab1e454 | gregorykremler/udacity-cs253 | /lib/utils.py | 2,624 | 3.796875 | 4 | """
Aplication utility functions.
"""
import re
import hmac
import random
import string
import hashlib
# Validation utilities for Birthday and ROT13 forms
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
abbrev_to_month = {m[:3].lower(): m for m in months}
def valid_month(month):
"""Return month if valid Gregorian calendar month."""
if month:
short_month = month[:3].lower()
return abbrev_to_month.get(short_month)
def valid_day(day):
"""Return day if in range 1-31 inclusive."""
if day and day.isdigit():
day = int(day)
if day > 0 and day <= 31:
return day
def valid_year(year):
"""Return year if in range 1900-2020 inclusive."""
if year and year.isdigit():
year = int(year)
if year >= 1900 and year < 2020:
return year
def rot13(text):
"""Encode text with ROT13 cipher."""
rot13 = ''
if text:
s = str(text)
rot13 = s.encode('rot13')
return rot13
# Validation utilities for user signup
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
def valid_username(username):
"""Return True if username match."""
return username and USER_RE.match(username)
PASS_RE = re.compile(r"^.{3,20}$")
def valid_password(password):
"""Return True if password match."""
return password and PASS_RE.match(password)
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
def valid_email(email):
"""Return True if either no email or email match."""
return not email or EMAIL_RE.match(email)
# Cookie hashing utitlities
SECRET = 'imsosecret'
def hash_str(s):
"""Return HMAC bitstring of s."""
return hmac.new(SECRET, s).hexdigest()
def make_secure_val(val):
"""Return val|hash of val."""
return "%s|%s" % (val, hash_str(val))
def check_secure_val(secure_val):
"""Return val if val of secure_val matches hash(val)."""
val = secure_val.split('|')[0]
if secure_val == make_secure_val(val):
return val
# Datastore hashing utilties
def make_salt(length=5):
"""Return randomly generated salt str."""
return ''.join(random.choice(string.letters) for x in xrange(length))
def make_pw_hash(name, pw, salt=None):
"""Return hash,salt of name, pw, salt."""
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return "%s,%s" % (h, salt)
def valid_pw_hash(name, pw, h):
"""Return True if h matches hash(name, pw, salt)."""
salt = h.split(',')[1]
return h == make_pw_hash(name, pw, salt)
|
cfd7692e4a9d358c38dba9d285a7a1a4a0a48c9c | BlendaBonnier/foundations-sample-website | /color_check/controllers/get_color_code.py | 1,060 | 3.859375 | 4 | # This file should contain a function called get_color_code().
# This function should take one argument, a color name,
# and it should return one argument, the hex code of the color,
# if that color exists in our data. If it does not exist, you should
# raise and handle an error that helps both you as a developer,
# for example by logging the request and error, and the user,
# letting them know that their color doesn't exist.
import json
def get_color_code(color_name):
#reading the data from the file and loop through and comapre keys with color_name
try:
color_name = color_name.lower().strip()
except AttributeError:
pass
try:
with open('color_check/data/css-color-names.json') as f:
data = json.load(f)
for key in data.keys():
if color_name == key:
hex = data[key]
return hex
break
color_hex_code = None
return color_hex_code
except FileNotFoundError:
return "File can not be found"
|
cafb6027ddc2a2d0f70874e10a72ee11b78317fa | GeoffNN/interview-prep | /row-col-to-zero.py | 868 | 3.984375 | 4 | import numpy as np
def row_col_to_zeros(in_matrix):
"""
Sets row and col to zero if contains a zero
"""
row_nb, col_nb = in_matrix.shape
flagged_rows = {}
flagged_cols = {}
# Find rows and cols that contain zeros
for row in range(row_nb):
for col in range(col_nb):
if(in_matrix[row, col] == 0):
flagged_rows[row] = True
flagged_cols[col] = True
# fill new matrix
for row in range(row_nb):
for col in range(col_nb):
if(row in flagged_rows or col in flagged_cols):
in_matrix[row, col] = 0
return in_matrix
if __name__ == "__main__":
rows = 6
cols = 5
in_mat = np.random.random_integers(0, 4, size=(rows, cols))
print(in_mat)
out_mat = row_col_to_zeros(in_mat)
print(out_mat)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.