blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c14f124e703e753a3a3554f64eef1faf4de8dde7 | Kwpolska/adventofcode | /2018/task02a.py | 564 | 3.703125 | 4 | #!/usr/bin/env python3
import collections
with open("input/02.txt") as fh:
file_data = fh.read().strip()
def solve(data):
twos = threes = 0
for line in data.split('\n'):
c = collections.Counter(line)
if 2 in c.values():
twos += 1
if 3 in c.values():
threes += 1
return twos * threes
test_data = "abcdef\nbababc\nabbcde\nabcccd\naabcdd\nabcdee\nababab"
test_output = solve(test_data)
test_expected = 12
print(test_output, test_expected)
assert test_output == test_expected
print(solve(file_data))
|
c050dd80df0b0f2969cac927c60afa029f9c41d8 | jdescalzo/card_trick | /card_trick.py | 2,708 | 4 | 4 | from deck import *
deck = []
suits = ['♠','♥','♦','♣']
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
deck = shuffle_deck(build_deck(deck,suits,values))[:21]
deck_top = []
deck_middle = []
deck_bottom = []
def deck_cut():
"""Separate the deck in three parts"""
while len(deck) > 0:
for card in deck:
current_card = deck.pop()
if len(deck) % 3 == 0:
deck_top.append(current_card)
elif len(deck) % 3 == 2:
deck_middle.append(current_card)
elif len(deck) % 3 == 1:
deck_bottom.append(current_card)
def show_decks():
"""Shows the three piles"""
print("1: " + str(deck_top))
print("2: " + str(deck_middle))
print("3: " + str(deck_bottom))
def deck_build(middle,top,bottom):
"""Makes a full deck from the three piles"""
while len(top)>0:
for card in top:
current_card = top.pop(0)
deck.append(current_card)
while len(middle)>0:
for card in middle:
current_card = middle.pop(0)
deck.append(current_card)
while len(bottom)>0:
for card in bottom:
current_card = bottom.pop(0)
deck.append(current_card)
def deck_rebuild(choice):
"""Set the order of the piles in the new deck"""
if choice == 1:
deck_build(deck_top,deck_middle,deck_bottom)
elif choice == 2:
deck_build(deck_middle,deck_top,deck_bottom)
elif choice == 3:
deck_build(deck_bottom,deck_middle,deck_top)
while True:
deck_cut()
print("Welcome to this magic trick! Please follow the instructions")
print("Enter 'quit' any time to stop playing")
print("Pick a card from any of the three decks below:\n")
show_decks()
choice = input("\nWas your card in the deck '1', '2' or '3'? ")
if choice == 'quit':
break
else:
deck_rebuild(int(choice))
deck_cut()
print("\nGreat! Now, once again.\n")
show_decks()
choice = input("\nIs your card in deck '1', '2' or '3'? ")
if choice == 'quit':
break
else:
deck_rebuild(int(choice))
deck_cut()
print("\nPerfect! One last time!\n")
show_decks()
choice = input("\nIs your card in deck '1', '2' or '3'? ")
if choice == 'quit':
break
else:
deck_rebuild(int(choice))
print("\n\tYour card is: " + str(deck[10]) + "!\n")
cont = input("Do you want to play again? (y/n) ")
if cont == 'n':
break
else:
print('\n ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ \n')
|
c6fd62a3919dfa4893310e5ff825850fd77fedb4 | Ankit-Kumar08/Soduku_Solver- | /Eliminate.py | 744 | 3.734375 | 4 |
from Grid_Value import *
def eliminate(values):
"""Eliminate values from peers of each box with a single value.
Go through all the boxes, and whenever there is a box with a single value,
eliminate this value from the set of values of all its peers.
Args:
values: Sudoku in dictionary form.
Returns:
Resulting Sudoku in dictionary form after eliminating values.
"""
for v in boxes:
if len(values[v]) == 1:
for peer in peers[v]:
values[peer] = values[peer].replace(values[v], '')
return values
#example
#display(eliminate(grid_values('..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..')))
|
b3d3a96c5294c50d10cbd3fc56db3ac17b34b029 | patkry/gios | /air_data.py | 860 | 3.71875 | 4 | """ Creating DataFrame for a specific sensor from data downloaded from api. """
import json, requests
import pandas as pd
from pandas.io.json import json_normalize
def load_s(z):
""" Creates url with sensor id as function argument, downloads data from api, parse json to python dictionary, flattens it, constructs DataFrame and changes columns in it for data base table 'air_data'"""
url = 'https://api.gios.gov.pl/pjp-api/rest/data/getData/' + str(z)
request = requests.get(url)
sensor_d=pd.DataFrame(json_normalize(json.loads(request.text),'values'))
sensor_d['id']=z
cols = sensor_d.columns.tolist()
cols = cols[-1:] + cols[:-1]
sensor_d=sensor_d[cols]
sensor_d.columns = ['sensor_id','date_s','sensor_v']
return sensor_d
if __name__ == "__main__":
k=92
sensor_data=load_s(k)
print(sensor_data.head()) |
5d3eec0be57361c043e60da4e1977e41b3ddbf3e | manikandan12629/Exercise | /venv/findLength.py | 400 | 3.640625 | 4 | def approach1():
global x, y, z
x='abc'
y='hello world !'
z=' h e l l o '
print('x length is {}, y length is {} and z lenth is {}'.format(len(x), len(y),len(z)))
def approach2():
a = b = c = 0
for i in x:
a+=1
for i in y:
b+=1
for i in z:
c+=1
print(f'x length is {a}, y length is {b} and z lenth is {c}')
approach1()
approach2() |
ec00a8cb1fa704a73ff7fc860117d99ef58dd949 | daniel199410/python | /reto2.py | 2,060 | 3.65625 | 4 | from os import system, name
def print_list(_list_):
x = 0
txt = ''
while x < len(_list_):
txt = '{} {}'.format(txt, '{}. {}'.format(x + 1, _list_[x]))
if x < len(_list_) - 1:
txt = txt + ","
else:
txt = txt + "."
x += 1
print(txt)
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
list_menu = ["Cambiar contraseña", "Ingresar coordenadas actuales", "Ubicar zona wifi más cercana",
"Guardar archivo con ubicación cercana", "Actualizar registros de zonas wifi desde archivo",
"Elegir opción de menú favorita", "Cerrar sesión"]
print_list(list_menu)
counter = 0
while counter < 4:
print("Elija una opción")
favorito = int(input(""))
if favorito == 6:
counter = 0
print("Seleccione opción favorita")
favorita = int(input(""))
if favorita in range(1, 6):
adivinanza1 = int(input(
"Para confirmar por favor responda:Me separaron de mi hermano siamés,antes era un ocho y ahora "
"soy un: "))
if adivinanza1 == 3:
adivinanza2 = int(input(
"Para confirmar por favor responda:Soy más de uno sin llegar al tres, y llego a cuatro cuando dos "
"me des: "))
if adivinanza2 == 2:
eliminado = list_menu.pop(favorita - 1)
list_menu.insert(0, eliminado)
clear()
else:
print("Error")
else:
print("Error")
print_list(list_menu)
else:
print("Error")
break
elif favorito in range(1, 6):
counter = 0
print('Usted ha elegido la opción {}'.format(favorito))
break
elif favorito == 7:
print('Hasta pronto')
break
else:
print("Error")
counter += 1
|
3c04909599fa5fdddac4ff36f325086be222fac7 | Jayakumari-27/python | /find the DOB.py | 76 | 3.609375 | 4 | x=2021
y=int(input("enter your birth year"))
z=x-y
print(f"you are {z} old") |
c2608d455c0c2d7a33f8c252cfaaf0207b42f7ca | kristinnk18/NEW | /Skipanir/forLoops/consecutiveNumbers.py | 482 | 4.3125 | 4 | # Write a Python program using for loops that, given an integer n as input, prints all consecutive sums from 1 to n.
# For example, if 5 is entered, the program will print five sums of consecutive numbers:
# 1 = 1
# 1 + 2 = 3
# 1 + 2 + 3 = 6
# 1 + 2 + 3 + 4 = 10
# 1 + 2 + 3 + 4 + 5 = 15
# Print only each sum, not the arithmetic expression.
num = int(input("Input an int: ")) # Do not change this line
sum = 0
for x in range(1, num + 1):
sum = sum + x
print(sum, x)
|
7f4815356a740c6fbf436c6489db245a81d10c27 | kylemaa/Hackerrank | /Implementation/time-conversion.py | 707 | 4.03125 | 4 | # https://www.hackerrank.com/challenges/time-conversion/problem
#!/bin/python3
import os
import sys
#
# Complete the timeConversion function below.
#
def timeConversion(s):
#
# Write your code here.
#
int_hr = int(s[0:2])
if s[8:10] == 'PM' and int_hr < 12:
int_hr += 12
if s[8:10] == 'AM' and int_hr == 12:
int_hr -= 12
if int_hr < 10:
updated_hr = '0'+ str(int_hr)
else:
updated_hr = str(int_hr)
for i in s[2:8]:
updated_hr = updated_hr + i
return updated_hr
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = timeConversion(s)
f.write(result)
f.close()
|
fd0bca58beb0380799468b6daf8dae9aaa1a11b1 | ramyaavak/product_even | /product_even.py | 89 | 3.921875 | 4 | a=int(raw_input())
b=int(raw_input())
if((a*b)%2==0):
print("even")
else:
print("odd")
|
f6fdcfafff17cbc4d8cbf2e76ab6b93117f02bd1 | Python87-com/PythonExercise | /Code/day16_20191128/my_range_exercise.py | 990 | 4.15625 | 4 | """
练习
for i in range(10):
print(i)
"""
class MyRange:
pass
class MyRangeManager:
# 开始数字 终止数字 步长
def __init__(self, startNum=0, stopNum=0, stepNum=1):
self.startNum = 0
self.stopNum = 0
self.stepNum = 1
self.__list_ruange = []
def add_myrange_num(self, num):
self.__list_ruange.append(num)
def __iter__(self):
return MyRangeIterator(self.__list_ruange)
# 迭代器
class MyRangeIterator:
def __init__(self, target):
self.__target = target
def __next__(self):
pass
# ------------------------------------------
m01 = MyRangeManager()
m01.add_myrange_num(1, 10, 1)
m01.add_myrange_num(11)
m01.add_myrange_num(13)
# 获取迭代器
iterator = m01.__iter__()
# 获取迭代器内下一个数据
item = iterator.__next__()
print(item)
for i in range(10):
print(i)
|
591bd8574542c8cfa5f832274e45650bd50f075f | 207leftovers/stupidlang | /stupidlang/parser.py | 2,239 | 3.921875 | 4 | Symbol = str
# Determines the object type of the token string and returns the
# token as its corresponding type
def typer(token):
# If the token is the string 'true' or 'false', returns the
# corresponding boolean value
if token == 'true':
return True
elif token == 'false':
return False
try:
# If the token is not a boolean, check if it is an int,
# if so, return it as an int
t = int(token)
return t
except ValueError:
try:
# If the token is neither a boolean, nor an int, check
# to see if it is a float, if so, return it as a float
t = float(token)
return t
except ValueError:
# If the type of the token isn't boolean, int or float,
# then return it as a string
return Symbol(token)
# lex takes in a string, adds spacing to the parentheses, splits
# it into its components and then runs typer on each element,
# recombining the typed elements into a list
def lex(loc):
tokenlist = loc.replace('(', ' ( ').replace(')', ' ) ').split()
return [typer(t) for t in tokenlist]
# syn takes in a list of tokens and breaks it up into sublists
# based on parenthesis
def syn(tokens):
# If there are no tokens in the list, then return an empty list
if len(tokens) == 0:
return []
# Pop the first token off the list of tokens
token = tokens.pop(0)
# If the first token is a left parenthesis
if token == '(':
L = []
# Recursively add sublists of tokens to the main list
while tokens[0] != ')':
L.append(syn(tokens))
tokens.pop(0) # pop off ')'
return L
# If the first token wasn't a left parenthesis
else:
# If the first token was a right parenthesis then something
# is a bit screwy
if token==')':
assert 1, "should not have got here"
# Otherwise, if the first token is neither a left nor right
# parenthesis, simply return the token
return token
# Break down the string loc into a list with sublists for each
# parenthesied set of variables and operations
def parse(loc):
return syn(lex(loc)) |
912f5b01232564e15a96e42e4461476c6fc26eb4 | DonatasNoreika/python1lygis | /Programos/Funkcijos/1uzduotis.py | 3,628 | 3.734375 | 4 | # Sukurkite ir išsibandykite funkcijas, kurios:
# 1. Gražinti trijų paduotų skaičių sumą.
def skaiciu_suma(sk1, sk2, sk3):
return sk1 + sk2 + sk3
print(skaiciu_suma(45, 5, 6))
# 2. Gražintų paduoto sąrašo iš skaičių, sumą.
def saraso_suma(sarasas):
suma = 0
for skaicius in sarasas:
suma += skaicius
return suma
sarasas = [4, 5, 78, 8]
print(saraso_suma(sarasas))
# 3. Atspausdintų didžiausią iš kelių paduotų skaičių (panaudojant *args).
# def didziausias_skaicius(*args):
# didziausias = args[0]
# for sk in args:
# if sk > didziausias:
# didziausias = sk
# return didziausias
# arba
def didziausias_skaicius(*args):
return max(args)
print(didziausias_skaicius(5, 8, 789, 94, 78))
# 4. Gražintų paduotą stringą atbulai.
def stringas_atbulai(stringas):
return stringas[::-1]
print(stringas_atbulai("Donatas Noreika"))
# 5. Atspausdintų, kiek paduotame stringe yra žodžių, didžiųjų ir mažųjų raidžių, skaičių.
def info_apie_sakini(stringas):
print(f"Šiame sakinyje yra {len(stringas.split())} žodžių")
didziosios = 0
mazosios = 0
skaiciai = 0
for simbolis in stringas:
if simbolis.isupper():
didziosios += 1
if simbolis.islower():
mazosios += 1
if simbolis.isnumeric():
skaiciai += 1
print(f"Didžiosios: {didziosios}, mažosios: {mazosios}, skaičiai: {skaiciai}")
info_apie_sakini("Laba diena laba diena lab 522")
# 6. Gražintų sąrašą tik su unikaliais paduoto sąrašo elementais.
def unikalus_sarasas(sarasas):
naujas_sarasas = []
for skaicius in sarasas:
if skaicius not in naujas_sarasas:
naujas_sarasas.append(skaicius)
return naujas_sarasas
print(unikalus_sarasas([4, 5, "Labas", 6, "Labas", True, 5, True, 10]))
# alternatyva:
def unique_only(*args):
return list(set(args))
# 7. Gražintų, ar paduotas skaičius yra pirminis.
n= int(input("Įveskite skaičių "))
def ar_pirminis(skaicius):
if skaicius > 1:
for num in range(2, skaicius):
if skaicius % num == 0:
return False
return True
return False
print(ar_pirminis(n))
# 8. Išrikiuotų paduoto stringo žodžius nuo paskutinio iki pirmojo
def isrikiuoti_nuo_galo(sakinys):
zodziai = sakinys.split()[::-1]
return " ".join(zodziai)
print(isrikiuoti_nuo_galo("Vienas du trys keturi"))
# 9. Gražina, ar paduoti metai yra keliamieji, ar ne.
import calendar
def ar_keliamieji(metai):
return calendar.isleap(metai)
print(ar_keliamieji(2020))
print(ar_keliamieji(2100))
print(ar_keliamieji(2000))
# 10. Gražina, kiek nuo paduotos sukakties praėjo metų, mėnesių, dienų, valandų, minučių, sekundžių.
import datetime
def patikrinti_data(sukaktis):
ivesta_data = datetime.datetime.strptime(sukaktis, "%Y-%m-%d %X")
now = datetime.datetime.now()
skirtumas = now - ivesta_data
print("Praėjo metų: ", skirtumas.days // 365)
print("Praėjo mėnesių: ", skirtumas.days / 365 * 12)
print("Praėjo savaičių: ", skirtumas.days // 7)
print("Praėjo dienų: ", skirtumas.days)
print("Praėjo valandų: ", skirtumas.total_seconds() / 3600)
print("Praėjo minučių: ", skirtumas.total_seconds() / 60)
print("Praėjo sekundžių: ", skirtumas.total_seconds())
patikrinti_data("2000-01-01 12:12:12")
patikrinti_data("1991-03-11 12:12:12")
|
8c965ac17f439bc477757d796c39d8d3586b22eb | garypush/leetcode-notes | /leetcode/727.py | 1,154 | 3.671875 | 4 | class Solution(object):
''' 难点在于dp[i][j]的定义 '''
def minWindow(self, S, T):
"""
dp[i][j] means the smallest end index of the substring in S[i:] and T[j:]
:type S: str
:type T: str
:rtype: str
"""
m,n = len(S),len(T)
dp = [[None for _ in range(n)] for _ in range(m+1)]
for j in range(n):
dp[m][j] = -1 # S is empty, impossible to find the index
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if S[i] == T[j]:
if j == n-1: # only one character in T
dp[i][j] = i # i is the end index
else:
dp[i][j] = dp[i+1][j+1]
else:
dp[i][j] = dp[i+1][j]
# find the minimum substring
left = None
right = None
for i in range(m):
if left == None or (dp[i][0] != -1 and dp[i][0]-i < right-left):
left = i
right = dp[i][0]
if left != None:
return S[left:right+1]
return ''
|
74ee397b16894aec64e9a42d6db8708ebd229557 | nanthamanish/GeneCentralityLethality | /Centrality.py | 4,043 | 3.578125 | 4 | import pandas as pd
import networkx as nx
import time
import os
def get_features(G, mi=1000):
"""Function to extract features from the Graph
Built in functions from the networkx package is used to extract the
following centrality measures.
1) Degree centrality
2) Eigenvector centrality
3) Closeness centrality
4) Betweenness centrality
5) Subgraph centrality
6) Load centrality
7) Harmonic centrality
8) Reaching centrality
9) Clustering centrality
10) Pagerank
"""
nodes = nx.nodes(G)
lrc_cen = {}
pagerank = {}
pre_time = time.time()
for v in nodes:
lrc_cen[v] = nx.local_reaching_centrality(G, v)
pagerank[v] = 0
print("Local Reaching Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
voterank = nx.voterank(G)
val=nodes.__len__()
for v in voterank:
pagerank[v] = val
val-=1
print("Page Rank Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
deg_cen = nx.degree_centrality(G)
print("Degree Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
eig_cen = nx.eigenvector_centrality(G, max_iter=mi)
print("Eigenvector Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
clo_cen = nx.closeness_centrality(G)
print("Closeness Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
bet_cen = nx.betweenness_centrality(G)
print("Betweenness Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
sub_cen = nx.subgraph_centrality(G)
print("Subgraph Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
ld_cen = nx.load_centrality(G)
print("Load Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
har_cen = nx.harmonic_centrality(G)
print("Harmonic Centrality Computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
pre_time = time.time()
cluster = nx.clustering(G)
print("Clustering Coefficients computed")
print("Time taken = ",str(time.time() - pre_time), '\n')
df = pd.DataFrame([ deg_cen, eig_cen, clo_cen,
bet_cen, sub_cen, ld_cen,
har_cen, lrc_cen, cluster,
pagerank],
index=["degree_centrality",
"eigenvector_centrality",
"closeness_centrality",
"betweenness_centrality",
"subgraph_centrality",
"load_centrality",
"harmonic_centrality",
"reaching_centrality",
"clustering_centrality",
"pagerank"])
return df.transpose()
if __name__ == "__main__":
with open("graphs.txt") as f:
graphs = f.readlines()
graphs = [x.strip() for x in graphs]
cwd = os.getcwd()
print(cwd)
for i in range (0, len(graphs)):
graphname = graphs[i]
print(graphname)
f_in = cwd + '\Graphs\\'+ graphname+ '.ppi.txt'
print(f_in)
f_out = cwd + '\Features\\' + graphname + '.csv'
print(f_out)
start_time = time.time()
G = nx.read_weighted_edgelist(f_in)
df = get_features(G)
#writing to out file
df.to_csv(f_out)
f_t = open("time_log.txt", 'a')
f_t.write(graphname + '\tt = ' + str(time.time() - start_time) + '\n')
else:
print("Wrong Argument") |
9760c341e75e7863644d6f1802bf8fab4c545cc5 | kradical/Pytris | /TetrisPieces.py | 9,964 | 3.546875 | 4 | import pygame
import random
# global properties of the instance of the application
class TetrisApp():
def __init__(self):
self.block_list = [['I', 'O', 'S', 'Z', 'J', 'L', 'T'], ['I', 'O', 'S', 'Z', 'J', 'L', 'T']]
random.shuffle(self.block_list[0])
random.shuffle(self.block_list[1])
self.block_in_sequence = 0
self.passive = Blocks()
self.active = MovingBlocks(self.block_list[0][self.block_in_sequence])
self.play_field = PlayingField(360, 0, 200, 485)
def new_active(self):
self.block_in_sequence += 1
self.block_in_sequence %= 7
if self.block_in_sequence == 0:
self.block_list[0], self.block_list[1] = self.block_list[1], self.block_list[0]
random.shuffle(self.block_list[1])
self.active = MovingBlocks(self.block_list[0][self.block_in_sequence])
# Makes a sprite of the rectangle that would be passed into pygame.Rect
# useful for sprite.collide type methods
class PlayingField(pygame.sprite.Sprite):
def __init__(self, left, top, w, h):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.Rect(left, top, w, h)
# any group of blocks
class Blocks(pygame.sprite.Group):
def move_down(self, t_game):
for sprite in iter(self):
sprite.rect = sprite.rect.move(0, 20)
self.center[1] += 20
if t_game is not None and self.check_for_collisions(t_game.passive, t_game.play_field):
self.move_up()
for sprite in iter(self):
self.remove(sprite)
t_game.passive.add(sprite)
t_game.passive.check_for_point()
t_game.new_active()
return False
else:
return True
def move_up(self):
for sprite in iter(self):
sprite.rect = sprite.rect.move(0, -20)
def check_for_collisions(self, group_of_blocks, play_field):
if len(pygame.sprite.spritecollide(play_field, self, False)) != 4:
return True
elif pygame.sprite.groupcollide(self, group_of_blocks, False, False):
return True
else:
return False
def check_for_point(self):
rows_down = 0
rows_removed = False
for x in range(20):
check_row = PlayingField(360, 480-20*x, 200, 20)
num_collisions = pygame.sprite.spritecollide(check_row, self, False)
if len(num_collisions) == 10:
self.remove(num_collisions)
rows_removed = True
rows_down += 1
for sprite in num_collisions:
sprite.rect = sprite.rect.move(0, 20*rows_down)
return rows_removed
#active 4 block unit
class MovingBlocks(Blocks):
def __init__(self, tetranimo):
pygame.sprite.Group.__init__(self)
self.rotate_state = 0
self.type = tetranimo
self.center = self.initialize_center()
if self.type == 'I':
for x in range(4):
self.add(Block(tetranimo, 420+20*x, 60))
elif tetranimo == 'O':
for x in range(2):
self.add(Block(tetranimo, 440+20*x, 60))
self.add(Block(tetranimo, 440+20*x, 80))
elif tetranimo == 'T':
self.center = [440, 80]
self.add(Block(tetranimo, 440, 60))
for x in range(3):
self.add(Block(tetranimo, 420+20*x, 80))
elif tetranimo == 'S':
self.center = [440, 80]
for x in range(2):
self.add(Block(tetranimo, 440+20*x, 60))
self.add(Block(tetranimo, 420+20*x, 80))
elif tetranimo == 'Z':
self.center = [440, 80]
for x in range(2):
self.add(Block(tetranimo, 420+20*x, 60))
self.add(Block(tetranimo, 440+20*x, 80))
elif tetranimo == 'J':
self.center = [440, 80]
self.add(Block(tetranimo, 420, 60))
for x in range(3):
self.add(Block(tetranimo, 420+20*x, 80))
elif tetranimo == 'L':
self.center = [440, 80]
self.add(Block(tetranimo, 460, 60))
for x in range(3):
self.add(Block(tetranimo, 420+20*x, 80))
def initialize_center(self):
if self.type == 'I':
return [460, 80]
else:
return [440, 100]
def move_left(self, t_game=None):
for sprite in iter(self):
sprite.rect = sprite.rect.move(-20, 0)
self.center[0] -= 20
if t_game is not None and self.check_for_collisions(t_game.passive, t_game.play_field):
self.move_right()
def move_right(self, t_game=None):
for sprite in iter(self):
sprite.rect = sprite.rect.move(20, 0)
self.center[0] += 20
if t_game is not None and self.check_for_collisions(t_game.passive, t_game.play_field):
self.move_left()
def drop_down(self, t_game):
while self.move_down(t_game):
pass
def rotate_cw(self):
if self.type == 'O':
pass
elif self.type == 'I':
self.rotate_state += 1
self.rotate_state %= 4
for sprite in iter(self):
self.remove(sprite)
if self.rotate_state == 0:
for x in range(4):
self.add(Block(self.type, self.center[0]-40+20*x, self.center[1]-20))
elif self.rotate_state == 1:
for x in range(4):
self.add(Block(self.type, self.center[0], self.center[1]-40+20*x))
elif self.rotate_state == 2:
for x in range(4):
self.add(Block(self.type, self.center[0]-40+20*x, self.center[1]))
else:
for x in range(4):
self.add(Block(self.type, self.center[0]-20, self.center[1]-40+20*x))
else:
for sprite in iter(self):
# left
if sprite.rect.left < self.center[0]:
# bot
if sprite.rect.top > self.center[1]:
sprite.rect.top -= 40
# mid
elif sprite.rect.top == self.center[1]:
sprite.rect.left += 20
sprite.rect.top -= 20
# top
else:
sprite.rect.left += 40
# mid
elif sprite.rect.left == self.center[0]:
# bot
if sprite.rect.top > self.center[1]:
sprite.rect.top -= 20
sprite.rect.left -= 20
# top
elif sprite.rect.top < self.center[1]:
sprite.rect.top += 20
sprite.rect.left += 20
# right
else:
# bot
if sprite.rect.top > self.center[1]:
sprite.rect.left -= 40
# mid
elif sprite.rect.top == self.center[1]:
sprite.rect.left -= 20
sprite.rect.top += 20
# top
else:
sprite.rect.top += 40
def rotate_ccw(self):
if self.type == 'O':
pass
elif self.type == 'I':
self.rotate_state += 3
self.rotate_state %= 4
for sprite in iter(self):
self.remove(sprite)
if self.rotate_state == 0:
for x in range(4):
self.add(Block(self.type, self.center[0]-40+20*x, self.center[1]-20))
elif self.rotate_state == 1:
for x in range(4):
self.add(Block(self.type, self.center[0], self.center[1]-40+20*x))
elif self.rotate_state == 2:
for x in range(4):
self.add(Block(self.type, self.center[0]-40+20*x, self.center[1]))
else:
for x in range(4):
self.add(Block(self.type, self.center[0]-20, self.center[1]-40+20*x))
# rotate for all 3x3 bricks
else:
for sprite in iter(self):
# left
if sprite.rect.left < self.center[0]:
# bot
if sprite.rect.top > self.center[1]:
sprite.rect.left += 40
# mid
elif sprite.rect.top == self.center[1]:
sprite.rect.left += 20
sprite.rect.top += 20
# top
else:
sprite.rect.top += 40
# mid
elif sprite.rect.left == self.center[0]:
# bot
if sprite.rect.top > self.center[1]:
sprite.rect.top -= 20
sprite.rect.left += 20
# top
elif sprite.rect.top < self.center[1]:
sprite.rect.top += 20
sprite.rect.left -= 20
# right
else:
# bot
if sprite.rect.top > self.center[1]:
sprite.rect.top -= 40
# mid
elif sprite.rect.top == self.center[1]:
sprite.rect.left -= 20
sprite.rect.top -= 20
# top
else:
sprite.rect.left -= 40
class Block(pygame.sprite.Sprite):
def __init__(self, colour, x_offset, y_offset):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("img/"+colour+"block.png")
self.rect = self.image.get_rect().move(x_offset, y_offset) |
2d96d9b64b846c7f99dc65bd272480e62de2e510 | ShakilAhmmed/Problem_Solve | /CodeForces/watermelon.py | 90 | 3.90625 | 4 | number = int(input())
if number > 2 and number % 2 == 0:
print("YES")
else:
print("NO")
|
63ebc1b1ca42ceaa7583b7afbf5c28976f7929fd | r96725046/leetcode-py | /Matrix/73.set-matrix-zeroes.py | 1,051 | 3.578125 | 4 | #
# @lc app=leetcode id=73 lang=python3
#
# [73] Set Matrix Zeroes
#
# @lc code=start
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
fr=False
fc=False
for j in range(len(matrix[0])):
if matrix[0][j]==0:
fr=True
for i in range(len(matrix)):
if matrix[i][0]==0:
fc=True
for i in range(1,len(matrix)):
for j in range(1,len(matrix[0])):
if matrix[i][j]==0:
matrix[0][j]=0
matrix[i][0]=0
for i in range(1,len(matrix)):
for j in range(1,len(matrix[0])):
if matrix[i][0]==0 or matrix[0][j]==0:
matrix[i][j]=0
if fr:
for j in range(0,len(matrix[0])):
matrix[0][j]=0
if fc:
for i in range(0,len(matrix)):
matrix[i][0]=0
# @lc code=end
|
5cf2ac22b1ae80dbfe7d8f228729b7fc8d33e8c7 | juaopedrosilva/Python-Challenge | /EstruturaSequencial/atividade7.py | 97 | 3.59375 | 4 | l = int(17)
area = float(l * l)
dobro = 2 * float(area)
print("o dobro desta área é ", dobro) |
d24a220a50086d515edc95aa28de2786d3daa4cc | GoVed/AITicTac | /Game.py | 3,179 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 1 19:36:59 2021
@author: vedhs
"""
import random
import numpy as np
class Game:
#For saving which player has which tile of the game
isX = np.full((3,3),False)
isO = np.full((3,3),False)
turn = False
def __init__(self):
self.turn = bool(random.randint(0, 1))
def reset(self):
self.isX = np.full((3,3),False)
self.isO = np.full((3,3),False)
def getCurrent(self,style='XO'):
#Different styles for returning status
styles={'XO':{'x':'X','o':'O'},'+-':{'x':'+','o':'-'}}
#Empty status var to fill in later
out=[['']*3]*3
#Looping through all the position in tic tac toe
for i in range(3):
for j in range(3):
if self.isX[i][j]:
out[i][j]=styles[style]['x']
if self.isO[i][j]:
out[i][j]=styles[style]['o']
return out
def select(self,x,y):
if self.checkWin()=='-':
if self.isX[x][y] or self.isO[x][y]:
return "Tile already selected"
self.turn = not self.turn
if not self.turn:
self.isX[x][y] = True
return "x"
else:
self.isO[x][y] = True
return "o"
return "Game over"
def checkWin(self):
#Check horizontal and verticle
for i in range(3):
if np.array_equal(self.isX[i,:],np.full((3),True)):
return 'x'
if np.array_equal(self.isO[i,:],np.full((3),True)):
return 'o'
if np.array_equal(self.isX[:,i],np.full((3),True)):
return 'x'
if np.array_equal(self.isO[:,i],np.full((3),True)):
return 'o'
#Check diagonal
if np.array_equal(self.isX.diagonal(),np.full((3),True)):
return 'x'
if np.array_equal(self.isO.diagonal(),np.full((3),True)):
return 'o'
if np.array_equal(np.fliplr(self.isX).diagonal(),np.full((3),True)):
return 'x'
if np.array_equal(np.fliplr(self.isO).diagonal(),np.full((3),True)):
return 'x'
#Check all filled / draw match
if np.array_equal(np.bitwise_or(self.isX,self.isO),np.full((3,3),True)):
return 'd'
return '-'
def playRandom(self):
empty = []
for i in range(3):
for j in range(3):
if not self.isX[i,j] and not self.isO[i,j]:
empty.append([i,j])
rand = random.randint(0,len(empty)-1)
self.select(empty[rand][0],empty[rand][1])
return empty[rand][0],empty[rand][1]
def playPriority(self,priority):
for i in range(9):
if self.select(priority[0,i], priority[1,i])=='o':
return priority[0,i], priority[1,i]
return -1,-1
|
cc9e3becff1a5d5954f0162274ed7277373f0bdd | souza10v/Exercicios-em-Python | /activities1/codes/61.py | 382 | 3.65625 | 4 | // -------------------------------------------------------------------------
// github.com/souza10v
// souza10vv@gmail.com
// -------------------------------------------------------------------------
k=soma=n=0
while n != 999:
n=int(input("Digite um número [999 para parar]: "))
if n != 999:
soma += n
k += 1
print(f"A soma dos {k} números é {soma}.")
|
4e31b7edc2767043bab5afe63f8c010e2a2e79aa | deanhadzi/cs-module-project-algorithms | /moving_zeroes/moving_zeroes.py | 899 | 4.375 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# Step 1 - create a copy of the original array.
arr_copy = arr[:]
# Step 2 - create a counter to get number of zeros in array.
counter = 0
# Step 3 - loop through the array copy and remove all zeros.
# Increase counter.
# If the array is made of all zeros, break once the counter matches length of original array.
while 0 in arr_copy:
arr_copy.remove(0)
counter += 1
if counter == len(arr):
break
# Step 4 - create a all zero array.
zeros = [0] * counter
# Step 5 - overwrite the original array.
arr = arr_copy + zeros
return arr
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
|
ad1b03f5f0186b63b7ec1762415c35295a0f29a8 | skrishna1978/CodingChallenge-January-2019- | /1.10.2019 | binaryToDecimalArray.py | 1,123 | 4.1875 | 4 | #1.10.2019 - Shashi
#program to accept binary value as an array and return its decimal equivalent.
#Binary code can be of any length but should only comprise of 1s and 0s.
def bin_dec(binArr): #function starts here
result = 0 #variable to hold final answer
for i in range(len(binArr)): #loop through each digit in the array
if binArr[i] == 1: #only 1 position elements have a power
result = result + pow(2,len(binArr)-1-i) #total calculated by squaring arrpos(length-1-i)
#We do this because digit powers start from right but array is being navigated from the left.
#So for 1100, the first 1 is [0] in array but in position 3 as a number.
#Hence, len(binArr)-1-i for that position gives u : len(binArr) = 4 -1-0 (since i is 0 at this point)
#4-1-0 = 4 - 1 = 3. 2 power 3 is what we want for first 1.
#continue loop for all elements in array
return result #return output
print(bin_dec([1,0,0,1,1,1,1])) #79
print(bin_dec([1,1,1,1,0])) #30
print(bin_dec([1,0,0])) #4
print(bin_dec([1,0,1,0,0,1])) #41
#end of program
|
b51c44618813b1d9c2033d4df445ecd5691f57b7 | i-am-Shuvro/Project-GS-4354- | /Main File.py | 8,972 | 3.96875 | 4 | def greet(str):
name1 = input("[N.B: Enter your name to start the program.] \n\t* First Name: ")
name2 = input("\t* Last Name: ")
return "Hello, " + str(name1) + " " + str(name2) + "! Welcome to this program, sir!"
print(greet(str))
print("This program helps you with some information on tax-rate on building construction. "
"\nBesides it tells you about some facilities you can add to your cart within your budget.")
input("\tPress ENTER to start the program!")
from Module import getinput
def confirm():
while True:
budget = getinput("Please enter your budget amount for building construction in BDT (At least 1 crore): ")
if budget < 10000000:
print("\tThis budget is too low to construct a building, sir! The minimum budget should be of 1 crore!")
continue
else:
input(f"\tGreat! {budget} BDT is quite a sufficient amount. \nNow please press ENTER & choose various options!")
if budget >= 150000000:
while True:
try:
marble = int(input("\tDo you want marble-flooring in your building? Type 1 if you want & type 2 if you don't: "))
if marble == 1:
print("\t\tOkay! Your building will be of marble-flooring, sir.")
elif marble == 2:
print("\t\tGot you! You will get tiles-flooring, sir.")
else:
print("\t\tPlease choose to type one option from 1 and 2!")
continue
except ValueError:
print("\t\tOops! Something is wrong. Please choose to type one option from 1 and 2!")
continue
break
elif budget <= 50000000 or budget >= 15000000:
while True:
try:
tiles = int(input("\tDo you want tiles-flooring in your building? Type 1 if you want & type 2 if you don't: "))
if tiles == 1:
print("\t\tOkay! our building will be of tiles-flooring, sir.")
elif tiles == 2:
print("\t\tGot you! You will get cement-flooring, sir.")
else:
print("\t\tPlease choose to type one option from 1 and 2!")
continue
except ValueError:
print("\t\tOops! Something is wrong. Please choose to type one option from 1 and 2!")
continue
break
else:
print("\t\tAlight! You will get cement-flooring, sir.")
break
return budget
my_budget = confirm()
def free():
free_facilities = ["AI Security System", "Free Water Supply", "10 Years of free maintenance"]
serial = [1, 2, 3]
serial_of_services = [serial, free_facilities]
print("\nAs a small present, we give all our customers these 3 facilities for free: ", *free_facilities, sep="\n\t")
print("Besides you can suggest us for some more free-services.")
try:
n = int(input("Except these 3, enter how many facilities you would suggest us to provide for free (Press ENTER to skip): "))
j = 1
while j != n + 1:
free_demands = input("\t* Suggestion " + str(j) + ": ")
if not free_demands:
j -= 1
print("\tPlease enter your suggestions!")
else:
free_facilities.append(free_demands)
serial.append(4 + j)
j += 1
t = len(free_facilities)
print(f"Along with the 3 services, we will try to provide you with these {n} facilities:",
*free_facilities[3:], sep="\n\t")
print("\nSo, all you get from us as complementary is", *free_facilities, sep="\n\t")
try:
r = int(input("\nIf you wish to remove any of the above free services, just enter the serial number (Press ENTER to skip): "))
z = free_facilities.index(serial_of_services[1][r - 1])
free_facilities.pop(z)
print("\tSo you will get these free-services:", *free_facilities, sep="\n\t\t")
try:
more_delete = int(input("Want to remove some more services? Then write here the number of services you want to delete (Press ENTER to skip): "))
print("\t\tWrite down service name completely to delete from your cart! (eg: AI Security Service)")
for a in range(0, more_delete):
items = str(input(f"\t\t\t{a + 1}. Remove the service = "))
free_facilities.remove(items)
print("Alright! So, you are getting this fro free:", *free_facilities, sep="\n\t")
except:
print("So you do not want anything more to be removed. Great!")
except:
print("So, you don't want to remove anything from the list. Great!")
except:
print("So, you don't want to remove anything from the list. Great!")
free_service = free()
def paid():
print("\nWe also provide some services to our customers. You can purchase them from us. They are:")
internaldata = {1: 2000000,
2: 250000,
3: 800000,
4: 2000000,
5: 600000,
}
paid_facilities = {'1. Car Parking': 2000000,
'2. Elevator': 250000,
'3. Jacuzzi': 800000,
'4. Roof-top Swimming Pool': 2000000,
'5. Sauna': 600000,
}
for info in paid_facilities:
print("\t", info)
while True:
try:
y = int(input("To know the price in BDT, please list number (Press ENTER to skip): "))
if 1 <= y <= 5:
print("\tThe price of this item will be: ", internaldata.get(y))
else:
print("Please enter between 1 to 5 from this list!")
continue
z = input("Do you want to add more services? Type y to continue & press ENTER to skip: ")
if z.lower() == 'y':
continue
else:
print("Okay! No more prices!")
break
except:
print("Okay! No more prices!")
break
print("\nHere is a complete list of services. You can order them later if need be. Have a look:")
for key, value in paid_facilities.items():
print(key, ": Price", value, "BDT")
paid_service = paid()
from Module import getinput
building_type = ('1. Garment', '2. Residential', '3. Commercial', '4. Corporate')
print("\n Now to know about tax-rates & your total cost, choose a building type from this list - ", *building_type, sep="\n\t")
b = getinput("Enter the number for your building type?: ")
tax_list = (12, 10, 20, 25)
from Module import TaxCalc
maxtax = TaxCalc(tax_list)
print(f"\tThe maximum tax-rate will be {maxtax.get_max_tax()}% ", end="")
print(f"and the minimum tax-rate will be {maxtax.get_min_tax()}% for your building!")
class Gar(TaxCalc):
def get_addtax_gar(self):
return my_budget * (3 / 100)
gar = Gar(TaxCalc)
gar.get_addtax_gar()
class Corp(TaxCalc):
def get_addtax_corp(self):
return my_budget * (2 / 100)
corp = Corp(TaxCalc)
corp.get_addtax_corp()
class Com(TaxCalc):
def get_addtax_com(self):
return my_budget * (4 / 100)
com = Com(TaxCalc)
com.get_addtax_com()
addtax_list = [gar.get_addtax_gar(), 0, com.get_addtax_com(), corp.get_addtax_corp()]
while True:
if b == 1:
print(f"[N.B: There will be additional tax of {gar.get_addtax_gar()} BDT for garments contraction.]")
elif b == 2:
print("There will be no additional tax!")
elif b == 3:
print(f"[N.B: There will be additional tax of {com.get_addtax_com()} BDT for commercial building contraction.]")
elif b == 4:
print(
f"[N.B: There will be additional tax of {corp.get_addtax_corp()} BDT for corporate building contraction.]")
else:
print("Please enter between 1 & 4")
b = getinput("Please re-enter the number for your building type?: ")
continue
break
max_total = my_budget + int(addtax_list[int(b) - 1]) + my_budget * 0.25
min_total = my_budget + int(addtax_list[int(b) - 1]) + my_budget * 0.1
print("\nYou total cost will fluctuate between ", max_total, "BDT & ", min_total, "BDT while completing the whole construction project!")
input("\nThanks a ton for running this code! Press ENTER to close.")
|
61e6e62fb99f60133fb12cd377ce3e2bdf4d2b2c | chrislarry/python | /fibonacci.py | 154 | 3.5625 | 4 | #!/usr/bin/python
new = 1
count = 10
old = 0
print("\n\nFibonacci number\n\n")
for i in range(count):
new += old
old = new - old
print(new)
|
3ec148e2293bcbd29a9787c40c1dcf34de1f9aa9 | kenan666/Study | /算法总结/合并K个排序链表.py | 1,706 | 4 | 4 | '''
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
'''
'''
解1
优先级队列
时间复杂度:O(n*log(k))O(n∗log(k)),n 是所有链表中元素的总和,k 是链表个数。
'''
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
import heapq
dummy = ListNode(0)
p = dummy
head = []
for i in range(len(lists)):
if lists[i] :
heapq.heappush(head, (lists[i].val, i))
lists[i] = lists[i].next
while head:
val, idx = heapq.heappop(head)
p.next = ListNode(val)
p = p.next
if lists[idx]:
heapq.heappush(head, (lists[idx].val, idx))
lists[idx] = lists[idx].next
return dummy.next
'''
解2
分而治之
链表两两合并
'''
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:return
n = len(lists)
return self.merge(lists, 0, n-1)
def merge(self,lists, left, right):
if left == right:
return lists[left]
mid = left + (right - left) // 2
l1 = self.merge(lists, left, mid)
l2 = self.merge(lists, mid+1, right)
return self.mergeTwoLists(l1, l2)
def mergeTwoLists(self,l1, l2):
if not l1:return l2
if not l2:return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
|
bb8ea7b5e9957e76a832e68f7270d5e4a4f9fb48 | tianyuemylove/yue | /p1月.py/冰淇淋.py | 246 | 3.5625 | 4 | import random
cc = random.randint(1,9)
if cc == 1 or cc == 4 or cc == 7:
print('刘美娜买棒棒糖')
elif cc == 2 or cc ==5 or cc == 8:
print('王一凡买奶喝')
elif cc == 3 or cc == 6 or cc ==9:
print('吕东泽买冰淇淋')
|
93e5d17db6aeff8758e91900f6a71e552fd22dd3 | mike1334/Project-2---build_a_soccer_league | /league_Functions.py | 2,425 | 3.875 | 4 | import csv
import copy
teams = {
'Sharks':[],
'Dragons':[],
'Raptors':[]
}
def divide_teams_experience():
# This function loops through the provided .csv file. First it finds and splits evenly the experinenced
# players between the three teams. Next it accomplishes the same task with the inexperienced players.
# the results are stored in the teams{} for future reference and use.
with open("soccer_players.csv", 'r') as player_csv:
fieldnames = ['Name','Height (inches)','Soccer Experience','Guardian Name(s)']
reader = csv.DictReader(player_csv)
n = list(reader)
i = 0
for l in n:
if l['Soccer Experience'] == 'YES' and i < 3 :
teams['Sharks'].append(l)
i+=1
elif l['Soccer Experience'] == 'YES' and i < 6 :
teams['Dragons'].append(l)
i+=1
elif l['Soccer Experience'] == 'YES' and i < 9 :
teams['Raptors'].append(l)
i+=1
i = 0
for l in n:
if l['Soccer Experience'] == 'NO' and i < 3 :
teams['Sharks'].append(l)
i+=1
elif l['Soccer Experience'] == 'NO' and i < 6 :
teams['Dragons'].append(l)
i+=1
elif l['Soccer Experience'] == 'NO' and i < 9 :
teams['Raptors'].append(l)
def build_teams():
# This function firstly creates the teams.txt output file. The first loop goes through a copy of the teams{} dictionary
# and .pop()'s the unnecessary key fields from each teams list. The copy is used as to not modify the original global teams{}
# for future use. In loops the team name is printed first before its players are written, once the end of team list is reached
# the next loop starts for the following team.
with open("teams.txt",'w') as roster:
fieldnames = ['Name','Soccer Experience','Guardian Name(s)']
roster_w = csv.DictWriter(roster, fieldnames = fieldnames)
# .deepcopy(x,[ memo]) used here to make a copy of the dict() and all of the elements within it,
teams_copy = copy.deepcopy(teams)
for l in range(len(teams_copy['Sharks'])):
teams_copy['Sharks'][l].pop('Height (inches)')
teams_copy['Dragons'][l].pop('Height (inches)')
teams_copy['Raptors'][l].pop('Height (inches)')
roster.write('\nSharks\n')
for l in teams_copy['Sharks']:
roster_w.writerow(l)
roster.write('\nDragons\n')
for l in teams_copy['Dragons']:
roster_w.writerow(l)
roster.write('\nRaptors\n')
for l in teams_copy['Raptors']:
roster_w.writerow(l)
teams_copy.clear()
|
d344c3f167cc2c43e88ee123edec72ba2ad81ff0 | Khun-Cho-Lwin/Python-Files-IPND | /Print_Numbers.py | 202 | 3.859375 | 4 | def print_numbers(x):
i = 0
while i < x:
i = i + 1
print i
print_numbers(3)
def print_numbers(n):
i = 1
while i <= n:
print i
i = i + 1
print_numbers(3)
|
c77aea0a501e5274320b729e577651440fc7f82c | rabidrabbit/tropical-cryptography | /key_exchange_protocol.py | 3,039 | 3.578125 | 4 | """
Implementation of a tropical key exchange protocol.
"""
from tropical_matrix import *
import math
import random
def get_identity_matrix(n):
if n <= 1:
raise ValueError("An identity matrix must have more than a singular entry.")
identity_matrix = []
for i in range(n):
row = [math.inf] * n
row[i] = 0
identity_matrix.append(row)
return TropicalMatrix(identity_matrix)
def generate_random_matrix(n, min_term, max_term):
new_matrix = [[None] * n for i in range(n)]
for i in range(n):
for j in range(n):
new_matrix[i][j] = random.randint(min_term, max_term)
return TropicalMatrix(new_matrix)
def generate_random_tropical_poly(max_degree, min_coefficient, max_coefficient):
"""
Generates a random (non-constant) tropical polynomial up to a given degree.
"""
coefficients = []
for d in range(0, random.randint(1, max_degree) + 1):
coefficients.append(random.randint(min_coefficient, max_coefficient))
return coefficients
def evaluate_polynomial(tropical_matrix, coefficient_list):
"""
Evaluates the polynomial (in list form) given a tropical matrix.
"""
identity_matrix = get_identity_matrix(tropical_matrix.get_dimension())
sum_list = []
sum_list.append(identity_matrix.mult_scalar(coefficient_list[0]))
for i in range(1, len(coefficient_list)):
sum_list.append(tropical_matrix.mult_scalar(coefficient_list[i]))
return get_minimum_sum(sum_list)
def get_minimum_sum(matrix_list):
new_matrix = matrix_list[0]
for matrix in matrix_list:
new_matrix = new_matrix.add_tropical_matrix(matrix)
return new_matrix
def get_polynomial_representation(coefficient_list):
term_list = [str(coefficient_list[0])]
for i in range(1, len(coefficient_list)):
term_list.append(str(coefficient_list[i]) + "x^" + str(i))
return " + ".join(term_list)
def generate_key(public_term, public_matrix_a, public_matrix_b, private_poly_a, private_poly_b):
p_1A = evaluate_polynomial(public_matrix_a, private_poly_a)
p_2B = evaluate_polynomial(public_matrix_b, private_poly_b)
left_term = p_1A.mult_tropical_matrix(public_term)
return left_term.mult_tropical_matrix(p_2B)
if __name__ == "__main__":
p_1 = [2, 5, 3]
p_2 = [0, 9, 0, 2, 5]
A = TropicalMatrix([[3, 2], [1, -2]])
B = TropicalMatrix([[7, 1], [2, -3]])
p_1A = evaluate_polynomial(A, p_1)
p_2B = evaluate_polynomial(B, p_2)
print(p_1A)
print(p_2B)
q_1 = [0, -2, 8, 3]
q_2 = [0, 0, 0]
q_1A = evaluate_polynomial(A, q_1)
q_2B = evaluate_polynomial(B, q_2)
print(q_1A)
print(q_2B)
print(A.mult_tropical_matrix(B))
print(B.mult_tropical_matrix(A))
alice_public_term = p_1A.mult_tropical_matrix(p_2B)
print(alice_public_term)
bob_public_term = q_1A.mult_tropical_matrix(q_2B)
print(bob_public_term)
print(generate_key(bob_public_term, A, B, p_1, p_2))
print(generate_key(alice_public_term, A, B, q_1, q_2))
|
46dd13daf20eae469285d583be1864a9dd6cc373 | aksharanigam1112/MachineLearningIITK | /packageML01/Practical30.py | 185 | 3.6875 | 4 | #Arbitrary Argument List
def disp1(*arr):
print("type(arr) = " , type(arr) , arr)
for num in arr:
print(num)
print("\n")
disp1(5,6,7,8)
disp1(2,3)
disp1()
disp1(9)
|
be0136e6fc715290143246e8f510b91df4ef6584 | taissalomao/curso_em_video | /exer_019.py | 371 | 4.09375 | 4 | # um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e escreevendo o nome escolhido.
import random
a1 = input("noem do aluno ")
a2 = input("nome do aluno ")
a3 = input("nome do aluno ")
a4 = input("nome do aluno ")
lista = [a1,a2,a3,a4]
print(f'O aluno escolhido foi', random.choice(lista)) |
519448917781c391a653f4218f306c6da2fba967 | sujith1919/TCS-Python | /classroom examples/2.py | 197 | 4.03125 | 4 | count = 0
while count < 10:
print(count)
if count % 2 == 0:
print("Even")
elif count % 2 == 1:
print("Odd")
else:
pass
count+=1
print("Done")
|
d6de9f8da0183a535ca750f926bead94f6a27a89 | sinayanaik/nand-and-tetris | /chapter 1/boolean_or.py | 384 | 4.09375 | 4 | # input 2 variables only 1 or 0
# output 0 only if both inputs are 0
import sys
def boolean_or(x:int,y:int)-> int:
if x and y not in [0,1]:
print("only 1 & 0 permittible as input")
sys.exit()
if x==y==0:
return 0
else:
return 1
x= int(input("operand x: "))
y= int(input("operand y: "))
print(f"\nboolean or({x},{y}) = {boolean_or(x,y)}") |
7018ab7bc15267394035bd6ce62f07ae625c89fd | NCRivera/Python-Crash-Course | /Chapter_3/3_5_Changing_Guest_List.py | 602 | 4.09375 | 4 | #3-5. Changing Guest List
guests = ['maria', 'celia', 'sheldy']
print("You, " + guests[0].title() + " are formally invited to my dinner, tomorrow night.")
print("You, " + guests[1].title() + " are formally invited to my dinner, tomorrow night.")
print("You, " + guests[2].title() + " are formally invited to my dinner, tomorrow night.")
new_invitee = "Rosalyn"
print("Unfortunately, " + guests[1].title() + " will not be coming so I will now invite " + new_invitee + ".")
guests[1] = new_invitee
print("You, " + guests[1].title() + " are formally invited to my dinner, tomorrow night.")
|
4c0551bb1e7303a383707b79e066ff978e1b9ce5 | Saikat2019/Python3-oop | /3static_class_methods.py | 1,558 | 3.953125 | 4 | class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, second,pay):
self.first = first
self.second = second
self.pay = pay
self.email = first + '.' + second + '@gmail.com'
Employee.num_of_emps += 1
#regular methods automatically takes the instance as first arg
def fullname(self): #it's a regular method
return '{} {}'.format(self.first,self.second)
def applyRaise(self):
self.pay = int(self.pay * self.raise_amount)
@classmethod #altering the functionality of this method
def set_raise_amt(cls,amount): #it will take the class as 1st arg
cls.raise_amount = amount #instead of instance
@classmethod # class method can be used as alternative
def from_string(cls,emp_str): #construction as this one
first , last , pay = emp_str.split('-')
return cls(first,last,pay) # here cls is same as Employee
@staticmethod #decorator for static method
def is_workday(day): #static methods don't pass anything autometically
if day.weekday() == 5 or day.weekday() == 6 :
return False
return True
print(Employee.num_of_emps)
emp_1 = Employee('corey','schafer',20000)
emp_2 = Employee('saikat','mondal',10000)
print(Employee.num_of_emps)
Employee.set_raise_amt(1.09)
emp_str1 = 'john-doe-70000'
emp_str2 = 'steve-smith-60000'
emp_str3 = 'jane-dow-40000'
new_emp1 = Employee.from_string(emp_str1)
print(Employee.num_of_emps)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
import datetime
my_date = datetime.date(2018,9,1)
print(Employee.is_workday(my_date)) |
b9947702b74c46a84194737e12f3ad1c3d65181d | killian-mahe/the_eternal_kingdom | /characters/zombie.py | 912 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# Standard imports
import time
# Package imports
from IO import Terminal
# Internal imports
from characters import Monster
class Zombie(Monster):
def __init__(self, monster_model_file, position, life=1, speed=3):
"""Create an instance of Zombie
Arguments:
monster_model_file {str} -- Where the zombie modele file is stored
position {list} -- 2D position
Keyword Arguments:
life {int} -- Monster life (default: {1})
speed {int} -- Monster speed in px/sec (default: {3})
"""
super(Zombie, self).__init__(monster_model_file, position, life, speed)
pass
def live(self):
"""Live method
"""
if time.time() - self.last_time_move > 1/self.speed :
self.position[0] -= 1
self.last_time_move = time.time()
pass
pass |
5577a5c54e2432f2c68fc171a11470a3108938d0 | ferreirads/uri | /uri1131.py | 936 | 3.6875 | 4 | partidas = 0
ponto_inter = 0
ponto_gremio = 0
empate = 0
while True:
inter, gremio = map(int, input().split())
partidas = partidas + 1
if inter > gremio:
ponto_inter = ponto_inter + 1
elif inter < gremio:
ponto_gremio = ponto_gremio + 1
elif gremio == inter:
empate = empate + 1
print('Novo grenal (1-sim 2-nao)')
novo_grenal = int(input())
while novo_grenal != 2 and novo_grenal != 1:
print('Novo grenal (1-sim 2-nao)')
novo_grenal = int(input())
if novo_grenal == 2:
break
print('{} grenais'.format(partidas))
print('Inter:{}'.format(ponto_inter))
print('Gremio:{}'.format(ponto_gremio))
print('Empates:{}'.format(empate))
if ponto_inter > ponto_gremio:
print('Inter venceu mais')
elif ponto_inter < ponto_gremio:
print('Gremio venceu mais')
elif ponto_inter == ponto_gremio:
print('Nao houve vencedor')
|
3d08317438ce08a954e020490fffd5bdd49c19fd | jonathan-wells/teamdanio-rosalind | /scripts/ini3.py | 432 | 3.96875 | 4 | #!/usr/bin/env python3
def index_string(s, a, b, c, d):
"""Return 2 strings from s corresponding to characters a-b and c-d."""
outstring1 = s[a:b+1]
outstring2 = s[c:d+1]
return outstring1, outstring2
s = 'HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain.'
mylist = [1, 2, 3, 4, 5, 6, 100, 'hello']
print(index_string(s, 22, 27, 97, 102))
|
e3d0fa0e90b28e78b8489ad11d5ea48a5b39960c | hkj9057/backjun | /05_03.py | 270 | 3.5 | 4 | import multiprocessing
import time
start_time = time.time()
def count(name):
sum = 0
for i in range(1, 5000001):
sum += i
num_list = ['a1','a2','a3','a4']
for num in num_list:
count(num)
print("--- %s seconds ---"%(time.time() - start_time)) |
88ffe20223c7c74346535197e86f7ebb21551ce7 | Weirdeeno/lab_1_python | /Lab/Lab7/Lab7.5.py | 774 | 4.4375 | 4 | """
9. Описати рекурсивну функцію Palindrome (S) логічного типу, яка повертає True,
якщо ціле S є паліндромом (Читається однаково зліва направо і справа наліво),
і False в іншому випадку. Оператор циклу в тілі функції не використовувати.
Вивести значення функції Palindrome для п'яти даних чисел.
"""
def Palindrom(S):
if len(S) >= 2:
return (S[0] == S[-1:-2:-1]) and Palindrom(S[1:-1])
return True
for i in range(0,5):
s = input('Введите число : ')
t = s.replace(" ", "").lower()
print("Palindrom:",Palindrom(t)) |
ac552976b46c33a710fff33cb1ae61463737872d | pranavkhuranaa/DailyCodes | /Constructor/constructor.py | 447 | 4.25 | 4 | #This code implements constructors in Python 3.0
#1
class Point:
def __init__(self,x,y): #constructor
self.x=x
self.y=y
def move(self):
print('move')
def draw(self):
print('draw')
point=Point(10,20)
#point.x=11
print(point.x)
#2
class Person:
def __init__(self,name):
self.name=name
def talk(self):
print(f"Hi, I am {self.name}")
john=Person("John Smith")
john.talk()
|
baefcbd2129b05dc598bb45bed1f3108126eddd6 | sandip-tiwari/IMNN | /IMNN/network/network.py | 5,864 | 3.59375 | 4 | """Simple network builder
This module provides the methods necessary to build simple networks for use in
the information maximising neural network. It is highly recommeneded to build
your own network from scratch rather than using this blindly - you will almost
certainly get better results.
"""
__version__ = "0.1rc1"
__author__ = "Tom Charnock"
import tensorflow as tf
import numpy as np
class network():
"""Simple network builder
"""
def __init__(self, parameters):
self.layers = parameters["hidden_layers"]
self.bb = parameters["bb"]
self.activation = parameters["activation"]
def dense(self, input_tensor, l):
"""Builds a dense layer
Parameters
__________
input_tensor : :obj:`TF tensor`
input tensor to the layer
l : int
counter for the number of layers
previous_layer : int
shape of previous layer
weight_shape : tuple
shape of the weight kernel
bias_shape : tuple
shape of the bias kernel
weights : :obj:`TF tensor`
the weight kernel for the dense layer
biases : :obj:`TF tensor
the biases for the dense layer
dense : :obj:`TF tensor`
non-activated output dense layer
Returns
_______
:obj:`TF tensor`
activated output from the dense layer
"""
previous_layer = int(input_tensor.get_shape().as_list()[-1])
weight_shape = (previous_layer, self.layers[l])
bias_shape = (self.layers[l])
weights = tf.get_variable("weights", weight_shape,
initializer=tf.variance_scaling_initializer(
))
biases = tf.get_variable("biases", bias_shape,
initializer=tf.constant_initializer(self.bb))
dense = tf.add(tf.matmul(input_tensor, weights), biases)
return self.activation(dense, name='dense_' + str(l))
def conv(self, input_tensor, l):
"""Builds a dense layer
Parameters
__________
input_tensor : :obj:`TF tensor`
input tensor to the layer
l : int
counter for the number of layers
previous_filters : int
number of filters in the previous layer
weight_shape : tuple
shape of the weight kernel
stride_shape : list
the size of strides to make in the convolution
bias_shape : tuple
shape of the bias kernel
weights : :obj:`TF tensor`
the weight kernel for the dense layer
biases : :obj:`TF tensor
the biases for the dense layer
dense : :obj:`TF tensor`
non-activated output dense layer
Returns
_______
:obj:`TF tensor`
activated output from the dense layer
"""
previous_filters = int(input_tensor.get_shape().as_list()[-1])
if len(self.layers[l][1]) == 1:
convolution = tf.nn.conv1d
weight_shape = (self.layers[l][1][0], previous_filters,
self.layers[l][0])
stride_shape = self.layers[l][2][0]
elif len(self.layers[l][1]) == 2:
convolution = tf.nn.conv2d
weight_shape = (self.layers[l][1][0], self.layers[l][1][1],
previous_filters, self.layers[l][0])
stride_shape = [1] + self.layers[l][2] + [1]
else:
convolution = tf.nn.conv3d
weight_shape = (self.layers[l][1][0], self.layers[l][1][1],
self.layers[l][1][2], previous_filters,
self.layers[l][0])
stride_shape = [1] + self.layers[l][2] + [1]
bias_shape = (self.layers[l][0])
weights = tf.get_variable("weights", weight_shape,
initializer=tf.variance_scaling_initializer(
))
biases = tf.get_variable("biases", bias_shape,
initializer=tf.constant_initializer(self.bb))
conv = tf.add(convolution(input_tensor, weights, stride_shape,
padding=self.layers[l][3]), biases)
return n.activation(conv, name='conv_' + str(l))
def build_network(self, input_tensor):
"""Construct a simple network for the IMNN
Parameters
__________
input_tensor : :obj:`TF tensor`
input tensor to the network
layer : :obj:`list` of :obj:`TF tensor`
a list containing each output of the previous layer
Returns
_______
"""
layer = [input_tensor]
for l in range(1, len(self.layers)):
if type(self.layers[l]) == list:
if len(layer[-1].get_shape(
).as_list()) < len(self.layers[l]) - 1:
layer.append(
tf.reshape(
layer[-1], [-1] + layer[-1].get_shape(
).as_list()[1:] +
[1 for i in range(
len(self.layers[l])
- len(layer[-1].get_shape().as_list()) - 1)]))
with tf.variable_scope('layer_' + str(l)):
layer.append(self.conv(layer[-1], l, drop_val))
else:
if len(layer[-1].get_shape()) > 2:
layer.append(
tf.reshape(
layer[-1], (-1, np.prod(layer[-1].get_shape(
).as_list()[1:]))))
with tf.variable_scope('layer_' + str(l)):
layer.append(n.dense(layer[-1], l, drop_val))
return layer[-1]
|
544310f3ef050399b88087c324c314fd0333e7c5 | mhee4321/python_basic | /matplotlib_examples/group_bar_plot.py | 2,293 | 3.515625 | 4 | #Group Bar Plot In MatPlotLib
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'pre_score': [4, 24, 31, 2, 3],
'mid_score': [25, 94, 57, 62, 70],
'post_score': [5, 43, 23, 23, 51]}
df = pd.DataFrame(raw_data, columns = ['first_name', 'pre_score', 'mid_score', 'post_score'])
# Setting the positions and width for the bars
pos = list(range(len(df['pre_score'])))
width = 0.25
# Plotting the bars
fig, ax = plt.subplots(figsize=(10,5))
# Create a bar with pre_score data,
# in position pos,
plt.bar(pos,
#using df['pre_score'] data,
df['pre_score'],
# of width
width,
# with alpha 0.5
alpha=0.5,
# with color
color='#EE3224',
# with label the first value in first_name
label=df['first_name'][0])
# Create a bar with mid_score data,
# in position pos + some width buffer,
plt.bar([p + width for p in pos],
#using df['mid_score'] data,
df['mid_score'],
# of width
width,
# with alpha 0.5
alpha=0.5,
# with color
color='#F78F1E',
# with label the second value in first_name
label=df['first_name'][1])
# Create a bar with post_score data,
# in position pos + some width buffer,
plt.bar([p + width*2 for p in pos],
#using df['post_score'] data,
df['post_score'],
# of width
width,
# with alpha 0.5
alpha=0.5,
# with color
color='#FFC222',
# with label the third value in first_name
label=df['first_name'][2])
# Set the y axis label
ax.set_ylabel('Score')
# Set the chart's title
ax.set_title('Test Subject Scores')
# Set the position of the x ticks
ax.set_xticks([p + 1.5 * width for p in pos])
# Set the labels for the x ticks
ax.set_xticklabels(df['first_name'])
# Setting the x-axis and y-axis limits
plt.xlim(min(pos)-width, max(pos)+width*4)
plt.ylim([0, max(df['pre_score'] + df['mid_score'] + df['post_score'])] )
# Adding the legend and showing the plot
plt.legend(['Pre Score', 'Mid Score', 'Post Score'], loc='upper left')
plt.grid()
plt.show() |
5b3a4ffedae758a88f2efcdaf82383d5235c492e | AJoh96/BasicTrack_Alida_WS2021 | /Week40/4.9.5.py | 218 | 3.671875 | 4 | import turtle
window = turtle.Screen()
window.bgcolor("lightgreen")
finn = turtle.Turtle()
finn.color('blue')
for x in range(100):
finn.forward(x * 5)
finn.right(90)
#finn.right(89)
window.mainloop()
|
56f76b7644b0f770cef0bfc52c466b00efd081bb | gunjan1991/CSC-455---Assignments | /Assignment 6 - Gunjan - Part 4 Solution.py | 885 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 09:53:17 2016
@author: gunjan
"""
# Assignment: 6
# Name: Gunjan Pravinchandra Pandya
# Part: 4
import sqlite3
# Open a connection to database
conn = sqlite3.connect("ChaufferDatabase.db") #Should be the database to which table belongs to
# Request a cursor from the database
cursor = conn.cursor()
def generateInsertStatements(table):
allSelectedRowsTweet = cursor.execute("SELECT * FROM " + table + ";").fetchall()
text_file = open("C:\Gunjan DePaul\CSC 455\Segment 6\InsertStatements.txt", "w")
for i in range( len( allSelectedRowsTweet ) ):
text_file.write("%s;\n" % ("INSERT INTO " + table + " VALUES " + str(allSelectedRowsTweet[i])))
#print("%s; \n" % ("INSERT INTO " + table + " VALUES " + str(allSelectedRowsTweet[i])))
generateInsertStatements('DRIVER') |
5b050974294599808516b3b1c7d173452c0424c6 | iWeslie/AlgorithmPlayground | /LeetCode/Python/141.linked-list-cycle.py | 602 | 3.71875 | 4 | #
# @lc app=leetcode id=141 lang=python
#
# [141] Linked List Cycle
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
p1 = p2 = head
if not head or not head.next:
return False
while p1 and p2 and p2.next:
p1 = p1.next
p2 = p2.next.next
if p1 == p2:
return True
return False
|
e680b7e421ea2ef55c7f2aa35d8d4bc0587f3099 | euyouer/python-cev | /curso-aula_em_video/Ex 088 - Palpites para a Mega Sena.py | 619 | 3.53125 | 4 | from random import randint
from time import sleep
print('\033[1;31m*\033[m' * 25)
print('JOGA NA MEGA SENA'.center(25))
print('\033[1;31m*\033[m' * 25)
game = list()
ans = int(input('Quantos jogos você quer que eu sorteie? '))
print(f'-=-=-=- SORTEANDO {ans} JOGOS -=-=-=-')
for n in range(ans):
aux = list()
while True:
numero = randint(1, 60)
if numero not in aux:
aux.append(numero)
if len(aux) == 6:
break
aux.sort()
game.append(aux)
print(f'Jogo {n + 1}: {game[n]}')
sleep(1)
aux.clear()
print('-=-=-=-=-=- < BOA SORTE! > -=-=-=-=-=-')
|
6289aa5aed46a293aacbab300062a0f5002de8ce | PalMassimo/AdvancedProgrammingProject | /Python/reverse_module.py | 274 | 3.5625 | 4 | def reverse_dictionary(d):
rd = dict()
for elem in set([value for values_list in d.values() for value in values_list]):
rd[elem] = list(set([key for key, value in d.items()
for list_elem in value if elem == list_elem]))
return rd
|
caf0bbef0996e7a25b8def0aa19d07e1ec44cbc7 | kristenscheuber/CP1404 | /prac_02/file.py | 1,602 | 4.125 | 4 | '''
Do all of the following in a single file called files.py:
1. Write a program that asks the user for their name, then opens a file called “name.txt” and writes that
name to it.
2. Write a program that opens “name.txt” and reads the name (as above) then prints,
“Your name is Bob” (or whatever the name is in the file).
3. Create a text file called “numbers.txt” (You can create a simple text file in PyCharm with Ctrl+N, choose
“File” and save it in your project). Put the numbers 17 and 42 on separate lines in the file and save it:
17
42
Write a program that opens “numbers.txt”, reads the numbers and adds them together then prints the
result, which should be… 59.
4. Extended (perhaps only do this if you’re cruising… if you are struggling, just read the solution) …
Now extend your program so that it can print the total for a file containing any number of numbers.
'''
#Task 1 - Ask for the users name and write it to the file.
out_file = open("name.txt", 'w')
user_name = input("Your Name: ")
print('{}'.format(user_name), file=out_file)
out_file.close()
#Task 2 - Read the users name and output this in a string.
out_file = open("name.txt", 'r')
for line in out_file:
print("Your Name is", line)
#Task 3 - Create a numbers file and write two numbers two it
number_file = open("numbers.txt", 'w')
number_file.write("17\n")
number_file.write("42\n")
number_file.close()
number_file = open("numbers.txt", 'r')
number_1 = int(number_file.readline())
number_2 = int(number_file.readline())
total = number_1 + number_2
print(total)
number_file.close()
|
702d2b230f02a98258cb6cf4c820f9ee5b62dd48 | GSAUC3/turtle-graphics | /poly_kwargs.py | 509 | 3.890625 | 4 | import turtle
class poly:
def __init__(self,**k) -> None:
self.side=k['side']
self.size=k['size']
self.color=k['color']
self.interior_angles=(self.side-2)*180
self.angle=self.interior_angles/self.side
def draw(self):
turtle.color(self.color)
for i in range(self.side):
turtle.forward(self.size)
turtle.right(180-self.angle)
turtle.done()
# poly(side,size,color)
sq=poly(side=6,size=100,color='red')
sq.draw()
|
0df7b84dc63ddbc80f77c53ee5e55ac7072b53e7 | Aasthaengg/IBMdataset | /Python_codes/p03377/s819525040.py | 93 | 3.59375 | 4 | cat, animal, just = map(int, input().split())
print("YES" if cat<=just<=cat+animal else "NO") |
43ee1473816a78d636a04923fdca4a04da569c38 | onuryarartr/trypython | /odev1.py | 469 | 4.21875 | 4 | """Problem 1
Kullanıcıdan aldığınız 3 tane sayıyı çarparak ekrana yazdırın. Ekrana yazdırma işlemini format metoduyla yapmaya çalışın."""
print("Merhaba, lütfen istenen değerleri girin..")
s1 = int(input("Sayı 1:"))
s2 = int(input("Sayı 2:"))
s3 = int(input("Sayı 3:"))
print("İşlem yapılıyor...")
sonuc = s1 * s2 * s3
print("İşlem Sonucu: {}".format(sonuc))
print("Programı kullandığınız için teşekkürler...")
|
2e71ab038509eed47cec6f27e0b90af17ede36b8 | penguin138/ctc_convolutions | /prettify_syllables.py | 2,194 | 3.703125 | 4 | #! /usr/bin/env python3
"""Wiktionary syllables prettifier."""
import re
import sys
import pandas as pd
def check_ru(x, axis):
"""Check whether string contains only russian alphabetic characters."""
alphabet = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
alphabet = alphabet + alphabet.lower() + 'и́о́а́ы́я́е́у́ю́э́- '
for ch in list(x.lower()):
if ch not in alphabet:
return False
return True
def remove_forbidden_chars(str_, axis=0):
"""Remove forbidden characters from string."""
forbidden_chars = ('\u0301\u0300\u0340\u0341' +
'.!:;,?@#$%^&*œ∑´®†¥¨ˆøπ“‘åß©˙∆˚¬…æ«Ω≈çµ≤≥÷')
forbidden_chars = forbidden_chars + ''.join(map(str, range(10)))
return ''.join([ch for ch in str_ if (ch not in forbidden_chars)])
def normal_syllables(row, axis=1):
"""Keep only normal syllable alignments.
Remove syllables when their quantity differs from number of vowels in word.
"""
tokens = re.split(r'\s*?\|\s*?', row[1])
vowels = r'[аеёоуиэюяы]'
for token in tokens:
syllables = re.split('\s+', token)
found_vowels = re.findall(vowels, row[0])
if len(found_vowels) == len(syllables):
return ' '.join(syllables)
return None
def check_lengths(row, axis=1):
"""Check if number of letters in syllables equals that number in word."""
syllables = re.split('\s+', row[1].strip())
if len(row[0]) != len(''.join([s for s in syllables if s != ''])):
return False
return True
def prettify(filename, out_filename="normal_syllables.txt"):
"""Prettify syllables from Wiktionary."""
data = pd.read_table(filename, names=['word', 'syllables'])
data = data.dropna()[data['word'].apply(check_ru, axis=1)]
data['syllables'] = data['syllables'].apply(remove_forbidden_chars, axis=1)
data['syllables'] = data.apply(normal_syllables, axis=1)
data = data.dropna()
data = data[data.apply(check_lengths, axis=1)]
data.to_csv(out_filename, index=False, sep='\t')
if __name__ == '__main__':
prettify(sys.argv[1], sys.argv[2])
|
aaeefc6b7013002144d92522faf7da514d1bcc7a | arslanaarslan/Hangman | /Topics/Loop control statements/Prime number/main.py | 386 | 4.1875 | 4 | number = int(input())
is_prime = False
divider = 2
while divider <= number:
if number == divider:
is_prime = True
break
if number == 2:
is_prime = True
break
if number % divider == 0:
break
divider += 1
if is_prime:
print("This number is prime")
else:
print("This number is not prime")
|
d6d7a8b6fbae97ccbde88f81d388beb02408a368 | SergioKuk/sk-repo | /Proj_1/stepik_2020-09.py | 5,837 | 3.84375 | 4 |
#==================================================================================================================
# 2.5 Списки
#==================================================================================================================
'''
Напишите программу, на вход которой подается одна строка с целыми числами. Программа должна вывести сумму этих чисел.
Используйте метод split строки.
'''
def list_example_1():
a = [int(i) for i in input().split()]
s=0
for i in a:
s += i
print (s)
return 0
#==================================================================================================================
'''
Напишите программу, на вход которой подаётся список чисел одной строкой.
Программа должна для каждого элемента этого списка вывести сумму двух его соседей.
Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка.
Например, если на вход подаётся список "1 3 5 6 10", то на выход ожидается список "13 6 9 15 7" (без кавычек).
Если на вход пришло только одно число, надо вывести его же.
Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.
'''
def list_example_2():
st = [int(i) for i in input().split()]
for i in range(len(st)):
if len(st)==1:
print (st[i])
elif i==(len(st)-1):
print (st[i-1]+st[0])
else:
print (st[i-1]+st[i+1])
return 0
#==================================================================================================================
'''
Напишите программу, которая принимает на вход список чисел в одной строке и выводит на экран в одну строку значения,
которые встречаются в нём более одного раза.
Для решения задачи может пригодиться метод sort списка.
Выводимые числа не должны повторяться, порядок их вывода может быть произвольным.
'''
def list_example_3():
st = [int(i) for i in input().split()]
st.sort()
x = st[0]
i = 1
l = len(st)
while i<l:
if st[i] == x:
while st[i] == x and i<l-1:
i += 1
print (x,end=' ')
x = st[i]
i += 1
return 0
#==================================================================================================================
# 2.6 Задачи по материалам раздела 2
#==================================================================================================================
'''
Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк,
заканчивающихся строкой, содержащей только строку "end" (без кавычек)
Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j равен сумме
элементов первой матрицы на позициях (i-1, j), (i+1, j), (i, j-1), (i, j+1). У крайних символов соседний
элемент находится с противоположной стороны матрицы.
В случае одной строки/столбца элемент сам себе является соседом по соответствующему направлению.
'''
def sec_26_1():
j = 0
k = 0
a = []
while j>=0:
st = [i for i in input().split()]
if st[0] == 'end':
j = -1
else:
# for i in range(len(st)):
# st[i] = int(st[i])
st = [int(i) for i in st]
a.append(st)
# print (st)
# print (a)
j += 1
# print (a)
n = len(a)
k = len(a[0])
b = []
# print (n,k)
for i in range (n):
c = []
for j in range (k):
x1 = i-1
x2 = i+1
y1 = j-1
y2 = j+1
if i == 0:
x1 = n-1
if i == n-1:
x2 = 0
if j == 0:
y1 = k-1
if j == k-1:
y2 = 0
# print (x1,x2,y1,y2)
# c.append (a[x1][j]+a[x2][j]+a[i][y1]+a[i][y2])
c += [a[x1][j]+a[x2][j]+a[i][y1]+a[i][y2]]
print (c[j],end=' ')
b.append (c)
print ()
# print (b)
return 0
#==================================================================================================================
print('Списки. Примеры:')
print('1. Пример 1')
print('2. Пример 2')
print('3. Пример 3')
print('Задачи по разделу 2:')
print('4. Сумма соседних элементов матрицы')
print("\nВыберите пункт или нажмите любую буквенную клавишу для выхода...")
sec_26_1()
|
ca4f3b12a43c4e2916704d59982c6cd091590b19 | janvanzeghbroeck/zombie_dice | /game_bits.py | 2,514 | 3.6875 | 4 | import numpy as np
## constants
n_green_dice = 6
n_yellow_dice = 4
n_red_dice = 3
# the distibution of the sides on each colored die
green_dice = ['brain','brain','brain','feet','feet','shot']
yellow_dice = ['brain','brain','feet','feet','shot','shot']
red_dice = ['brain','feet','feet','shot','shot','shot']
class Dice(object):
'''
A zombie dice of a color with corresponding hard coded distribution of brains, feets, shots for the sides
you can roll the dice
'''
def __init__(self, color):
if color == 'green':
self.sides = green_dice
elif color == 'yellow':
self.sides = yellow_dice
elif color == 'red':
self.sides = red_dice
self.color = color
def __repr__(self):
''' dice are represented by their color '''
return self.color
def roll(self):
''' returns a random single side of the die '''
return np.random.choice(self.sides,1)[0]
class Jar(object):
'''
The jar holds the dice. dice are randomly pulled from the jar
you can check the number and colors of any remaining dice in the jar
you can shake the jar to shuffel the dice
'''
def __init__(self, greens=n_green_dice, yellows=n_yellow_dice, reds=n_red_dice):
self.dice = np.hstack([
[Dice('green') for _ in range(greens)],
[Dice('yellow') for _ in range(yellows)],
[Dice('red') for _ in range(reds)]])
def num_color(self, color):
''' returns the number of the given color in ('green', 'yellow', 'red')'''
return len([d for d in self.dice if d.color == color])
def __repr__(self):
'''prints how many dice are left in the bag'''
return '{} green | {} yellow | {} red'.format(
self.num_color('green'),
self.num_color('yellow'),
self.num_color('red'))
def shake(self):
''' shuffles the order of the dice'''
self.dice = np.random.choice(self.dice,len(self.dice),replace = False)
def get_dice(self, n=3):
''' removes and returns n dice from the jar at random '''
self.shake()
gotten_dice = []
for i in range(n):
if len(self.dice)>0:
gotten_dice.append(self.dice[0])
self.dice = self.dice[1:]
return gotten_dice
def add_dice(self, dice_list):
''' adds a list of dice to the jar '''
self.dice = np.hstack([self.dice, dice_list])
if __name__ == '__main__':
jar = Jar()
|
20198d30d02238a019306c693f741d4e545fa58c | MFTECH-code/checkpoint02-cpt | /ZenGroup.py | 3,408 | 3.828125 | 4 | # CHECKPOINT 2 CPT
#quantidade de Pratos Principais
pratosPrincipais = int(input("Quantos pratos principais: "))
while (pratosPrincipais <= 0):
print("Número de pratos principais inválido. Digite novamente.")
pratosPrincipais = int(input("Quantos pratos principais: "))
if (pratosPrincipais > 3):
descontoPratos = 0.04
else:
descontoPratos = 0
#Valor total da nota
valorTotalNota = float(input("Valor total da nota: R$"))
while (valorTotalNota <= 0):
print("Valor inválido. Digite novamente.")
valorTotalNota = float(input("Valor total da nota: R$"))
if (valorTotalNota > 500):
descontoTotalNota = 0.06
else:
descontoTotalNota = 0
#Cupom de desconto
temCupom = input("Tem cupom[S/N]: ").upper()
while (temCupom != "S" and temCupom != "N"):
print("Cupom inválido..., Digite 'S' ou 'N'...")
temCupom = input("Tem cupom[S/N]: ").upper()
if (temCupom == "S"):
codCupom = input("Digite o código do cupom: ").upper()
while (codCupom != "BORALA10" and codCupom != "BORALA05"):
print("Cupom inválido...")
continuar = input("Deseja tentar outro código?[S/N]: ").upper()
while (continuar != "S" and continuar != "N"):
print("Inválido... Digite 'S' ou 'N'...")
continuar = input("Deseja tentar outro código?[S/N]: ").upper()
if (continuar == "S"):
codCupom = input("Digite o código do cupom: ").upper()
else:
cupom = 0
break
if (codCupom == "BORALA10"):
cupom = 0.1
elif (codCupom == "BORALA05"):
cupom = 0.05
else:
print("Sem cupom.")
cupom = 0
primeiraVez = input("É a primeira vez no restaurante[S/N]? ").upper()
while (primeiraVez !="S" and primeiraVez != "N"):
print("Valor inválido. Digite novamente.")
primeiraVez = input("É a primeira vez no restaurante[S/N]? ").upper()
if (primeiraVez == "S"):
descontoPrimeiraVez = 0.05
else:
descontoPrimeiraVez = 0
descontosTotal = descontoPratos + descontoPrimeiraVez + descontoTotalNota + cupom
if (descontosTotal == 0):
valorFinal = valorTotalNota
else:
valorFinal = valorTotalNota - ( valorTotalNota * descontosTotal )
racharConta = input("Deseja rachar a conta[S/N]: ").upper()
while (racharConta != "S" and racharConta != "N"):
print("Inválido... Digite 'S' ou 'N'...")
racharConta = input("Deseja rachar a conta[S/N]? ")
if (racharConta == "S"):
qtdPessoas = int(input("Deseja dividir a conta em quantas pessoas: "))
valorRachado = valorFinal / qtdPessoas
print('-' * 50)
if (descontosTotal <= 0):
print(f"Valor total da nota fiscal: R${valorTotalNota:.2f}")
print(f"Não tiveram descontos.")
print(f"\nNúmero de pessoas: {qtdPessoas}")
print(f"Total por pessoa: R${valorRachado:.2f}")
else:
print(f"Valor total da nota fiscal: R${valorTotalNota:.2f}")
print(f"Valor total da nota com desconto: R${valorFinal:.2f}")
print(f"\nNúmero de pessoas: {qtdPessoas}")
print(f"Total por pessoa: R${valorRachado:.2f}")
print('-' * 50)
else:
print('-' * 50)
if (descontosTotal <= 0):
print(f"Valor total da nota fiscal: R${valorTotalNota:.2f}")
else:
print(f"Valor total da nota fiscal: R${valorTotalNota:.2f}")
print(f"Valor total da nota com desconto: R${valorFinal:.2f}")
print('-' * 50) |
be3afe48729bb126c0730e8c3dc6dbd743868283 | Praveen-bbps/python_basic_examples | /mutable_demo.py | 470 | 3.671875 | 4 | # Strings are immutable
a="bbps"
print(a[2])
# make the below line comment to remove the error
a[2]="q"
# lists are mutable
months=["jan","feb","mar"]
print(months[2])
months[2]="apr"
print(months[2])
myscore=[20,15,80,25,90]
myname=["bbps", "school",25]
# ascending order
print(sorted(myscore))
# decending order
print(sorted(myscore,reverse=True))
# make the below line comment to remove the error
print(min(myname))
print(min(myscore))
|
3fa696abaaa3db0b3241f4c52c6807d394ad6d17 | QuantumKane/statistics-exercises | /probability_distributions.py | 4,853 | 4.0625 | 4 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from env import host, user, password
# 1 A bank found that the average number of cars waiting during the noon hour at a drive-up window follows a Poisson distribution with a mean of 2 cars. What is the probability that no cars drive up in the noon hour?
λ = 2
stats.poisson(λ).pmf(0)
# Answer is 0.1353352832366127
# What is the probability that 3 or more cars come through the drive through?
λ = 2
stats.poisson(λ).sf(2)
# Answer is 0.32332358381693654
# How likely is it that the drive through gets at least 1 car?
λ = 2
1 - stats.poisson(λ).pmf(0)
# Answer is 0.8646647167633873
# simulation
λ = 2
x = np.arange(0,10)
y = stats.poisson(λ).pmf(x)
plt.bar(x,y, width = 0.9)
plt.xlabel('Number of Cars')
plt.ylabel('probability P(X)')
plt.xticks(np.arange(0,10,1))
plt.title('Poisson distrbution with $\lambda$ = 2', fontsize = 14);
# 2 Grades of State University graduates are normally distributed with a mean of 3.0 and a standard deviation of .3. Calculate the following: What grade point average is required to be in the top 5% of the graduating class?
mean = 3
sd = .3
grades = stats.norm(mean, sd)
grades.isf(0.05)
# What GPA constitutes the bottom 15% of the class?
grades = stats.norm(mean, sd)
grades.ppf(0.15)
# simulation
np.quantile(np.random.normal(3, 0.3, 10_000), 0.15)
# An eccentric alumnus left scholarship money for students in the third decile from the bottom of their class. Determine the range of the third decile. Would a student with a 2.8 grade point average qualify for this scholarship?
stats.norm(3, .3).ppf([.2,.3])
# simulation
np.quantile(np.random.normal(3, 0.3, 10_000), [0.2, 0.3])
# If I have a GPA of 3.5, what percentile am I in?
stats.norm(3, .3).cdf(3.5)
# simulation
(np.random.normal(3, 0.3, 10_000) < 3.5).mean()
# 3 A marketing website has an average click-through rate of 2%. One day they observe 4326 visitors and 97 click-throughs. How likely is it that this many people or more click through?
n_trials = 4326
prob = 0.02
stats.binom(n_trials, prob).sf(96)
# simulation
clicks = np.random.choice([0,1], (100_000, 4326), p = [0.98, 0.02])
# 4 You are working on some statistics homework consisting of 100 questions where all of the answers are a probability rounded to the hundreths place. Looking to save time, you put down random probabilities as the answer to each question. What is the probability that at least one of your first 60 answers is correct?
n_trials = 60
prob = .01
stats.binom(n_trials, prob).sf(0)
# simulation
answers = np.random.choice([0,1], (10_000, 60), p = [0.99, 0.01])
# 5 Suppose that there's a 3% chance that any one student cleans the break area when they visit it, and, on any given day, about 90% of the 3 active cohorts of 22 students visit the break area. How likely is it that the break area gets cleaned up each day?
n_trials = 59
prob = .03
stats.binom(n_trials, prob).sf(0)
# How likely is it that it goes two days without getting cleaned up?
stats.binom(n_trials * 2, prob).pmf(0)
# All week?
stats.binom(n_trials * 5, prob).pmf(0)
# simulation
x = np.arange(0,9)
y = stats.binom(n, p).pmf(x)
plt.bar(x,y, width = 0.9)
plt.xlabel('Number of times area is cleaned per day')
# 6 You want to get lunch at La Panaderia, but notice that the line is usually very long at lunchtime. After several weeks of careful observation, you notice that the average number of people in line when your lunch break starts is normally distributed with a mean of 15 and standard deviation of 3. If it takes 2 minutes for each person to order, and 10 minutes from ordering to getting your food, what is the likelihood that you have at least 15 minutes left to eat your food before you have to go back to class? Assume you have one hour for lunch, and ignore travel time to and from La Panaderia.
mean = 30
sd = 6
stats.norm(mean, sd).cdf(35)
# simulation
(np.random.normal(30, 6, 100_000) < 35).mean()
# 7 Connect to the employees database and find the average salary of current employees, along with the standard deviation. For the following questions, calculate the answer based on modeling the employees salaries with a normal distribution defined by the calculated mean and standard deviation then compare this answer to the actual values present in the salaries dataset.
# What percent of employees earn less than 60,000?
mean_df = df.salary.mean()
sd_df = df.salary.std()
mean_df, sd_df
stats.norm(mean_df, sd_df).cdf(60000)
# What percent of employees earn more than 95,000
stats.norm(mean_df, sd_df).sf(95000)
# What percent of employees earn between 65,000 and 80,000?
stats.norm(mean_df, sd_df).sf(65000) - stats.norm(mean_df, sd_df).sf(80000)
# What do the top 5% of employees make?
stats.norm(mean_df, sd_df).isf(0.05) |
d6d48b86ee1f3203e6a9e16291a0d0925635e1dd | CastleWhite/LeetCodeProblems | /92.py | 636 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
dummy = ListNode(0, head)
newbegin = dummy
for i in range(left-1):
newbegin = newbegin.next
tmphead = newbegin.next
for i in range(right-left):
lasthead = tmphead.next
newbegin.next, lasthead.next, tmphead.next = lasthead, newbegin.next, lasthead.next
return dummy.next
|
5d3cda86ae06ab1c5926bd0e4459e22e12e5b11b | Pradeepsuthar/pythonCode | /BasicPrograms/binary_search.py | 440 | 3.84375 | 4 | # Binary Search
a = [1,5,7,8,11,13,16]
def binary_search(a, key, start, end):
if start <= end:
mid = int((start+end)/2)
if a[mid] > key:
return binary_search(a, key, start, mid-1)
elif a[mid] < key:
return binary_search(a, key, mid+1,end)
else:
print(key,"is found")
else:
print(key,"not found")
print(binary_search(a, 19,0, len(a)-1))
|
60b43a72356f7f93ba251381bdab9ddde3c1cf7e | Keonhong/IT_Education_Center | /Jumptopy/Codding_Test/Theater.py | 617 | 3.859375 | 4 | #영화관 티켓 판매기
while True:
print("안녕하세요. IT영화관을 찾아주셔서 감사합니다.")
a = int(input("나이를 입력하세요: (-1 종료)"))
if a < 3 and a > 0:
print("%s세의 입장료는 무료입니다. 감사합니다."% a)
continue
if a >= 3 and a < 13:
print("%s세의 입장료는 10달러입니다. 감사합니다."% a)
continue
if a >= 13:
print("%s세의 입장료는 15달러입니다. 감사합니다."% a)
continue
else:
a == -1
print("프로그램을 종료합니다.")
break |
ff015f3ea57661249e54e7c2b58d495b8abe9306 | jcarball/python-programs | /examen.py | 437 | 3.84375 | 4 | i=2
while i >= 0:
print("*")
i-=2
for n in range(-1, 1):
print("%")
z=10
y=0
x=z > y or z==y
lst=[3,1, -1]
lst[-1] = lst[-2]
print(lst)
vals = [0,1,2]
vals[0], vals[1] = vals[1], vals[2]
print(vals)
nums=[]
vals = nums
vals.append(1)
print(nums)
print(vals)
nums=[]
vals = nums[:]
vals.append(1)
print(nums)
print(vals)
lst = [0 for i in range(1, 3)]
print(lst)
lst = [0,1,2,3]
x=1
for elem in lst:
x*=elem
print(x) |
c3857ae5f2dfd19fab3eef8691cc6ef1a9ed4b56 | thientt03/C4E26 | /C4E26/Session3/while_intro.py | 148 | 3.84375 | 4 | loop_count = 0
loop = True
while True:
print("Running...")
loop_count += 1
print(loop_count)
if loop_count > 2:
loop = False |
740712f8d0eaa2f72d590b9c6caf130419e97e4c | arpankbasak/pymol-animations | /tutorials/basics/01-moviesetup.py | 1,433 | 3.671875 | 4 | __author__ = 'sebastians'
# PyMOL Animation Tutorials -- 01 - Movie Setup
# This tutorial will show you how to set up a python script for writing an PyMOL animation.
# To start PyMOL from a python script, import the pymol modules
import pymol
from pymol import cmd
# The next line is essential to prevent any threading errors. Call this function before using any PyMOl methods!
pymol.finish_launching()
# Next, we configure some global settings which are needed for our movies.
cmd.set('scene_buttons', 1) # This installs scene buttons to switch between scenes
cmd.set('matrix_mode', 1) # This sets up a mode needed for animations.
cmd.set('movie_panel', 1) # This setting shows a slider to interactively move between frames
# Finally, we have to think about the length and quality of our animation
cmd.mset("1 x500") # How many frames do we need?. 500 frames are enough for a 20 seconds video with 25 frames/second
cmd.set('ray_trace_frames', 1) # Should the frames be ray-traced? If yes, rendering will take longer, but look nicer.
cmd.viewport(800, 800) # Choose the desired resolution for the movie here (in pixels).
# Launching this script with Python should invoke PyMOL and show a black screen with everything set up for a movie.
# Note that in the cmd.mset() command we don't care about the first number, which has to do with the
# ratio of states and frames in the movie. Let's leave it at '1' for the moment. |
935e42f3c05449ef92c6d49e8c73ba366cff4d7c | joshtsengsh/Learn-Coding-with-Python | /07. Math/math2.py | 722 | 4.34375 | 4 | #Created by Josh Tseng, 5 May 2020
#This file shows you some concepts related to performing math calculations in Python using float values
#Note that num1 is a float value, and num2 is an int value
num1 = 5.0
num2 = 10
#All calculations involving float values will result in a float value being produced
print("Addition:")
result = num1 + num2
print(result)
print(type(result))
print("---")
print("Subtraction:")
result = num1 - num2
print(result)
print(type(result))
print("---")
print("Multiplication:")
result = num1 * num2
print(result)
print(type(result))
print("---")
print("Division:")
result = num1 / num2
print(result)
print(type(result))
print("---")
result = num2 / num1
print(result)
print(type(result))
|
4bbb11c54c029b2c28fad0c0b6991d865cb99276 | kkdai/python_learning | /input_check.py | 480 | 3.828125 | 4 |
def is_input_number(any_input):
try:
val = int(any_input)
return True
except ValueError:
return False
def is_input_string(any_input):
'''
Any input could be string, so this always be True
'''
try:
val = str(any_input)
return True
except ValueError:
return False
print is_input_number("222") #True
print is_input_number("22a") #False
print is_input_string(222) #True
print is_input_string("22") #True
|
3e4161da89e1161f7a8e933eebf6701e35766d2f | dewanhimanshu/Python | /practical.py | 707 | 4.0625 | 4 | def pattern1(n,patternType):
"""[To print a pattern 1 ]
Args:
n ([int]): [number of rows]
patternType
"""
if patternType == '1':
count = 1
for i in range(1,n+1):
for j in range(1,i+1):
print(count*count,end=' ')
count = count + 1
print()
elif patternType == '2':
for i in range(1,n+1):
for j in range(1,i+1):
print(i,end='')
print()
else:
print("Wrong Input")
n = int(input("ENter the number of rows for pattern :"))
patternType = input("Enter the patter type(Valid input is 1 and 2 only:")
pattern1(n,patternType)
|
4e43be9a21445b4c39b0c028365275d1e79d7969 | finchnest/Python-prac-files | /_quiz1/armstrong number.py | 207 | 3.65625 | 4 | for z in range(0,1000):
if len(str(z))==3:
n1=z%10
n2=(z//10)%10
n3=z//100
if (n1**3+n2**3+n3**3)==z:
print(z," is an armstrong number!")
|
0fc220744de9a8c8cdee42bf69c2ccd9639c9cf3 | Sharmaxz/HarvardX-CS50 | /pset6 - python/mario (less)/mario.py | 324 | 4.25 | 4 | height = 0
# Loop to get the correct value
while (1 >= height or height > 9):
height = int(input("Height: ")) + 1
# Logic to make the pyramid
for i in range(1, height):
for j in range(1, height - i):
print(" ", end='')
for j in range((height - i), height):
print("#", end='')
print("")
|
e2b8f3f20673fa627e8b8ee8b80e0e6d1082d0f0 | dingguopeng/python3_test | /求绝对值.py | 164 | 3.796875 | 4 | def my_abs(x):
if x > 0:
return x
else:
return -x
s = float(input('输入一个数:'))
print('该数的绝对值是:',my_abs(s)) |
03c7555365554a32bc8d4627dc33043b5bbf258a | PetrPrazak/AdventOfCode | /2017/02/aoc2017_02.py | 937 | 3.625 | 4 | # https://adventofcode.com/2017/day/2
def solve(lines):
total = 0
for line in lines:
table = line.split()
numbers = list(map(int, table))
amax = max(numbers)
amin = min(numbers)
total += amax - amin
print("Total = ", total)
def solve2(lines):
total = 0
for line in lines:
numbers = list(map(int, line.split()))
numbers.sort(reverse=True)
adiv = 0
for i, num in enumerate(numbers):
if adiv != 0:
break
dividers = numbers[i+1:]
for div in dividers:
(x, y) = divmod(num, div)
if y == 0:
adiv = x
total += adiv
break
print("Total =", total)
if __name__ == "__main__":
with open("input.txt") as f:
lines = f.readlines()
print("Lines count =", len(lines))
solve2(lines)
|
a0c8341b9d2973c6cfc18da2247b799626205d31 | Gangamagadum98/Python-Programs | /PythonClass/LearningJson.py | 478 | 3.578125 | 4 | import json
# converting json to dictionary
user = '{"email":"sneha@gmail.com", "password":"pass"}'
dict=json.loads(user)
print(type(dict))
print(type(user))
# converting dictionary to json
dictionary = {'name':'Ganga','mob':'9067787678'}
json1 = json.dumps(dictionary)
print(json1)
print(type(json1))
# converting list to json
list= ['harish',78,'chaitra']
lists = json.dumps(list)
print(lists)
num=67
print(json.dumps(num))
t=('23','34','12',90)
print(json.dumps(t)) |
657416bf0344ace1170c6c5efc6b0166c6ac76cb | Rxma1805/LintCode | /159. Find Minimum in Rotated Sorted Array/1500ms.py | 669 | 3.6875 | 4 | class Solution:
"""
@param nums: a rotated sorted array
@return: the minimum number in the array
"""
def findMin(self, A):
# write your code here
N = len(A)
return self.binarySearchFirstIndex(0,N-1,A,A[N-1])
def binarySearchFirstIndex(self,left,right,A,target):
if right - left == 1 :
if A[left] > A[right]:
return A[right]
else:
return A[left]
mid = (left+right)//2
if A[mid] <= target:
return self.binarySearchFirstIndex(left,mid,A,target)
else:
return self.binarySearchFirstIndex(mid,right,A,target)
|
04c088d083d48e279a66f206c1ed05af092696af | derekbomfimprates/python | /ProjectPython/mainScreen.py | 10,983 | 3.515625 | 4 | #import modules
from tkinter import *
import os
from datetime import date
from datetime import datetime
import requests
import re
main_screen = Tk()
# CREATING THE REGISTRATION SCREEN
def register():
global register_screen
#LAYOUT INFORMATION:
register_screen = Toplevel(main_screen)
register_screen.title("Register")
register_screen.geometry("300x250")
#VARIABLES:
global username
global password
global username_entry
global password_entry
username = StringVar()
password = StringVar()
#ASKING THE USER TO INSERT THEY DETAILS
Label(register_screen, text="Please enter details below", bg="blue").pack()
Label(register_screen, text="").pack()
username_lable = Label(register_screen, text="Username * ")
username_lable.pack()
username_entry = Entry(register_screen, textvariable=username)
username_entry.pack()
password_lable = Label(register_screen, text="Password * ")
password_lable.pack()
password_entry = Entry(register_screen, textvariable=password, show='*')
password_entry.pack()
Label(register_screen, text="").pack()
#THE BUTTON REGISTER WILL SEND THE INFORMATION TO register_user where the information will be manage
Button(register_screen, text="Register", width=10, height=1, bg="blue", command = register_user).pack()
# CREATING LOGIN SCREEN
def login():
global login_screen
login_screen = Toplevel(main_screen)
#DESIGNER SET UP
login_screen.title("Login")
login_screen.geometry("300x250")
Label(login_screen, text="Please enter details below to login").pack()
Label(login_screen, text="").pack()
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
global password_login_entry
#ASKING THE USER TO INSERT THEY DETAILS
Label(login_screen, text="Username * ").pack()
username_login_entry = Entry(login_screen, textvariable=username_verify)
username_login_entry.pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Password * ").pack()
password_login_entry = Entry(login_screen, textvariable=password_verify, show= '*')
password_login_entry.pack()
Label(login_screen, text="").pack()
#THE BUTTON LOGIN WILL SEND THE INFORMATION TO login_verify WHERE THE INFORMATION WILL BE VERIFIED
Button(login_screen, text="Login", width=10, height=1, command = login_verify).pack()
# THE REGISTER BUTTON WILL SEND THE INFORMATION FOR THE FOLLOWING :
def register_user():
#GETTING THE INFORMATION FROM THE USER
username_info = username.get()
password_info = password.get()
#WRITING THE INFORMATION ON A FILE
file = open(username_info, "w")
file.write(username_info + "\n")
file.write(password_info+ "\n")
file.close() #CLOSING THE FIKE
username_entry.delete(0, END)
password_entry.delete(0, END)
#DISPLAYING THE MESSAGE
Label(register_screen, text="Registration Success", fg="green", font=("calibri", 11)).pack()
# Implementing event on login button
def login_verify():
username1 = username_verify.get()
password1 = password_verify.get()
username_login_entry.delete(0, END)
password_login_entry.delete(0, END)
list_of_files = os.listdir()
if username1 in list_of_files:
file1 = open(username1, "r")
verify = file1.read().splitlines()
if password1 in verify:
login_sucess()
else:
password_not_recognised()
else:
user_not_found()
# Designing popup for login success
def login_sucess():
global login_success_screen
login_success_screen = Toplevel(login_screen)
login_success_screen.title("Success")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="Login Success").pack()
Button(login_success_screen, text="OK", command=delete_login_success).pack()
news_now()
def news_now():
global news_screen
news_screen = Toplevel(main_screen)
news_screen.title("News")
#news_screen.geometry("300x250")
URL = "https://newsapi.org/v2/top-headlines?country=ie&category=business&apiKey=c7e21cd081124ea28a1b9e011327d0a8"
count=int("0")
r = requests.get(url=URL)
data= r.json()
news_b=[]
global desc_business
desc_business=[]
for x in range(3):
head= data['articles'][x]['title']
date= data['articles'][x]['publishedAt']
content= data['articles'][x]['content']
count=count+1
desc_business.append(str(count)+" - "+head +" - "+ date + '\n')
news_b.append(str(count)+" - "+head +" - "+ date + '\n')
print(str(count)+" - "+head, date, '\n')
frame = LabelFrame(news_screen, text='Business News')
frame.pack(expand=YES, fill=BOTH)
for y in range(3):
business_news= Label(frame, text=news_b[y])
business_news.grid(row=y, column =0)
b1= Button(frame, text="Save", width=10, height=1, command =lambda:save(news_b[0]))
b1.grid(row=0, column=1)
b2= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_b[1]))
b2.grid(row=1, column=1)
b3= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_b[2]))
b3.grid(row=2, column=1)
URL = "https://newsapi.org/v2/top-headlines?country=ie&category=sports&apiKey=c7e21cd081124ea28a1b9e011327d0a8"
count1=int("3")
r = requests.get(url=URL)
data= r.json()
news_s=[]
global desc_sport
desc_sport=[]
for x in range(3):
head= data['articles'][x]['title']
date= data['articles'][x]['publishedAt']
content= data['articles'][x]['content']
count1=count1+1
desc_sport.append(str(count1)+" - "+head +" - "+ date + '\n')
news_s.append(str(count1)+" - "+head +" - "+ date + '\n')
print(str(count1)+" - "+head, date, '\n')
frame = LabelFrame(news_screen, text='Sport News')
frame.pack(expand=YES, fill=BOTH)
for y in range(3):
sport_news= Label(frame, text=news_s[y])
sport_news.grid(row=y, column =0)
b4= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_s[0]))
b4.grid(row=0, column=1)
b5= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_s[1]))
b5.grid(row=1, column=1)
b6= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_s[2]))
b6.grid(row=2, column=1)
URL = "https://newsapi.org/v2/top-headlines?country=ie&category=business&apiKey=c7e21cd081124ea28a1b9e011327d0a8"
count2=int("6")
r = requests.get(url=URL)
data= r.json()
news_f=[]
global desc_financial
desc_financial=[]
for x in range(3):
head= data['articles'][x]['title']
date= data['articles'][x]['publishedAt']
content= data['articles'][x]['content']
count2=count2+1
desc_financial.append(str(count2)+" - "+head +" - "+ date + '\n')
news_f.append(str(count2)+" - "+head +" - "+ date + '\n')
print(str(count2)+" - "+head, date, '\n')
frame = LabelFrame(news_screen, text='financial News')
frame.pack(expand=YES, fill=BOTH)
for y in range(3):
fin_news= Label(frame, text=news_f[y])
fin_news.grid(row=y, column =0)
b4= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_f[0]))
b4.grid(row=0, column=1)
b5= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_f[1]))
b5.grid(row=1, column=1)
b6= Button(frame, text="Save", width=10, height=1,command =lambda:save(news_f[2]))
b6.grid(row=2, column=1)
frame = LabelFrame(news_screen, text='Your news')
frame.pack(expand=YES, fill=BOTH)
show_your_news= Button(frame, text="Your News", padx=10, pady=10,command =lambda:show_news())
show_your_news.grid(row=0, column=0)
def show_news():
global show_screen
global delete_entry
delete= int()
show_screen = Toplevel(news_screen)
show_screen.title("Your News")
login_screen.geometry("300x250")
Label(show_screen, text="Here is your news: ").pack()
file = open('your_news','r')
Label(show_screen, text=file.read()).pack()
Label(show_screen, text="Would you like to delete any news? Enter the number.").pack()
delete_entry = Entry(show_screen, textvariable=delete)
delete_entry.pack()
Label(show_screen, text="").pack()
Button(show_screen, text="delete", width=10, height=1, command = delete_news).pack()
def delete_news():
x= delete_entry.get()
find= x+" - "
f = open("your_news","r")
lines = f.readlines()
f.close()
f = open("your_news","w")
for line in lines:
if find not in line:
f.write(line)
f.close()
def save(x):
global save
news_info = x
file = open('your_news', "at")
file.write(news_info)
file.close()
Label(news_screen, text="Saved Success", fg="green", font=("calibri", 11)).pack()
def password_not_recognised():
global password_not_recog_screen
password_not_recog_screen = Toplevel(login_screen)
password_not_recog_screen.title("Success")
password_not_recog_screen.geometry("150x100")
Label(password_not_recog_screen, text="Invalid Password ").pack()
Button(password_not_recog_screen, text="OK", command=delete_password_not_recognised).pack()
# Designing popup for user not found
def user_not_found():
global user_not_found_screen
user_not_found_screen = Toplevel(login_screen)
user_not_found_screen.title("Success")
user_not_found_screen.geometry("150x100")
Label(user_not_found_screen, text="User Not Found").pack()
Button(user_not_found_screen, text="OK", command=delete_user_not_found_screen).pack()
# Deleting popups
def delete_login_success():
login_success_screen.destroy()
def delete_password_not_recognised():
password_not_recog_screen.destroy()
def delete_user_not_found_screen():
user_not_found_screen.destroy()
# Designing Main(first) window
def main_account_screen():
global main_screen
now = datetime.now()
today = now.strftime("%d/%m/%Y %H:%M:%S")
main_screen.geometry("300x250")
main_screen.title("Account Login")
Label(text="Welcome! ", bg="green", width="300", height="1", font=("Calibri", 13)).pack()
Label(text="Here you will keep track of different world events as they occur.", bg="green", width="300", height="1", font=("Calibri", 9)).pack()
Label(text=today, bg="green", width="300", height="1", font=("Calibri", 9)).pack()
Label(text="").pack()
Button(text="Login", height="2", width="30", command = login).pack()
Label(text="").pack()
Button(text="Register", height="2", width="30", command=register).pack()
main_screen.mainloop()
main_account_screen()
|
9107df2177c8bd77d22eecc0b3ae6efe8e41baaa | Dlac/Python-For-Everybody | /exer65.py | 390 | 4.1875 | 4 | #take the following python code that stores a string
#str = 'x-dspam-confidence: 0.8475
#use find and string slicing to extract the portion of the string after the colon
# character and tehn use the float function to conver tthe extracted string int a floating point number
x = 'X-DSPAM-Confidence: 0.8475'
print x
pos = x.find(':')
#print pos
num = float(x[pos+1:])
print num, type(num)
|
dfc64a661dfca677d7b9731586886207098e62de | sergabrod/Python-Code | /gui2/radio_button.py | 682 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# utilizando radio button
from tkinter import *
root = Tk()
opcion = IntVar()
def imprimir():
if opcion.get() == 1:
label2.config(text="has elegido Masculino")
elif opcion.get() == 2:
label2.config(text="has elegido Femenino")
else:
label2.config(text="has elegido Otro")
Label(root, text="Género:").pack()
Radiobutton(root, text="Masculino", variable=opcion, value=1, command=imprimir).pack()
Radiobutton(root, text="Femenino", variable=opcion, value=2, command=imprimir).pack()
Radiobutton(root, text="Otro", variable=opcion, value=3, command=imprimir).pack()
label2 = Label(root)
label2.pack()
root.mainloop()
|
2b663ea9099a5116f59fc84d333a00d69e3528e7 | fabriciovale20/AulasExercicios-CursoEmVideoPython | /Exercícios Mundo 2 ( 36 à 71 )/ex062.py | 920 | 4.15625 | 4 | """
Exercício 62
Melhore o DESAFIO 061, perguntando para o usuário se ele quer mostrar mais alguns termos.
O programador encerra quando ele disser que quer mostrar 0 termos.
"""
print('='*30)
print('{:^30}'.format('GERADOR DE UMA PA'))
print('='*30)
primeiro_termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
cont = 1
qnt_de_termos = 0
while cont <= 10:
print(f'{primeiro_termo}', end=' → ')
primeiro_termo += razao
cont += 1
qnt_de_termos += 1
print('ACABOU')
termos = 1
while termos != 0:
termos = int(input('Quantos termos você quer mostrar a mais? '))
if termos != 0:
cont = 1
while cont <= termos:
print(f'{primeiro_termo}', end=' → ')
primeiro_termo += razao
cont += 1
qnt_de_termos += 1
print('ACABOU')
print(f'Progressão finalizada com {qnt_de_termos} termos mostrados.')
|
52b89c1bb0457d98e4b068a30311203ff60afb09 | braytonbravo/trabajo10_bravo | /submenu_1.py | 1,200 | 3.671875 | 4 | import libreria
def agregarPosicion():
nombre=libreria.pedir_nombre("Ingrese posicion de jugador:")
contenido=nombre+"\n"
libreria.agregar_datos("info.text",contenido,"a")
print("Posicion guardado")
def mostrarPosicion():
archivo=open("info.text")
datos=archivo.read()
print(datos)
archivo.close()
def nuevoJugador():
opc=0
max=3
while ( opc != max ):
print("####### Posicion de jugador #######")
print("#1. Agregar Posicion #")
print("#2. Mostrar Posicion: #")
print("#3. Salir #")
print("############################")
opc=libreria.pedir_entero("Ingrese opcion:", 1,3)
if ( opc == 1):
agregarPosicion()
if ( opc == 2):
mostrarPosicion()
opc=0
max=3
while ( opc != max ):
print("####### LISTA DE JUGADORES #######")
print("#1. Nuevo jugador: #")
print("#2. Mostrar jugadores: #")
print("#3. Salir #")
print("############################")
opc=libreria.pedir_entero("Ingrese opcion:", 1,3)
if ( opc == 1):
nuevoJugador()
if ( opc == 2):
mostrarJugadores()
|
484952344b7e7c94d97732a56c3500f05ab3ff82 | Abdelatief/Codeforces-Problems | /A. Pangram.py | 175 | 3.84375 | 4 | # http://codeforces.com/contest/520/problem/A
n = input()
string = input()
string_set = set(string.lower())
if len(string_set) == 26:
print('YES')
else:
print('NO')
|
e0a1ac224ab041f557e5454e43c75d16ae05c846 | orlandopython/tic-tac-toe-oop | /code/ttt4_turtle.py | 2,867 | 3.921875 | 4 | """
Tic Tac Toe
This uses Turtle graphics to draw the game board
It puts some "self protection" in the button class
"""
import sys
from turtle import Screen, Turtle
from typing import Callable
FONT = ("Arial", 24, "bold")
BUTTON_COLOR = "blue"
SYMBOL_COLOR = "white"
BUTTON_STRETCH = 5
BUTTON_SHAPE = "square"
FILLER = " "
XOFFSET, YOFFSET = -200, 200 # normally starts in center of window, yuck
class Button(Turtle):
def __init__(self, row: int, column: int):
super().__init__(visible=False)
self.penup()
self.hideturtle()
self.color(BUTTON_COLOR)
self.pencolor(SYMBOL_COLOR)
self.id = (row, column) # not actually used but good if you want it smarter
self.shape(BUTTON_SHAPE)
self.setposition(x=XOFFSET + column * 102, y=-(row * 102) + YOFFSET)
self.turtlesize(stretch_wid=BUTTON_STRETCH, stretch_len=BUTTON_STRETCH)
self.onclick(self.my_click_handler)
self.showturtle()
def my_click_handler(self, *_):
self.onclick(None) # disable button
Button.callback(self) # call the contoller function
def draw_symbol(self, symbol: str):
self.write(symbol, align="center", font=FONT)
class Model:
def __init__(self, size: int = 3):
self.size = size
self.data = [[FILLER for _ in range(size)] for _ in range(size)]
def update_state(self, symbol: str, row: int, column: int):
self.data[row][column] = symbol
def __repr__(self) -> str:
text = "\n"
for row in self.data:
text += "\n" + "|".join(row)
return text
class View:
def __init__(self, callback: Callable, size: int = 3):
Button.callback = callback # same callback for all buttons.
for row in range(size):
for column in range(size):
button = Button(row, column)
class Controller:
def __init__(self, model: Model):
self.counter = model.size ** 2
self.model = model
self.PLAYERS = "XO"
self.next_player = 0
def get_next_player(self) -> str:
player = self.PLAYERS[self.next_player]
self.next_player = (self.next_player + 1) % 2
return player
def click_handler(self, button: Button) -> bool:
symbol = self.get_next_player()
button.draw_symbol(symbol)
row, column = button.id
self.model.update_state(symbol, row, column)
self.counter -= 1
return self.keep_playing()
def keep_playing(self) -> bool:
if self.counter > 0:
return True
print("game over man")
print(self.model)
sys.exit(0)
def main():
model = Model(size=3)
controller = Controller(model)
view = View(controller.click_handler, size=model.size)
screen = Screen()
screen.mainloop()
if __name__ == "__main__":
main()
|
27abcf787e6b79daed3a8bfbab20c539e826bf52 | pricixavier/Think-Phython | /vowel.py | 141 | 3.859375 | 4 | d=['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
s=char(input("enter the letter"))
if(a in d):
print("vowel")
else:
print("invalid")
|
8aac005909cd57659ecf57a721418b1c603e6d9c | maknetaRo/pythonpractice | /while_ex4.py | 732 | 4.09375 | 4 | """
Write a program that asks the user to enter a password. If the user enters the
right password, the program should tell them they are logged into the system.
Otherwise, the program should ask them to reenter the password. The user should
only get five tries to enter the password, after which point the program
should tell them that they are kicked off of the system.
"""
password = input("Enter a password: ")
logged = "1234ba"
tries = 1
while tries < 5:
if password == logged:
print("You are logged into the system.")
break
else:
print("Reenter the password.")
password = input("Enter a password: ")
tries += 1
print("After 5 tries, you are kicked off of the system.")
|
9788816cfb5d6917e646bf8c4ccdeee7c2730e43 | zhbbupt/ospaf-primary | /Ospaf/src/Matplotlib/DrawChart.py | 239 | 3.796875 | 4 | '''
use matplot to draw some charts
@author: Garvin
'''
import matplotlib.pyplot as plt
def BarChart(name,num):
plt.bar(range(len(num)), num, align='center')
plt.xticks(range(len(num)), name, size='large')
plt.show()
|
6538ffc09e72b1552b813034d0e0d1482ee07dad | devjoi2018/simple_password_generator_python | /simple_password_generator.py | 2,319 | 3.921875 | 4 | # This code is part of the tests that I have been doing with Github Copilot.
# Program that generates passwords randomly
# The length of the password must be requested from the user through the console
# The user should be asked if they want to include special characters in the opassword
# If the user selects 'y', a password must be generated with special characters and with uppercase lowercase letters and numbers randomly
# If the user chooses 'n', a password must be generated with uppercase lowercase letters and numbers randomly
import random
import string
import sys
import os
def main():
print('RANDOM PASSWORD GENERATOR')
print('Select an option: ')
print('1. Generate random password')
print('2. Generate password with special characters')
print('3. Generate password with uppercase lowercase letters and numbers')
option = input('Enter your option:')
if option == '1':
length = input('Enter the password length: ')
password = generate_password(length)
print('Password generado: ' + password)
elif option == '2':
length = input('Enter the password length: ')
password = generate_password_especial_character(length)
print('Password generado: ' + password)
elif option == '3':
length = input('Enter the password length: ')
password = generate_password_uppercase_lowercase(length)
print('Generated password: ' + password)
else:
print('Enter a valid option')
def generate_password(longitud):
password = ''
for i in range(int(longitud)):
password += random.choice(string.ascii_letters + string.digits)
return password
def generate_password_especial_character(longitud):
password = ''
for i in range(int(longitud)):
password += random.choice(string.ascii_letters + string.digits + string.punctuation)
return password
def generate_password_uppercase_lowercase(longitud):
password = ''
for i in range(longitud):
password += random.choice(string.ascii_letters + string.digits)
if i % 2 == 0: password += random.choice(string.ascii_uppercase)
else: password += random.choice(string.ascii_lowercase)
return password
if __name__ == '__main__':
main() |
36a06dfab09c09c7e9f6c14a35b148fc16988c72 | Touchhub/Ahri | /lian/info_3.py | 268 | 3.953125 | 4 | math=input("math:")
pe=input("pe:")
age=input("age:")
print(type(age))
job=input("job:")
name=input("name")
info='''
-------info of {0}-------
math={1}
pe={2}
age={3}
job={4}
'''.format(name,
pe,
age,
job,
math)
print(info) |
c386b270da19bb4b8cd89874a97d99f6d7ea8ec0 | seymakara/CTCI | /01ArraysAndStrings/LCclimbingTheStairs.py | 417 | 3.734375 | 4 | class Solution(object):
def climbStairs(self, n):
if n == 1:
return 1
if n == 2:
return 2
one_step_before = 2
two_steps_before = 1
all_ways = 0
for i in range(2,n):
all_ways = one_step_before + two_steps_before
two_steps_before = one_step_before
one_step_before = all_ways
return all_ways |
3be8119a9adbbafb71042ff10355fcd4d8fc8016 | jobafash/InterviewPrep | /common-ds/lls.py | 7,994 | 4.34375 | 4 | '''
Connected data(nodes) is dispersed throughout memory.
In a linked list, each node represents one item in the list.
This is the key to the linked list: each node also comes with a little extra
information, namely, the memory address of the next node in the list.
This extra piece of data—this pointer to
the next node’s memory address—is known as a link.
A really important point emerges: when dealing with a linked list, we only
have immediate access to its first node. This is going to have serious ramifica-
tions as we’ll see shortly.
'''
#Working with LL - Create node, connect, update
class Node:
def __init__(self, data):
self.data = data
self.next_element = None
class LinkedList:
def __init__(self):
self.head_node = None
def get_head(self):
return self.head_node
def is_empty(self):
return self.head_node == None
'''
The three types of insertion strategies used in singly linked-lists are:
Insertion at the head
Insertion at the tail
Insertion at the kth index
'''
def insert_at_head(self, data):
# Create a new node containing your specified value
temp_node = Node(data)
temp_head = self.get_head()
if not temp_head:
self.head_node = temp_node
# The new node points to the same node as the head
temp_node.next_element = self.head_node
self.head_node = temp_node # Make the head point to the new node
return
#Inserting at the tail of a LL
def insert_at_tail(lst, value):
newest = Node(value)
temp = lst.get_head()
if temp is None:
lst.head_node = newest
return
while temp.next_element is not None:
temp = temp.next_element
temp.next_element = newest
return
def insert_at_kth(lst, value, k):
new_node = Node(value)
temp = lst.get_head()
if not temp:
lst.head_node = new_node
k -= 1
while k > 1 and temp.next_element:
temp = temp.next_element
k -= 1
temp.next_element = new_node
new_node.next_element = temp.next_element.next_element
return
def search(lst, value):
temp = lst.get_head()
if not temp: return False
if temp.data == value: return True
while temp.next_element:
if temp.next_element == value:
return True
temp = temp.next_element
return False
# Supplementary print function
def print_list(self):
if(self.is_empty()):
print("List is Empty")
return False
temp = self.head_node
while temp.next_element is not None:
print(temp.data, end=" -> ")
temp = temp.next_element
print(temp.data, "-> None")
return True
'''
There are three basic delete operations for linked lists:
Deletion at the head
Deletion by value
Deletion at the tail
'''
def delete_at_head(lst):
# Get Head and firstElement of List
first_element = lst.get_head()
# if List is not empty then link head to the
# nextElement of firstElement.
if first_element is not None:
lst.head_node = first_element.next_element
first_element.next_element = None
return
def delete(lst, value):
# Write your code here
deleted = False
if lst.is_empty():
return deleted
val = lst.get_head()
previous = None
if val.data is value:
lst.delete_at_head()
deleted = True
return deleted
while val is not None:
if val.data == value:
previous.next_element = val.next_element
val.next_element == None
deleted=True
break
previous = val
val = val.next_element
return deleted
def length(lst):
temp = lst.get_head()
size = 0
if not temp: return 0
while temp is not None:
temp = temp.next_element
size += 1
return size
def reverse(lst):
current = lst.get_head()
previous = None
next = None
while current:
next = current.next_element #Save what we're working on next
current.next_element = previous #Reversal
previous = current #After reversal, make it previous
current = next #Get our current
lst.head_node = previous #Set head to previous so we can iterate again
return lst
def detect_loop(lst): # Floyd’s Cycle-Finding Algorithm
slow = lst.get_head()
fast = lst.get_head()
while fast and fast.next_element:
slow = slow.next_element
fast = fast.next_element.next_element
if slow == fast: return True
return False
def find_mid(lst):
length = lst.length()
mid = 0
if length % 2 == 0: mid = length // 2
if length % 2 == 1: mid = (length // 2) + 1
temp = lst.get_head()
while mid > 0 and temp:
temp = temp.next_element
mid -= 1
return temp.data
def remove_duplicates(lst):
if lst.is_empty():
return None
# If list only has one node, leave it unchanged
if lst.get_head().next_element is None:
return lst
outer_node = lst.get_head()
while outer_node:
inner_node = outer_node # Iterator for the inner loop
while inner_node:
if inner_node.next_element:
if outer_node.data == inner_node.next_element.data:
# Duplicate found, so now removing it
new_next_element = inner_node.next_element.next_element
inner_node.next_element = new_next_element
else:
# Otherwise simply iterate ahead
inner_node = inner_node.next_element
else:
# Otherwise simply iterate ahead
inner_node = inner_node.next_element
outer_node = outer_node.next_element
return lst
def union(list1, list2):
# Return other List if one of them is empty
if (list1.is_empty()):
return list2
elif (list2.is_empty()):
return list1
start = list1.get_head()
# Traverse the first list till the tail
while start.next_element:
start = start.next_element
# Link last element of first list to the first element of second list
start.next_element = list2.get_head()
list1.remove_duplicates()
return list1
def intersection(list1, list2):
result = LinkedList()
current_node = list1.get_head()
# Traversing list1 and searching in list2
# insert in result if the value exists
while current_node is not None:
value = current_node.data
if list2.search(value) is not None:
result.insert_at_head(value)
current_node = current_node.next_element
# Remove duplicates if any
result.remove_duplicates()
return result
def find_nth(lst, n):
if (lst.is_empty()):
return -1
# Find Length of list
length = lst.length() - 1
# Find the Node which is at (len - n + 1) position from start
current_node = lst.get_head()
position = length - n + 1
if position < 0 or position > length:
return -1
count = 0
while count is not position:
current_node = current_node.next_element
count += 1
if current_node:
return current_node.data
return -1 |
db852fa295bed837efa39df3ca81e77006f7c894 | WangXu1997s/store | /统计列表中每个数出现的次数.py | 196 | 3.671875 | 4 |
List = [1,4,7,5,8,2,1,3,4,5,9,7,6,1,10]
setL = set(List)
#print(setL.pop())
for i in range(len(setL)):
view = setL.pop()
print("{0}出现了{1}次。".format(view,List.count(view))) |
9215f9ce7e5f571fb25d5e2b10b44fc8a2f69f1e | mxruedag/ProblemSolving | /project-euler/Problem4.py | 351 | 3.546875 | 4 | def is_palindrome(n):
strn = str(n)
if len(strn) <= 1:
return True
noLastOrFirst = strn[1:-1]
return strn[0] == strn[-1] and is_palindrome(noLastOrFirst)
max_pal = 0
for i in xrange(1000):
for j in xrange(i,1000):
new = i*j
if is_palindrome(new) and max_pal < new:
max_pal = i*j
print max_pal
|
05d1f40563b9d99b38f00350e793f2975b8393f5 | rashigupta37/tic_tac_toe | /Game.py | 2,875 | 3.640625 | 4 | import copy
#game class
class Game:
def __init__(self):
self.board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
self.win = 0 #winner
self.curPlayer = 1 #current player
self.boardSize = 3 #board-size
self.moveHistory = [] #stores move history
self.p1 = None #first player
self.p2 = None #second player
self.depth=0
# checks whether board is full or not
def isBoardFull(self):
ans = True
for i in self.board:
if i.count(0) > 0:
ans = False
break
return ans
#stores moves of current player in the board
def move(self, n):
if n not in range(0, 9):
return -2
if self.board[n//3][n%3] == 0:
self.board[n//3][n%3] = self.curPlayer
self.moveHistory.append(n+1)
return 1
else:
return -1
#clears the move from the table
def clearMove(self, n):
if n not in range(0, 9):
return -2
else:
self.board[n//3][n%3] = 0
return 1
#filling the position of board in emp[] after flattening
#ex: board[0][0]=0, board[0][1]=1.... board[2][2]=8
def getEmp(self):
emp = []
for i in range(self.boardSize):
for j in range(self.boardSize):
if self.board[i][j] == 0:
emp.append((i*3)+j)
return emp
def getCopy(self):
return copy.deepcopy(self)
#checks for the winner
def checkForWinner(self):
#checks first row for victory
if self.board[0][0] == self.board[0][1] == self.board[0][2] != 0:
return self.board[0][1]
#checks second row for victory
elif self.board[1][0] == self.board[1][1] == self.board[1][2] != 0:
return self.board[1][1]
#checks third row for victory
elif self.board[2][0] == self.board[2][1] == self.board[2][2] != 0:
return self.board[2][1]
#checks leading diagnol for victory
elif self.board[0][0] == self.board[1][1] == self.board[2][2] != 0:
return self.board[0][0]
#checks first column for victory
elif self.board[0][0] == self.board[1][0] == self.board[2][0] != 0:
return self.board[0][0]
#checks second column for victory
elif self.board[0][1] == self.board[1][1] == self.board[2][1] != 0:
return self.board[0][1]
#checks third column for victory
elif self.board[0][2] == self.board[1][2] == self.board[2][2] != 0:
return self.board[0][2]
#checks the other diagnol for victory
elif self.board[0][2] == self.board[1][1] == self.board[2][0] != 0:
return self.board[0][2]
else:
return 0
|
5fdffcece872a84525531747e9927b9e603d53a9 | Surya0705/Python_Colorful_Pattern | /Main.py | 538 | 4.0625 | 4 | import turtle # Importing the Module.
colors=['red', 'deeppink2', 'cyan', 'chartreuse', 'blue', 'yellow'] # Giving a set of Colors.
turtle.bgcolor('black') # Giving it a background Color.
turtle.speed(20) # Giving it a speed.
for x in range(360): # Starting a loop.
turtle.pencolor(colors[x%6]) # Changing Colors.
turtle.width(x/100+1) # Changing Width.
turtle.forward(x) # Making turtle Move forward.
turtle.left(59) # Making turtle turn at an angle of 59.
turtle.exitonclick() # Making the Window Exit only when Clicked. |
a8aa1bd1ff0d95512892fba4f4b226bfed534d4e | Rakk4403/deep-learning-from-scratch | /common/differential.py | 2,058 | 3.546875 | 4 | # author: rakk4403
import numpy as np
import matplotlib.pylab as plt
def numerical_diff_badcase(f, x):
"""
It would be rounding error, if input is too small.
"""
h = 10e-50 # close to 0
return (f(x + h) - f(x)) / h
def numerical_diff(f, x):
# Right function
h = 1e-4 # 0.0001
return (f(x + h) - f(x - h)) / (2 * h)
def function_1(x):
# temporary function for differential target
return 0.01 * (x ** 2) + 0.1 * x
def function_2(x):
# temporary function for partial differenctials
return np.sum(x ** 2) # or x[0]**2 + x[1]**2
def numerical_gradient(f, x):
"""
gradient is same as partial differentials
"""
h = 1e-4 # 0.0001
grad = np.zeros_like(x)
for idx in range(x.size):
tmp_val = x[idx]
# f(x+h)
x[idx] = tmp_val + h
fxh1 = f(x)
# f(x-h)
x[idx] = tmp_val - h
fxh2 = f(x)
grad[idx] = (fxh1 - fxh2) / (2 * h)
x[idx] = tmp_val
return grad
def gradient_descent(f, init_x, lr=0.01, step_num=100):
"""
f: target function to optimize
init_x: initial value
lr: learning rate
step_num: repeat count for descent method
"""
x = init_x
for i in range(step_num):
grad = numerical_gradient(f, x)
x -= lr * grad
return x
if __name__ == '__main__':
# check function_1
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.plot(x, y)
plt.show()
# differential of function_1
ret = numerical_diff(function_1, 5)
print(ret)
# partial differentials (gradient)
ret = numerical_gradient(function_2, np.array([3.0, 4.0]))
print(ret)
ret = numerical_gradient(function_2, np.array([0.0, 2.0]))
print(ret)
ret = numerical_gradient(function_2, np.array([3.0, 0.0]))
print(ret)
# gradient_descent
init_x = np.array([-3.0, 4.0])
ret = gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100)
print('gradient descent: {}'.format(ret)) |
d94bf97b404dd62c7bd34da11059fc82506448c3 | JEONJinah/Shin | /quick_sort.py | 957 | 3.875 | 4 | # 주어진 리스트를 2 그룹으로 나누는 코드 작성
def quick_sort(in_list, left, right): # 재귀호출로 작성시 함수의 매개변수도 변경되어야함.
n = len(in_list)
pl = left # 0
pr = right #n - 1
x = in_list[(left+right) //2 ]
# x = in_list[n // 2] # 재귀 호출로 해당 함수를 호출할 경우에는 (left, right)
while pl <= pr:
while in_list[pl] < x: pl += 1
while in_list[pl] < x: pr -= 1
if pl <= pr:
in_list[pl], in_list[pr] = in_list[pr], in_list[pl]
pl += 1
pr -= 1
if left < pr: quick_sort(in_list, left, pr)
if pl < right: quick_sort(in_list, pl, right)
# print(f'피벗보다 작은 그룹: {in_list[0: pl]}')
# print(f'피벗보다 큰 그룹: {in_list[pr+1: n]}')
if __name__ == "__main__":
x = [5, 8, 4, 2, 6, 1, 3, 9, 7]
quick_sort(x, 0, len(x) - 1)
print(x) |
356e0e5b5970efe4d557a592a580619602be7b1a | HelloImKevo/PyPlayground | /src/pluralsight_misc/examples.py | 3,041 | 3.671875 | 4 | #!/usr/bin/env python3
"""
Miscellaneous Pluralsight examples.
"""
import datetime
import math
print("Reticulating spline {} of {}.".format(4, 23))
# String formatting with a tuple
print("Galactic position x={pos[0]}, x={pos[1]}, z={pos[2]}"
.format(pos=(65.2, 23.1, 82.2)))
# String formatting and import substitution and attribute reference
print("Math constants: pi={m.pi}, e={m.e}".format(m=math))
# String formatting with truncation / float precision
print("Math constants: pi={m.pi:.3f}, e={m.e:.3f}".format(m=math))
# PEP 498: Literal String Interpolation - Commonly called f-strings
print(f'The current time is {datetime.datetime.now().isoformat()}')
print(f'Math constants: pi={math.pi:.5f}, e={math.e:.5f}')
# Print all help docstrings for the string class (verbose)
# help(str)
presidents: list = ['Washington', 'Adams', 'Jefferson', 'Clinton', 'Bush', 'Obama', 'Trump']
for num, name in enumerate(presidents, start=1):
print("President {}: {}".format(num, name))
print('Working with Dictionaries...')
colors: dict = dict(aquamarine='#7FFFD4', burlywood='#DEB887',
chartreuse='#7FFF00', cornflower='#6495ED',
firebrick='#B22222', honeydew='#F0FFF0',
maroon='#B03060', sienna='#A0522D')
for key in colors:
print(f"{key} => {colors[key]}")
for value in colors.values():
print(value)
for key in colors.keys():
print(key)
# Traverse dictionary as item tuples
for key, value in colors.items():
print(f"{key} => {colors[key]}")
print('aquamarine' in colors)
print('emerald' not in colors)
print('Working with Sets...')
blue_eyes: set = {'Olivia', 'Harry', 'Lily', 'Jack', 'Amelia'}
blond_hair: set = {'Harry', 'Jack', 'Amelia', 'Mia', 'Joshua'}
# People that can smell hydrogen cyanide
smell_hcn: set = {'Harry', 'Amelia'}
# People that can taste phenylthiocarbamide
taste_ptc: set = {'Harry', 'Lily', 'Amelia', 'Lola'}
o_blood: set = {'Mia', 'Joshua', 'Lily', 'Olivia'}
b_blood: set = {'Amelia', 'Jack'}
a_blood: set = {'Harry'}
ab_blood: set = {'Joshua', 'Lola'}
print(blue_eyes.union(blond_hair))
print(blue_eyes.union(blond_hair) == blond_hair.union(blue_eyes))
# Find all people with blond hair and blue eyes (intersection collects only
# elements that are present in both sets). This is commutative.
print(blue_eyes.intersection(blond_hair))
print(blue_eyes.intersection(blond_hair) == blond_hair.intersection(blue_eyes))
# Find all the people with blond hair and don't have blue eyes
print(blond_hair.difference(blue_eyes))
# People that have exclusively blond hair OR blue eyes, but not both
print(blond_hair.symmetric_difference(blue_eyes))
# Check if all people that can smell HCL have blond hair
print(smell_hcn.issubset(blond_hair))
# Check if all elements of the second set are present in the first set
print(taste_ptc.issuperset(smell_hcn))
# Check if these have no members in common
print(a_blood.isdisjoint(o_blood))
# Protocols: Container, Sized, Iterable, Sequence,
# Mutable Sequence, Mutable Set, Mutable Mapping
|
1c1d8185ddb52f86cec08ee82e654f5fa6b27b21 | diwadd/Algs | /quicksort.py | 1,394 | 3.734375 | 4 | import random
def partition(a, p, r):
"""
Intorduction to algorithms 3rd ed.
Cormen et al.
Page 171, Section 7.1
:param a: An array.
:param p: Index in a.
:param r: Index in a.
"""
x = a[r]
i = p - 1
for j in range(p, r):
if a[j] <= x:
i = i + 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[r] = a[r], a[i + 1]
return i + 1
def randomized_partition(a, p, r):
"""
Intorduction to algorithms 3rd ed.
Cormen et al.
Page 179, Section 7.3
:param a: An array.
:param p: Index in a.
:param r: Index in a.
"""
i = random.randint(p, r)
a[i], a[r] = a[r], a[i]
return partition(a, p, r)
def quicksort(a, p, r):
"""
Intorduction to algorithms 3rd ed.
Cormen et al.
Page 171, Section 7.1
:param a: An array.
:param p: Index in a.
:param r: Index in a.
"""
if p < r:
q = partition(a, p, r)
quicksort(a, p, q - 1)
quicksort(a, q + 1, r)
def randomized_quicksort(a, p, r):
"""
Intorduction to algorithms 3rd ed.
Cormen et al.
Page 179, Section 7.3
:param a: An array.
:param p: Index in a.
:param r: Index in a.
"""
if p < r:
q = randomized_partition(a, p, r)
randomized_quicksort(a, p, q - 1)
randomized_quicksort(a, q + 1, r)
|
72551ad3dd4dd73b2a7e342d4009ca287471c00d | ksingh7/python-programs | /password_checker.py | 700 | 3.921875 | 4 | def passwordChecker(string):
import re
x = True
while x:
if (len(string) < 6 or len(string) > 12):
print "Incorrect length"
break
elif not (re.search('[a-z]',string)):
print "no lower case characters found"
break
elif not (re.search('[A-Z]',string)):
print "no upper case characters found"
break
elif not (re.search('[@$#]',string)):
print "no special characters found"
break
else:
print "Password validated successfully"
x = False
break
password = raw_input("Enter password to validate")
passwordChecker(password)
|
e5f8bcd6a8a84bcc19faa5ae06609bcea2caea29 | balbinoaylagas/telus-py-training-B2 | /telus_py_training_b2/py_dictionaries.py | 7,823 | 4.59375 | 5 | """
Python Dictionaries
"""
# Dictionary
# Dictionaries are used to store data values in key:value pairs.
# A dictionary is a collection which is unordered, changeable and does not allow duplicates.
# Dictionaries are written with curly brackets, and have keys and values:
# Create and print a dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
print(thisdict)
# Dictionary Items
# Dictionary items are unordered, changeable, and does not allow duplicates.
# Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
# Print the "brand" value of the dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
print(thisdict["brand"])
# Unordered
# When we say that dictionaries are unordered, it means that the items does not have a defined order, you cannot refer to an item by using an index.
# Changeable
# Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
# Duplicates Not Allowed
# Dictionaries cannot have two items with the same key:
# Duplicate values will overwrite existing values:
# this code gives an error
"""
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964, "year": 2020}
print()
print(thisdict)
"""
# Dictionary Length
# To determine how many items a dictionary has, use the len() function:
# Print the number of items in the dictionary:
print()
print(len(thisdict))
# Dictionary Items - Data Types
# The values in dictionary items can be of any data type:
# String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"],
}
print()
print(thisdict)
# type()
# From Python's perspective, dictionaries are defined as objects with the data type 'dict':
# <class 'dict'>
# Print the data type of a dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
print(type(thisdict))
# Accessing Items
# You can access the items of a dictionary by referring to its key name, inside square brackets:
# Get the value of the "model" key:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
x = thisdict["model"]
print()
print(x)
# There is also a method called get() that will give you the same result:
# Get the value of the "model" key:
x = thisdict.get("model")
print()
print(x)
# Get Keys
# The keys() method will return a list of all the keys in the dictionary.
# Get a list of the keys:
x = thisdict.keys()
print()
print(x)
# The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary
# will be reflected in the keys list.
# Add a new item to the original dictionary, and see that the value list gets updated as well:
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
x = car.keys()
print()
print(x) # before the change
car["color"] = "white"
print(x) # after the change
# Get Values
# The values() method will return a list of all the values in the dictionary.
# Get a list of the values:
x = thisdict.values()
print()
print(x)
# The list of the values is a view of the dictionary, meaning that any changes done to the dictionary
# will be reflected in the values list.
# Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
x = car.values()
print()
print(x) # before the change
car["year"] = 2020
print(x) # after the change
# Get Items
# The items() method will return each item in a dictionary, as tuples in a list.
# Get a list of the key:value pairs
x = thisdict.items()
print()
print(x)
# The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary
# will be reflected in the items list.
# Add a new item to the original dictionary, and see that the items list gets updated as well:
car = {"brand": "Ford", "model": "Mustang", "year": 1964}
x = car.items()
print()
print(x) # before the change
car["year"] = 2020
print(x) # after the change
# Check if Key Exists
# To determine if a specified key is present in a dictionary use the in keyword:
# Check if "model" is present in the dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
# Change Values
# You can change the value of a specific item by referring to its key name:
# Change the "year" to 2018:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict["year"] = 2018
print()
print(thisdict)
# Update Dictionary
# The update() method will update the dictionary with the items from the given argument.
# The argument must be a dictionary, or an iterable object with key:value pairs.
# Update the "year" of the car by using the update() method:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.update({"year": 2020})
print()
print(thisdict)
# Adding Items
# Adding an item to the dictionary is done by using a new index key and assigning a value to it:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict["color"] = "red"
print()
print(thisdict)
# Update Dictionary
# The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
# The argument must be a dictionary, or an iterable object with key:value pairs.
# Add a color item to the dictionary by using the update() method:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.update({"color": "red"})
print()
print(thisdict)
# Removing Items
# There are several methods to remove items from a dictionary:
# The pop() method removes the item with the specified key name:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.pop("model")
print()
print(thisdict)
# The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.popitem()
print()
print(thisdict)
# The del keyword removes the item with the specified key name:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
del thisdict["model"]
print()
print(thisdict)
# The del keyword can also delete the dictionary completely:
"""
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
del thisdict
print()
print(thisdict) # this will cause an error because "thisdict" no longer exists.
"""
# The clear() method empties the dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.clear()
print()
print(thisdict)
# Loop Through a Dictionary
# You can loop through a dictionary by using a for loop.
# When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
# Print all key names in the dictionary, one by one:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
for x in thisdict:
print(x)
# Print all values in the dictionary, one by one:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
for x in thisdict:
print(thisdict[x])
# You can also use the values() method to return values of a dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
for x in thisdict.values():
print(x)
# You can use the keys() method to return the keys of a dictionary:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
for x in thisdict.keys():
print(x)
# Loop through both keys and values, by using the items() method:
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print()
for x, y in thisdict.items():
print(x, y)
|
0ff5e10c2173301e12bff7727520d318ac6427a7 | Jaamunozr/Archivos-python | /Archivos Python Documentos/Cifrados/Python Prueba/AES_Encriptar.py | 1,944 | 3.5 | 4 | print ('-'*120)
print ('\n ALGORITMO DE ENCRIPTACION AES \n ')
def Alg_AES():
while True:
try:
llave= input ('Indique el archivo en que se encuentra alojada la llave (ejm: "llave.txt"): \n \n')
key = open(llave, 'rb')
key = key.read()
key = key [:-1]
break
except FileNotFoundError:
print ('''\n Archivo ""''' + llave+ '''"" no encontrado\n''')
from Crypto.Cipher import AES
from Crypto import Random
#Llamamos el archivo con la llave secreta de 16 bit (Se puede con 16, 24 o 32bits)
def encriptar(MensajeE):
MensajeE = MensajeE
#Se pasa por parametro al cifrado
iv = Random.new().read(AES.block_size)
#Se llama la clase AES y se cre un nuevo cifrado
cifrado = AES.new(key, AES.MODE_CFB, iv)
#Aqui se pasa la llave, luego se cita la libreria MODE
#Ahora encriptamos el mensaje
msg = iv + cifrado.encrypt(MensajeE)
while True:
try:
Encriptado = input ('\n Indique el nombre del nuevo archivo encriptado (ejm: " encriptado.txt"): \n \n')
f = open(Encriptado, 'wb')
#Argumento a escribir debe ser de tipo binario 'wb'
#Autores aseguran que es para archivos vacios, sin texto
f.write(msg)
f.close
break
except FileNotFoundError:
print ('''\n Archivo ""''' + Sin_Encriptar + '''"" no valido\n''')
#Aquí podemos hacer el llamado de lo que queremos encriptar
while True:
try:
Encriptado = input ('\n Indique el nombre del archivo a encriptar (ejm: "AES encriptar.txt"): \n \n')
TSE = open (Encriptado, 'rb')
TSE = TSE.read()
encriptar(TSE)
break
except FileNotFoundError:
print ('''\n Archivo ""''' + Encriptado + '''"" no valido\n''')
#Alg_AES()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.