blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
6d595915c78424f87e1b1587dcc1d00472fa200f | Mansi1096/testrepo | /strings.py | 364 | 3.765625 | 4 | <<<<<<< HEAD
for i in range (0,6):
n=input("enter the strings")
m=input("enter the character")
if m is n[0]:
print(n)
else:
print("wrong!!!")
=======
for i in range (0,6):
n=input("enter the strings")
m=input("enter the character")
if m is n[0]:
print(n)
else:
print("wrong!!!")
>>>>>>> 2ab4ec5da217893e10e6f82d0e0178ebc8b11ab9
|
5ab04ddcf6089a09688aad722abdca9aa214acbc | Cxov80415/Eric_PsychoPy2018 | /ex18.py | 460 | 3.796875 | 4 | def print_three(*args):
arg1, arg2, arg3 = args
print ("arg1: %r, arg2: %r, arg3: %r" % (arg1, arg2, arg3))
def print_three_again(arg1, arg2, arg3):
print ("arg1: %r, arg2: %r, arg3: %r" % (arg1, arg2, arg3))
def print_one(arg1):
print ("arg1: %r" % arg1)
def print_OK(arg3):
print ("arg3: %r" % arg3)
print_three("Zed","Shaw","Eric")
print_three_again("Zed","Shaw","Eric")
print_one("First!")
print_OK("ok")
|
0afcdd1b460d404300305ada8fbcd91fc78611db | threexc/SYSC5001 | /assignment_3/test_uniformity.py | 739 | 3.53125 | 4 | #!/usr/bin/python3
# test_uniformity calculates the max D value for evaluating data sets with the
# Kolmogorov-Smirnov test
def test_uniformity(filename):
data = []
D_plus_values = []
D_minus_values = []
count = 0
with open(filename) as f:
for line in f:
data.append(float(line.strip('\n').replace('"','')))
f.close()
count = len(data)
D_plus_values = [0]*count
D_minus_values = [0]*count
for i in range(0,count):
D_plus_values[i] = (i+1)/count - data[i]
D_minus_values[i] = data[i] - i/count
D_plus = max(D_plus_values)
D_minus = max(D_minus_values)
D_value = max(D_plus, D_minus)
return D_value
if __name__ == '__main__':
print("The D value for this set is: " + str(test_uniformity("7_20_data")) + "\n")
|
d078ba46d8fe58b23aaf3265655069a50d016e02 | orez-/Orez-Summer-2012 | /Tactics/skills.py | 7,367 | 3.625 | 4 | import pygame
import random
import sys
from string import lowercase as alphabet
from math import cos, sin, pi
from constants import SCREEN_SIZE
try:
seed = int(sys.argv[1])
except:
seed = random.randint(0, 2 ** 32 - 1)
random.seed(seed)
print seed
vowel = "aeiou"
consonant = ''.join(filter(lambda x: x not in vowel, alphabet))
SKILL_RADIUS = 12
DNA_RADIUS = 70
DNA_STEP = 50
DNA_TWIST = pi / 8
"""
UP, RIGHT, DOWN, LEFT, IN = (2 ** i for i in xrange(5))
data = {"One": {"next": {UP:"Two"}, "pos":(50, 50)},
"Two": {"next": {LEFT|IN: "One"}, "pos":(200, 200)}}
"""
def random_word(length=8):
toR = random.choice(consonant)
while len(toR) < length:
toR += random.choice(vowel)
eh = random.randint(1, 3)
if eh == 1:
toR += random.choice(vowel)
toR += random.choice(consonant)
if eh == 3:
toR += toR[-1]
return toR[:length].title()
def arc(surface, color, rect, start_angle, end_angle, width):
while start_angle > end_angle:
end_angle += 2 * pi
pygame.draw.arc(surface, color, rect, -end_angle, -start_angle, width)
class SkillHelix:
def __init__(self):
self.moving = 0
self.cur_y = 0
self.viewangle = 0
names = list(set(random_word() for _ in xrange(20)))
self.skills = {n: {"next": [] if i % 2 else names[i + 1: i + 3], "color": tuple(random.randint(0, 0xFF) for _ in xrange(3))} for i, n in enumerate(names)}
self.orbsurface = pygame.Surface(SCREEN_SIZE, pygame.SRCALPHA) # size might be wrong
self.linesurface = pygame.Surface(SCREEN_SIZE)
self.init_skills(names[0])
self.redraw()
def keep_moving(self):
if self.moving:
if int(self.cur_y) != int(self.cur_y + self.moving) or self.cur_y * (self.cur_y + self.moving) <= 0:
self.cur_y = int(round(self.cur_y+self.moving))
self.moving = 0
else:
self.cur_y += self.moving
self.redraw()
def set_viewangle(self, degrees):
self.viewangle = degrees * pi / 180
self.redraw()
def move(self, direction):
if abs(direction) != 1:
raise ValueError("Directional values only")
self.moving = direction * .125
self.cur_y += self.moving
def init_skills(self, job, pos=(-1, 0)):
self.skills[job]["pos"] = pos
self.skills[job]["angle"] = (DNA_TWIST * pos[1]) % (2 * pi)
self.skills[job]["done"] = True
up = False
for next in self.skills[job]["next"]:
self.init_skills(next, (pos[0] * (up * 2 - 1), pos[1] + up))
up = True
def draw_orb(self, orb):
for color, wid in ((orb["color"], 0), ((0, ) * 3, 2)):
if orb["done"]:
orb["curpos"] = map(int, (orb["pos"][0] * DNA_RADIUS * cos(orb["angle"] - (DNA_TWIST * self.cur_y) % (2 * pi)) + SCREEN_SIZE[0] / 2,
sin(self.viewangle) * orb["pos"][0] * DNA_RADIUS * sin(orb["angle"] - (DNA_TWIST * self.cur_y) % (2 * pi)) + SCREEN_SIZE[1] / 2 + cos(self.viewangle) * (orb["pos"][1] - self.cur_y) * DNA_STEP))
#(orb["pos"][1]-self.cur_y)*DNA_STEP+250))
#_y = cy+Math.sin(angle+mod-Math.PI/2-fullstep)*spinradius*Math.sin(viewangle) + cz*Math.cos(viewangle);
pygame.draw.circle(self.orbsurface, color, orb["curpos"], SKILL_RADIUS, wid)
def redraw(self):
self.linesurface.fill((0xFF, )*3)
self.orbsurface.fill((0, )*4)
for skill in self.skills:
self.draw_orb(self.skills[skill])
for skill in self.skills:
for next in self.skills[skill]["next"]:
pygame.draw.line(self.linesurface, (0, ) * 3 ,
self.skills[skill]["curpos"],
self.skills[next]["curpos"], 2)
def reblit(self, screen):
screen.blit(self.linesurface, (0,0))
screen.blit(self.orbsurface, (0,0))
class SkillWeb:
def __init__(self):
self.view_pos = [0,0]
self.orbsurface = pygame.Surface(SCREEN_SIZE, pygame.SRCALPHA) # size might be wrong
self.linesurface = pygame.Surface(SCREEN_SIZE)
self.linesurface.fill((0xFF, ) * 3)
self.skills = {}
names = list(set(random_word() for _ in xrange(20)))
self.job = names[0]
for name in names:
self.skills[name] = {"next":[random.choice(names[len(self.skills): ]) for x in xrange(int(random.randint(4, 8) / 4))] if len(self.skills) - len(names) else [],
"color":(random.randint(0,255), random.randint(0,255), random.randint(0,255)),
"done":False}
self.init_skills(self.job)
self.redraw()
def circle_radius(self, circle_num):
return SKILL_RADIUS * circle_num * 5
def init_skills(self, job, circle=0, last_angle=None, direction=None):
if not self.skills[job]["done"]:
if last_angle is None:
last_angle = random.randint(0, 7)
if direction is None:
direction = random.randint(0, 1) * 2 - 1
self.skills[job].update({
"circle":circle,
"angle":last_angle,
"pos":(int(cos(pi * last_angle / 4) * self.circle_radius(circle)) + SCREEN_SIZE[0] / 2,
int(sin(pi * last_angle / 4) * self.circle_radius(circle)) + SCREEN_SIZE[1] / 2),
"done":True
})
for next in self.skills[job]["next"]:
maybe_angle = (last_angle + direction + 8) % 8
if not circle or filter(lambda x:x[1]["done"] and x[1]["circle"] == circle and x[1]["angle"] == maybe_angle, self.skills.items()):
pos = self.init_skills(next, circle+1, last_angle, random.randint(0,1) * 2 - 1)[0]
pygame.draw.line(self.linesurface, (0, ) * 3, self.skills[job]["pos"], pos, 2)
else:
pos, ang = self.init_skills(next, circle, maybe_angle, direction)
r = self.circle_radius(circle)
#pygame.draw.line(self.linesurface, self.skills[job]["color"], self.skills[job]["pos"], pos, 2)
arc(self.linesurface, self.skills[job]["color"], (-r+SCREEN_SIZE[0] / 2, -r+SCREEN_SIZE[1] / 2, 2 * r, 2 * r), last_angle * pi / 4, ang * pi / 4, 2)
pygame.draw.line(self.linesurface, self.skills[job]["color"],
(int(cos(pi * ang / 4) * self.circle_radius(circle)) + SCREEN_SIZE[0] / 2,
int(sin(pi * ang / 4) * self.circle_radius(circle)) + SCREEN_SIZE[1] / 2), pos, 2)
return self.skills[job]["pos"], self.skills[job]["angle"]
def draw_orb(self, orb):
for color, wid in ((orb["color"], 0), ((0, ) * 3, 2)):
if orb["done"]:
pygame.draw.circle(self.orbsurface, color, orb["pos"], SKILL_RADIUS, wid)
def redraw(self):
self.orbsurface.fill((0, )*4)
for skill in self.skills:
self.draw_orb(self.skills[skill])
def reblit(self, screen):
screen.blit(self.linesurface, (0, 0), (self.view_pos[0], self.view_pos[1], SCREEN_SIZE[0], SCREEN_SIZE[1]))
screen.blit(self.orbsurface, (0, 0), (self.view_pos[0], self.view_pos[1], SCREEN_SIZE[0], SCREEN_SIZE[1]))
|
dc15be912cf9927fb8882770b25a2dba9a680fe3 | bhornung/python-utilities | /source/io_utils.py | 1,455 | 3.953125 | 4 | def load_from_json(path_to_db):
"""
Loads the contents of a json file.
Parameters:
path_to_db (str) : full path to a json file.
Returns:
data_ (object) : the loaded object.
"""
with open(path_to_db, 'r') as fproc:
data_ = json.load(fproc)
return data_
def load_dict_from_json(path_to_db, convert_keys_to_int = False):
"""
Loads a dictionary from a json file. It optionally tries to convert the keys to integers.
(Integers cannot be keys in standard json.)
Parameters:
path_to_db (str) : full path to a json file.
convert_keys_to_int (bool) : whether to coerce keys to ints. Default: False
Returns:
dict_ ({:}) : the loaded dictionary
"""
with open(path_to_db, 'r') as fproc:
dict_ = json.load(fproc)
if not isinstance(dict_, dict):
raise TypeError("Loaded object is not a dictionary.")
if convert_keys_to_int:
try:
dict_ = {int(k) : v for k, v in dict_.items()}
except:
raise
return dict_
def save_to_json(path_to_db, data):
"""
Saves an obect to a file.
Parameters:
path_to_db (str) : full path to file
data (object) : object to save
"""
with open(path_to_db, 'w') as fproc:
json.dump(data, fproc, indent = 4) |
35617eb0f37c0dbe7c5c79740d7d1a97c3818f9c | jchamish/python3-algorithms | /Daily_code_problems/anytwo_numbers_add_up_k.py | 898 | 3.890625 | 4 | # Problem Number 1
# Good morning! Here's your coding interview problem for today.
#
# This problem was recently asked by Google.
#
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
#
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
#
# Bonus: Can you do this in one pass?
import random
array_numbers = [10, 15, 3, 7]
# N^2
def sulotion_1(arr, k):
for idx, val in enumerate(arr):
for val_2 in arr[idx:]:
if val+val_2 == k:
return True
return False
def sulotion_2(arr, k):
for idx, val in enumerate(arr):
remainder = k - val
if remainder in arr[idx:]:
return True
return False
random_number = random.randint(1,21)
print(random_number)
print(sulotion_1(array_numbers, random_number))
print(sulotion_2(array_numbers, random_number)) |
2b1a783d4c28b82fd0d0aa2b57f00d2427163544 | maskani-moh/algorithms | /island_size.py | 3,003 | 4 | 4 | """
Two solutions presented for the Exercise 695 of Leetcode.
The aim is to find the maximum area of an island given a binary grid.
The idea is to find the maximum size of the connected component (4 directions)
in the grid.
Method: Depth-first Search
"""
def maxAreaOfIsland(grid):
"""
Function returning the greatest area of all the connected components
in the grid (if any).
:param grid: List[List[int]]
:return: int
"""
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
and (r, c) not in seen and grid[r][c]):
return 0
seen.add((r, c))
return (1 + area(r + 1, c) + area(r - 1, c) +
area(r, c - 1) + area(r, c + 1))
return max(area(r, c)
for r in range(len(grid))
for c in range(len(grid[0])))
def maxAreaOfIsland2(grid):
"""
Function returning the greatest area of all the connected components
in the grid (if any).
:param grid: List[List[int]]
:return: int
"""
# Size of the matrix grid
m, n = len(grid), len(grid[0])
# Def custom class
class Node:
def __init__(self, i, j):
self.value = grid[i][j]
self.visited = False
# Corners of the grid
# TODO: Fix recursion issue here
if i == 0 and j == 0:
self.neighbors = [Node(0, 1), Node(1, 0)]
elif i == m - 1 and j == n - 1:
self.neighbors = [Node(m - 1, n - 2), Node(m - 2, n - 1)]
elif i == 0:
self.neighbors = [Node(0, j - 1), Node(0, j + 1),
Node(1, j + 1)]
elif j == 0:
self.neighbors = [Node(i - 1, 0), Node(i, 1),
Node(i + 1, 0)]
elif i == m - 1:
self.neighbors = [Node(m - 2, j), Node(m - 1, j + 1)]
elif j == n - 1:
self.neighbors = [Node(i, n - 2), Node(i - 1, n - 1),
Node(i + 1, n - 1)]
else:
self.neighbors = [Node(i - 1, j), Node(i, j - 1),
Node(i, j + 1), Node(i + 1, j + 1)]
connected_compo = []
def exploreNode(node):
tmp = []
if node.visited:
return tmp
node.visited = True
if node.value == 0:
return tmp
tmp.append(node)
for PosNeighbor in [n for n in node.neighbors if n.value == 1]:
tmp.extend(exploreNode(PosNeighbor))
return tmp
for i in range(0, m):
for j in range(0, n):
node = Node(i, j)
if node.visited:
continue
connected_compo.append(exploreNode(node))
print(connected_compo)
return max([len(c) for c in connected_compo])
if __name__ == "__main__":
grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
print(maxAreaOfIsland(grid)) |
4a3edaf4fd696b7a6ab15bbf2031299c04c1ddf8 | hautbli/algorithm | /programmers_codingtest/level1/codingtest1_ex16.py | 472 | 3.75 | 4 | # 행렬의 덧셈
def solution(arr1, arr2):
answer = []
for ar1, ar2 in zip(arr1, arr2):
line = []
for a1, a2 in zip(ar1, ar2):
line.append(a1 + a2)
answer.append(line)
return answer
print(solution([[1, 2], [2, 3]], [[3, 4], [5, 6]]))
import numpy as np
def sumMatrix(A, B):
A = np.array(A)
B = np.array(B)
answer = A + B
return answer.tolist()
print(sumMatrix([[1, 2], [2, 3]], [[3, 4], [5, 6]])) |
8295833dcb16487914fb9e42e15439091cc442fe | sanskarjain2507/full-stack-development | /Django/Automobile shop/class_practice/class1.py | 411 | 3.8125 | 4 | class Student:
'''this is class'''
clg_name='bit'
def __init__(self):
self.__name="sanskar jain"
self.age=20
def input(self):
self.__name="sanskar"
self.age=20
def show(self):
print(f"name: {self._Student__name}")
print(f"age: {self.age}")
print(f"colege name: {Student.clg_name}")
s1=Student()
s1.input()
print(s1._Student__name)
s1.show() |
8053045835240b92902ae0ad6ca65defcadf73a3 | NikitaKirin/Linear-equation-solver-calculator | /main.py | 1,212 | 3.78125 | 4 | import core.method_of_Cramer as calc
matrix_of_variables = []
matrix_of_free = []
count_line = 0
count_free_line = 0
while True:
line = input(
'Вводите коэффициенты при неизвестных построчно через пробел! - для остановки ввода введите Stop' + '\n')
if line == "Stop":
break
else:
line = line.split(' ')
current_line = [int(i) for i in line]
count_line += 1
matrix_of_variables.append(current_line)
while True:
line = input(
'Вводите свободные переменные построчно! - для остановки ввода введите Stop' + '\n')
if line == "Stop":
break
else:
line = line.split(' ')
current_line = [int(i) for i in line]
count_free_line += 1
matrix_of_free.append(current_line)
if count_line != count_free_line:
print("Данные введены не в правильном формате")
else:
answer = calc.method_of_cramer(matrix_of_variables, matrix_of_free)
print('Ответ:' + '\n')
for j in range(len(answer)):
print(f'X{j + 1} = {answer[j]}')
|
17b7b272d6760d87db456fea41ca171e99ed9cce | manoj0806/progate-python | /python_study_2/page4/script.py | 192 | 4.125 | 4 | fruits = ['apple', 'banana', 'orange']
# Get the elements of fruits using a for loop, and print 'I like ___s'
i=0
for fruit in fruits :
print("I like " +fruits[i],"s")
i+=1
|
23565631a8aa3b716b7d974a8d5f9b359c91b9d2 | paulettemaina/password_locker | /password_locker.py | 7,145 | 3.625 | 4 | #!/usr/bin/env python3.6
import pyperclip
import string
import random
from user_credentials import User, Credentials
def create_user(login, pword):
'''
Function to create a new user
'''
new_user = User(login,pword)
return new_user
def save_users(user):
'''
Function to save user
'''
user.save_user()
def find_user(login):
'''
Funtion that finds a user by a login and returns the user
'''
return User.find_by_login(login_name)
def check_existing_users(login):
'''
Function that checks if a user exists with that login and return a boolean
'''
return User.user_exist(login)
def create_credentials(website,username,p_key):
'''
Function to create a new credentials
'''
new_credentials = Credentials(website,username,p_key)
return new_credentials
def generate_password(self):
return generated_passwords
def save_credential(credentials):
'''
Function to save Credentials
'''
credentials.save_credentials()
def del_credentials(credentials):
'''
Function to delete a credentials
'''
credentials.delete_credentials()
def find_credentials(user_id):
'''
Funtion that finds a credentials by a user_id and returns the credentials
'''
return Credentials.find_by_user_id(user_id)
def check_existing_credential(user_id):
'''
Function that checks if a credentials exists with that user_id and return a boolean
'''
return Credentials.credentials_exist(user_id)
def display_credentials():
'''
Function that returns all the saved credentials
'''
return Credentials.display_credentials()
def copy_credentials_pass_key(user_id):
'''
Function that copies email to clipboard
'''
return Credentials.copy_pass_key(user_id)
def main():
print("WELCOME TO PASSWORD LOCKER. ")
print('\n')
while True:
print("Use these short codes :")
print("\n log - To login into your password_locker account, \n cu - To create a new password_locker account, \n fu - To find user account, \n ex -exit account ")
short_code = input().lower()
if short_code == 'cu':
print('\n')
print("To create a password_locker account kindly fill in the information below")
print("Enter your desired password_locker login name")
login = input()
print("Enter your desired password_locker password")
pword = input()
save_users(create_user(login,pword))
print('\n')
print(f"Welcome {login}. \n")
print("You have succesfully created a password locker account. You can now log in and save, display, delete or copy youe credentials.")
elif short_code == 'fu':
print(" \n Enter the login username to find the user account \n")
search_login = find_user(search_login)
print(f"Account {search_login.login} exists")
elif short_code == 'log':
print('\n')
print("Enter you password_locker login id ...")
login = input()
print("Enter you password_locker login password ...")
pword = input()
if check_existing_users(login):
logged_user = find_user(login)
if logged_user == pword:
print(f"Welcome {login}")
while True:
print('\n')
print("Please use the following short codes \n cc-To create a new credential, \n cpass- To generate a new password, \n fc - To find a credential, \n dc- To display credentials, \n del- to delete a credential, \n cp- To copy a credential's password \n ex- to exit")
log_shortcode=input()
# credential_user =logged_user
if log_shortcode == 'cc':
print('\n')
print("Fill in the information below to create a new credential")
print('\n')
print("Enter the website")
website=input()
print("Enter your username for the website")
username=input()
print("Enter your password for the website")
p_key=input()
save_credential(create_credentials(website,username,p_key))
print('\n')
print(f"You have created a new credential for {website}.")
print('\n')
elif log_shortcode == 'cpass':
print('\n')
print("Generate a new random password \n")
print(generate_password)
elif log_shortcode == 'dc':
print('/n')
if display_credentials():
for credentials in display_credentials():
print(f"{credentials.site}, {credentials.user_id}, {credentials.pass_key}")
print('\n')
else:
print("\n Nothing to display")
elif log_shortcode == 'fc':
print('/n')
print("Enter your username for the website you want to find your stored credentials")
search_username = input()
if check_existing_credential(search_username):
search_credential = find_credentials(search_username)
print(f"{search_username.username} , {search_contact.website}")
print('-' *20)
else:
print(" \n That credential does not exist")
elif log_shortcode == 'del':
print('/n')
print("Enter the username of the credentials you want to delete")
del_username = input()
if check_existing_credential(del_username):
search_del_credentials = find_credentials(del_username)
del_credential = del_credentials(search_del_credentials)
print(f"Deleted credentials of {website} with the {del_username} username ")
else:
print(" \n That credential does not exist")
elif log_shortcode == 'cp':
print('/n')
print("Enter the username of the credential you want to copy")
copy_user = input()
if check_existing_credential(copy_user):
search_copy_user = find_credentials(copy_user)
pyperclip.copy(search_copy_user.pass_key)
#copy_search_pass_key = copy_credentials_pass_key(search_copy_user)
# print("Copy: {copy_search_pass_key}")
print(f"Password has been copied {search_copy_user.pass_key} ")
else:
print(" \n Those credentials don't exist.")
elif log_shortcode =='ex' :
print("Bye...")
break
else:
print("I really didn't get that. Please use shortcode, Thank you.")
if __name__ == '__main__':
main()
|
a8c3af298eb233d532edbf4186168d230c30cbb4 | asfinahamza/python_basics | /palindrome.py | 655 | 3.828125 | 4 | # str=input('enter a word : ')
# status=0
# l=len(str)
# for i in range(0,int(len(str)/2)):
# if(str[i] != str[l-i-1]):
# status=1
# if(status==1):
# print('no')
# else:
# print('yss')
# string=input('enter the string: ')
# rev_str=string[::-1]
# print(rev_str)
# if(string==rev_str):
# print('it is a palindrome')
# else:
# print('sorry..not a palindrome')
string=input('enter the string: ')
l=len(string)
status='true'
for x in range(int(l/2)):
print(string[x])
if(string[x]!=string[l-x-1]):
status='false'
else:
status='true'
if(status=='true'):
print('yesss')
else:
print('noooo')
|
60b1548ca27bdb9be62743c75f1409683a9e5e19 | vishwanath79/PythonMisc | /Py201/29Lock.py | 534 | 3.53125 | 4 | from multiprocessing import Process, Lock
def printer(item,lock):
""" Prints out the item that was passed in """
lock.acquire()
print('process')
try:
print(item)
finally:
lock.release()
if __name__ == '__main__':
lock = Lock()
items = ['tango', 'foxtrot', 10]
# Loop over list and create a process for each item. Next process in line will wait for the lock to release before proceeding
for item in items:
p = Process(target=printer, args=(item,lock))
p.start()
|
125dba0146620cdff4e0353f63e7123411cf6be6 | ThisIsRoy/leetcode | /easy/rotated-digits.py | 806 | 3.703125 | 4 | # Runtime can be improved
class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
count = 0
for num in range(N + 1):
if self.valid_rotate(num):
count += 1
return count
def valid_rotate(self, n):
"""
Checks if n is valid after rotating each digit
"""
inval_set = set(['3', '4', '7'])
changed_set = set(['2', '5', '6', '9'])
changed = False
for char in str(n):
if char in inval_set:
return False
elif not changed and char in changed_set:
changed = True
return True if changed else False |
18be706141e79076e3c674dcb8dec85a1d50048d | Wolverinepb007/Python_Assignments | /Python/greater.py | 174 | 4 | 4 | a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
print(a," is greatest the number.")
else:
print(b," is greatest the number.")
|
9054372d90ef79898c94434adcf32331c389b29a | YiHerngOng/ME599 | /ME599_HW3/optimizer.py | 1,610 | 3.65625 | 4 | #!/usr/bin/env python
#Written by Yi Herng Ong
#ME 599 Homework 3
#Note: This code takes about 2 seconds to compute the lowest cost
import numpy as np
def optimize(simulator, record_waypoints, done):
baseline_cost = simulator.evaluate([(-10, -10), (10, 10)])
waypoints = [(-10, -10), (0, 0), (10, 10)]
record_waypoints(waypoints)
best_cost = baseline_cost
best_waypoints = waypoints[:]
cost = 0
arrx = np.arange(-10,11)
arry = np.arange(-10,11)
new_list = [(-10,-10),(10,10)]
new_list1 = []
# Put this while statement in here to play nice with the grading software
while not done():
#Start adding intermediate waypoints into new_list
for i in arrx:
for j in arry:
#if current intermediate waypoint is in the list, jump to next iteration
if (i,j) in new_list:
continue
new_list.append((i,j))
#Sort the list after added new intermediate waypoints
new_list = sorted(new_list)
cost = simulator.evaluate(new_list)
if cost < best_cost:
best_cost = cost
else:
new_list.remove((i,j))
#Add 300 more waypoints in between waypoints
for k in xrange(len(new_list)):
if k > len(new_list) - 2:
break
x = np.linspace(new_list[k][0], new_list[k+1][0],300)
y = np.linspace(new_list[k][1], new_list[k+1][1],300)
for l in xrange(len(x)):
new_wp = (x[l], y[l])
new_list1.append(new_wp)
best_cost = simulator.evaluate(new_list1)
best_waypoints = new_list1[:]
record_waypoints(best_waypoints)
|
8c1da0f90add339328ae60f632520d7be392e1fb | rapidcode-technologies-private-limited/Python | /medhavi/assignment1/7.py | 149 | 4.09375 | 4 | #python program to swap two elements in a list
array=[1,2,35,4]
t=array[0]
array[0]=array[1]
array[1]=t
print('after'+' '+ 'swaping'+' '+'=',array)
|
69f032b2c01996a8cc55e4793adb573e076f4f8d | panditdandgule/Pythonpractice | /Fibonacci.py | 431 | 4.34375 | 4 | # Program to display the Fibonacci sequence up to n-th term where n is provided by the user
n=int(input())
n1=0
n2=1
count=0
if n<=0:
print("Please enter a positive number")
elif n==1:
print('Fibonacci sequance upto:',n)
print(n1)
else:
print('Fibonacci sequance upto:',n)
while count<n:
print(n1,end=', ')
nth=n1+n2
n1=n2
n2=nth
count+=1
|
5f4d2fa34d042b71e861815b3b9a645fb55b9a04 | J4VJ4R/pythonCourse | /conditionals/if.py | 152 | 3.890625 | 4 | #!/usr/bin/python3
uno = 15
dos = 15
if uno < dos:
print ("is menor")
elif uno == dos:
print ("Vamos al mar")
else:
print ("es more big")
|
6ae2a5d02c4da06fb0a46b721b807cc34759ef2e | d1sd41n/holbertonschool-machine_learning | /math/0x03-probability/binomial.py | 1,581 | 3.75 | 4 | #!/usr/bin/env python3
"""docs"""
class Binomial():
"""docs"""
def __init__(self, data=None, n=1, p=0.5):
"""docs"""
if data is None:
if n <= 0:
raise ValueError("n must be a positive value")
elif p <= 0 or p >= 1:
raise ValueError("p must be greater than 0 and less than 1")
else:
self.n = int(n)
self.p = float(p)
else:
if type(data) != list:
TypeError("data must be a list")
elif len(data) < 2:
ValueError("data must contain multiple values")
else:
mean = sum(data) / len(data) # mean = n*p
var = sum([(data[x] - mean) ** 2 for x in range(len(data))]
) / len(data)
self.p = (1 - (var / mean))
n = mean / self.p
self.n = int(round(n))
self.p = mean / self.n
def pmf(self, k):
"""docs"""
k = int(k)
if k < 0:
return 0
else:
ww = factorial(self.n) / (factorial(k) * factorial(self.n - k))
return ww * (self.p ** k) * ((1 - self.p) ** (self.n - k))
def cdf(self, k):
"""docs"""
k = int(k)
if k < 0:
return 0
else:
c = 0
for i in range(k + 1):
c += self.pmf(i)
return c
def factorial(k):
"""docs"""
if k == 0:
return 1
else:
return k * factorial(k - 1)
|
13d336c2bccc88b11793702bbbff85138d8d090d | Oking123/CFG_Generator | /recursion.py | 370 | 3.796875 | 4 | x = 0
y = 0
signal = [True]
if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]):
print(1)
if grid[x][y] == 1:
print(1)
else:
if x == 0 or x == len(grid) - 1 or y == 0 or y == len(grid[0]) - 1:
signal[0]= False
grid[x][y] = 1
travel(x - 1, y, signal)
travel(x + 1, y, signal)
travel(x, y - 1, signal)
travel(x, y + 1, signal)
|
f60c00c8e7adf14ff95416c9f518d8a4672e3750 | Iararibeiro/coding-challenges | /easy/arrays/MaximumSubArray.py | 629 | 3.5 | 4 | def solution(nums):
result = float('-inf')
for i in range(0, len(nums)):
current_sum = 0
for j in range(i, len(nums)):
current_sum += nums[j]
result = max(result, current_sum)
return result
def solutionDP(nums):
currentSubArray = nums[0]
maxSubArray = nums[0]
for i in range(1, len(nums)):
currentSubArray = max(nums[i], currentSubArray + nums[i])
maxSubArray = max(maxSubArray, currentSubArray)
return maxSubArray
print(solutionDP([-2,-1,-3,4,-1,2,1,-5,4]))
print(solutionDP([1]))
print(solutionDP([5,4,-1,7,8]))
print(solutionDP([-2,1])) |
4f1ebb0f1b25ea6a4cd9622a46ee0d3cade33f60 | suifengqjn/python_study | /7迭代器与生成器/1什么是迭代协议.py | 435 | 4.0625 | 4 |
# 迭代器是什么
# 迭代器是访问集合内元素的一种方式,一般用来遍历数据
# 迭代器和用下标访问的方式不一样,迭代器是不能返回的
# 只要实现 __iter__ 就是可迭代的 成为迭代器还需要实现 __next__
from collections.abc import Iterable,Iterator
list = [1, 2, 3, 4]
# 创建迭代器对象
it = iter(list)
print(isinstance(it, Iterable))
print(isinstance(it, Iterator))
|
4f5a0579f48fe6b2d4395730c69fe4a5281a35e0 | Sean-Moon/algo | /goorm5.py | 1,074 | 3.5625 | 4 | #-*- coding: utf-8 -*-
#알파벳 빈도
from collections import Counter
texts = input().split()
lower_caracters = []
while(texts):
lower_caracters += list(texts.pop().lower())
counter = Counter(lower_caracters)
print("a : %s" % counter['a'])
print("b : %s" % counter['b'])
print("c : %s" % counter['c'])
print("d : %s" % counter['d'])
print("e : %s" % counter['e'])
print("f : %s" % counter['f'])
print("g : %s" % counter['g'])
print("h : %s" % counter['h'])
print("i : %s" % counter['i'])
print("j : %s" % counter['j'])
print("k : %s" % counter['k'])
print("l : %s" % counter['l'])
print("m : %s" % counter['m'])
print("n : %s" % counter['n'])
print("o : %s" % counter['o'])
print("p : %s" % counter['p'])
print("q : %s" % counter['q'])
print("r : %s" % counter['r'])
print("s : %s" % counter['s'])
print("t : %s" % counter['t'])
print("u : %s" % counter['u'])
print("v : %s" % counter['v'])
print("w : %s" % counter['w'])
print("x : %s" % counter['x'])
print("y : %s" % counter['y'])
print("z : %s" % counter['z'])
#print(pd.Series(lower_caracters).value_counts()) |
4f4e50bf42368947439e225128fa9a5803bc57f3 | cairoas99/Projetos | /PythonGuanabara/exers/listaEx/Mundo2/ex063.py | 163 | 4.09375 | 4 | n = int(input('Insira um numero: '))
c = 0
def fib(x):
if x == 1 or x == 2:
return 1
elif x > 0:
return (fib(x-1)+fib(x-2))
print(fib(n)) |
674095b45964b534f92ebe09f600ef0ec686dae6 | nikita-chudnovskiy/ProjectPyton | /00 Базовый курс/Zadachi/011 Строки методы/07 Сколько раз встречается буква h 1 или больше.py | 601 | 4 | 4 | # Если она встречается более 2 раз выведите индекс 1 и посл числа
a = 'hello world'
print(a.count('l'),'вхождения') # ищем сколько вхождений
if a.count('l')==1: # если 1 то пишем
print(a.find('l')) # под каким индексом
elif a.count('l')>=2: # если находим больше 2
print('под индексом',a.find('l'),'под индексом',a.rfind('l')) # то пишем под каким первый find и последний rfind |
10d802bbb014cb3bc871fdd00551c20cfaa5ddf9 | Renwoxin/leetcode | /array/hg_832_Flipping_an_Image.py | 3,024 | 4.40625 | 4 | """
Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the
resulting image.To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].To invert an image means that
each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results
in [1, 0, 0].
Example 1:
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
Example 2:
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Notes:
1.1 <= A.length = A[0].length <= 20
2.0 <= A[i][j] <= 1
"""
# 整体思路
# 1. 先将数组进行行对称
# 2. 再对每个元素进行取反
# 参考答案有一些很实用的方法
# row[~i] = row[-i-1] = row[len(row) - 1 - i]
# a,b = b,a——python中的交换变量值
# row[i] ^ 1 —— row[i] 与 1 进行按位异或
# 标准答案
class Solution(object):
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for row in A:
for i in range(int((len(row) + 1) / 2)):
"""
In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i]
helps us find the i-th value of the row, counting from the right.
"""
row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1
return A
"""
Complexity Analysis
Time Complexity: O(N)O(N), where N is the total number of elements in A.
Space Complexity: O(1)O(1) in additional space complexity.
"""
A = Solution()
B = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
C = A.flipAndInvertImage(B)
print(C)
# 网上参考答案
# class Solution:
# def flipAndInvertImage(self, A):
# """
# :type A: List[List[int]]
# :rtype: List[List[int]]
# """
# rows = len(A)
# cols = len(A[0])
# for row in range(rows):
# A[row] = A[row][::-1]
# for col in range(cols):
# A[row][col] ^= 1
# return A
# # 错误答案,但是还是有点用 by myself
# 程序中求取m,n的方法可以用len()代替
# 向上取整可以用int(n/2+1)代替
# import numpy as np
# import math
#
# A = [[1,1,0,0],[1,0,1,0],[1,0,0,0]]
#
# m,n = np.shape(A)
#
# for i in range(m):
# for j in range(math.ceil(n/2)):
# a = A[i][j]
# A[i][j] = A[i][n-j-1]
# A[i][n-j-1] = a
# print(A)
#
# m,n = np.shape(A)
#
# for i in range(m):
# for j in range(n):
# if A[i][j] == 0:
# A[i][j] = 1
# else:
# A[i][j] = 0
# print(A) |
30ccd0ae2a813d68d6d31c42be7d3771d575b7d1 | syurskyi/Python_Topics | /060_context_managers/_exercises/104. Generators and Context Managers - Coding.py | 3,835 | 3.703125 | 4 | # # Generators and Context Managers
# # Let's see how we might write something that almost behaves like a context manager, using a generator function:
#
# print('#' * 52 + ' ### Generators and Context Managers')
#
#
# ___ my_gen
# t__
# print('creating context and yielding object')
# lst _ 1 2 3 4 5
# y___ l..
# f___
# print('exiting context and cleaning up')
#
#
# gen _ m.. # create generator
#
# lst _ n.. g.. # enter context and get "as" object
# print l..
# # [1, 2, 3, 4, 5]
# # ######################################################################################################################
#
# # next(gen) # exit context # StopIteration:
#
# # As you can see, the exiting context code ran. But to make this cleaner, we'll catch the StopIteration exception:
#
# print('#' * 52 + ' As you can see, the exiting context code ran.')
# print('#' * 52 + ' But to make this cleaner, we will catch the StopIteration exception:')
#
# gen _ m..
# lst _ n.. g..
# print l..
# t__
# n.. g..
# e_____ S..I..
# p____
# # creating context and yielding object
# # [1, 2, 3, 4, 5]
# # exiting context and cleaning up
# # ######################################################################################################################
#
#
# # Now let's write a context manager that can use the type of generator we wrote so we can use it using a with statement
# # instead:
# print('#' * 52 + ' Now lets write a context manager that can use the type of generator we wrote'
# ' so we can use it using a `with` statement instead:')
#
#
# c_ GenCtxManager
# ___ __i__ ____ gen_func
# ____._gen _ g.._f.
#
# ___ __e__ ____
# r_ n.. ____._g..
#
# ___ __e__ ____ exc_type exc_value exc_tb
# t__
# n.. ____._g..
# e___ S..I..
# p___
# r_ F..
#
#
# w__ G.. m._g. a_ lst
# print l..
# # creating context and yielding object
# # [1, 2, 3, 4, 5]
# # exiting context and cleaning up
# # ######################################################################################################################
#
# # Our GenCtxManager class is not very flexible - we cannot pass arguments to the generator function for example.
# # We are also not doing any exception handling...
# # We could try some of this ourselves. For example handling arguments:
#
# print('#' * 52 + ' Our `GenCtxManager` class is not very flexible -'
# ' we cannot pass arguments to the generator function for example.')
# print('#' * 52 + ' We are also not doing any exception handling...')
#
#
# c_ GenCtxManager
# ___ __i__ ____ gen_func 0a.. 00k..
# ____._gen _ g._f. 0a.. 00k..
#
# ___ __e__ ____
# r_ n.. ____._g..
#
# ___ __e__ ____ exc_type exc_value exc_tb
# t__
# n.. ____._g..
# e_____ S..I..
# p___
# r_ F..
#
#
# ___ open_file fname mode
# t__
# print('opening file...')
# f _ o.. f.. m..
# y____ f
# f_____
# print('closing file...')
# f.c..
#
#
# w__ G... open_file test.txt '_') a_ f
# print('writing to file...')
# f.w.. 'testing...'
# # opening file...
# # writing to file...
# # closing file...
# # ######################################################################################################################
#
# print('#' * 52 + ' ')
#
# w.. o.. test.txt a_ f
# print n.. f
# # testing...
# # ######################################################################################################################
#
# # This works, but is not very elegant, and we still are not doing much exception handling. In the next video,
# # we'll look at a decorator in the standard library that does this far more robustly and elegantly...
#
|
3c71007ba3f92f9f1ace1c84bf59de88b14da17a | AlphaCoderX/MyPythonRepo | /Assignment 8/Weather.py | 1,060 | 3.734375 | 4 | #Programmer Raphael Heinen
#Date 4/18/17
#Version 1.0
import json
import urllib2
import functions
def readJson():
city = functions.userString("Please enter a zip code or city name:")
print " "
url = 'https://api.apixu.com/v1/current.json?key=dcb629e49c894492b66150648172303&q=' + city
jsonTxt = urllib2.urlopen(url).read()
apixu = json.loads(jsonTxt)
return apixu
def printer(apixu):
print "Here is the weather for %s, %s" % (apixu['location']['name'],apixu['location']['region'])
print "%s and %s degrees (F)." % (apixu['current']['condition']['text'],apixu['current']['temp_f'])
print "It actually feels like %s (F)." % apixu['current']['feelslike_f']
print " "
again = functions.userString("Want to check another location? (y/n):")
return again
def main():
ask = True
while ask == True:
r = readJson()
a = printer(r)
if a == 'n':
ask = False
if a == 'y':
ask = True
main() |
490a2df88ffd95d3dfb014c40e1dc118ea6490dc | divyansh-gupta-0210/BinarySearch.io | /LongDistance.py | 1,018 | 3.5 | 4 | # Long Distance
# Given a list of integers nums, return a new list where each element in the new list is the number of smaller elements to the right of that element in the original input list.
# Constraints
# n ≤ 100,000 where n is the length of nums
# Example 1
# Input
# lst = [3, 4, 9, 6, 1]
# Output
# [1, 1, 2, 1, 0]
# Explanation
# There is 1 smaller element to the right of 3
# There is 1 smaller element to the right of 4
# There are 2 smaller elements to the right of 9
# There is 1 smaller element to the right of 6
# There are no smaller elements to the right of 1
# Example 2
# Input
# lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Output
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# Example 3
# Input
# lst = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Output
# [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
class Solution:
def solve(self, lst):
N = len(lst)
res = []
b = SortedList()
for n in lst[::-1]:
res.append(b.bisect_left(n))
b.add(n)
return res[::-1]
|
5233789df7e1c181a6b01480fdd40b563808d51f | sarabudlasoumyasri/20176080_Competitive-Programming | /Competitive-Programming/week-3/day5/url.py | 1,103 | 3.875 | 4 | def Base(string):
dict1={}
for i in range(len(string)):
dict1[i]=string[i]
return dict1
short = 7
shorturl={}
Long={}
count=0
base=Base("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
def shortmethod(url):
if (url in Long):
print("ShortURL Exists"+Long[url])
return
global count
s=""
k=count
count+=1
if (k==0):
s="0000000"
if (s not in shorturl):
shorturl[s]=url
Long[url]=s
print("short URL for "+url+" is https://ca.ke/"+s)
return
while(k!=0):
s=base[k%62]+s
k=k//62
l=len(s)
if (l<short):
for i in range(short-l):
s="0"+s
if (s not in shorturl):
shorturl[s]=url
Long[url]=s
print("https://ca.ke/"+s)
while (True):
print("\n\t1)Generate ShortURL\n\t2)Redirect ShortURL\n\t3)Stop\n\tYour option:",end="")
i=int(input())
if (i==1):
url=input("Enter URL: ")
shortmethod(url)
elif (i==2):
correct=input("Enter a short URL: ")
if shorturl.get(correct,None) is not None:
print("Redirect to "+shorturl[correct])
else:
print("URL does not exist")
elif(i==3):
break
else:
print("Please enter valid Input")
|
96e66221ceebd0b1653fce8eb8931d29ab48d9a5 | zspatter/network-simulation | /network_simulator/ConnectivityChecker.py | 4,071 | 3.84375 | 4 | from typing import Set, Optional
from network_simulator.Network import Network
class ConnectivityChecker:
"""
This class determines whether a given network is connected or not.
In a connected network, there exists a path between any given node
and all other nodes (no nodes exist that cannot be reached)
"""
@staticmethod
def is_connected(network: Network, nodes_encountered: Set[Optional[int]] = None,
source: int = None) -> bool:
"""
Returns bool indicating graph connectivity (path between all nodes).
This is a recursive DFS.
:param network: object representing a graph (network)
:param Set[int] nodes_encountered: set of node_id's encountered (None by default)
:param int source: node_id of start of search (None by default)
:return: bool indicating graph connectivity
:rtype: bool
"""
if not nodes_encountered:
nodes_encountered = set()
nodes = network.nodes()
if not source:
# chose a vertex from network as start point
source = nodes[0]
nodes_encountered.add(source)
if len(nodes_encountered) != len(nodes):
for node in network.network_dict[source].get_adjacents():
if node not in nodes_encountered:
if ConnectivityChecker.is_connected(network, nodes_encountered, node):
return True
else:
return True
return False
@staticmethod
def depth_first_search(network: Network, node_id: int = None) -> bool:
"""
Returns bool indicating graph connectivity (path between all nodes).
This is an iterative DFS.
:param network: object representing a graph (network)
:param int node_id: identifies node where search will start (None by default)
:return: bool indicating graph connectivity
:rtype: bool
"""
nodes_encountered: Set[Optional[int]] = set()
if not node_id:
node_id = network.nodes()[0]
stack = [node_id]
while stack:
node = stack.pop()
if node not in nodes_encountered:
nodes_encountered.add(node)
stack.extend(network.network_dict[node].get_adjacents())
if len(nodes_encountered) != len(network.nodes()):
return False
else:
return True
@staticmethod
def breadth_first_search(network: Network, node_id: int = None) -> bool:
"""
Returns bool indicating graph connectivity (path between all nodes).
This is an iterative BFS.
:param network: object representing a graph (network)
:param int node_id: identifies node where search will start (None by default)
:return: bool indicating graph connectivity
:rtype: bool
"""
# mark all the nodes as not visited (value is None)
visited = dict.fromkeys(network.nodes())
nodes_encountered = set()
queue = []
if not node_id:
node_id = network.nodes()[0]
# mark the source node as visited and enqueue it
queue.append(node_id)
visited[node_id] = True
nodes_encountered.add(node_id)
while queue:
# dequeue a node from queue and add to nodes_encountered
node_id = queue.pop(0)
nodes_encountered.add(node_id)
# all adjacents of current node are checked, if the node hasn't been
# enqueued previously, node is enqueued and added to nodes_encountered
for node in network.network_dict[node_id].get_adjacents():
if not visited[node]:
queue.append(node)
visited[node] = True
nodes_encountered.add(node)
# if size of nodes_encountered equals size of nodes(), return True
if len(nodes_encountered) == len(network.nodes()):
return True
else:
return False
|
6793c72a499bae6029fc4a0736cbc51e48c76563 | EPAlmighty/cti110 | /M6T2_Pinnell.py | 308 | 3.875 | 4 | #CTI 110
#M6T2- Bug Collector
#Evan Pinnell
#11/29/17
def main():
total = 0
for day in range(1, 8):
print('Enter the bugs collected on day', day)
bugs = int(input())
total += bugs
print('You collected a total of', total, 'bugs')
main()
|
2cc01678177ec762442fd1b71258e799cf53659f | asherLZR/algorithms | /graphs/kruskals_mst.py | 1,107 | 3.5 | 4 | from abstract_data_types.union_find import UnionFind
# initialisation of input values
vertex_count, edge_count = map(int, input().split())
U, V, W = [0] * edge_count, [0] * edge_count, [0] * edge_count
for i in range(edge_count):
U[i], V[i], W[i] = map(int, input().split())
edge_list = sorted(zip(U, V, W), key=lambda x: x[2])
# union find data structure for each unique vertex in the edge list
union_find = UnionFind(list(set(x for x in U + V)))
finalised = []
mst_weight = 0
# continually try adding edges in sorted order provided they do not create a cycle
for u, v, w in edge_list:
# if the 2 vertices are in disjoint sets, there is no cycle
if union_find.set_id(u) != union_find.set_id(v):
# add the edge to the finalised graph
finalised.append((u, v, w))
# union the sets of both vertices incident to the edge
union_find.union_sets(u, v)
mst_weight += w
# break once the number of edges is that of a tree, |V|-1
if len(finalised) == vertex_count - 1:
break
print(mst_weight)
# 4 6
# 1 2 5
# 1 3 3
# 4 1 6
# 2 4 7
# 3 2 4
# 3 4 5 |
c1d62dcc63b0a8205ac14ae5d9d80f88e1f23f52 | tsjabie-o/Advent-of-Code-2020 | /Day 6/main.py | 998 | 3.609375 | 4 |
from typing import MutableMapping
def ParseInput():
with open("./Day 6/data.txt") as data:
rawdata = data.read()
groups = rawdata.split("\n\n")
groups = [group.replace("\n", " ") for group in groups]
return groups
def CountQuestions1(group):
questions = list()
for char in group:
if char not in questions and char != " ": questions.append(char)
return questions
def CountQuestions2(group):
passengers = group.split()
mutual = [char for char in passengers[0]]
for char in passengers[0]:
for i in range(1, len(passengers)):
if char not in passengers[i]:
mutual.remove(char)
break
return mutual
groups = ParseInput()
# Part one
total1 = 0
for group in groups:
questions = CountQuestions1(group)
total1 += len(questions)
# Part two
total2 = 0
for group in groups:
# print(group)
questions = CountQuestions2(group)
# print(questions)
total2 += len(questions)
|
81ce842c498e71e2fffcf79700f8eb187735f79b | BotOreo/Python-Files | /ngram_test_zaim.py | 3,785 | 3.59375 | 4 | import re
di_unigram={}
di_bigram={}
di_trigram={}
di_unigram_count = {}
di_bigram_count = {}
di_trigram_count = {}
di_probability = {}
def ngram():
#using "with" will close the file immediately after last call
with open("text-ngram.dat","r") as rfile:
infile = rfile.readlines()
#for line in infile:
# word = line.split()
# di_unigram = word
sent = [s for s in infile[0].split(".")] #store every line
for line in sent:
for j in range(len(line.split())-1): #range 0 sampai total perkataan yg ada
uni = line.split()[j] #unigram words = 1 word #store first word dulu dalam uni starting from index j=0
if uni in di_unigram:
di_unigram[uni] = di_unigram[uni] + 1
else:
di_unigram[uni] = 1
for line in sent:
for j in range(len(line.split())-1): #range 0 sampai total perkataan yg ada
bi = line.split()[j]+" "+line.split()[j+1]
if bi in di_bigram:
di_bigram[bi] = di_bigram[bi] + 1
else:
di_bigram[bi] = 1
print("This is the unigram")
print(di_unigram)
print("\nThis is the bigram")
print(di_bigram)
for line in sent:
for k in range(len(line.split())-2):
tri = line.split()[k]+" "+line.split()[k+1]+" "+line.split()[k+2] #trigram words pairing
if tri in di_trigram:
di_trigram[tri] = di_trigram[tri] +1
else:
di_trigram[tri] = 1
print("\nThis is the trigram")
print(di_trigram)
print("\nTest")
for k in di_bigram:
for v in di_unigram:
#print(di_bigram[v]) #setakat ni sequence die sama ngan dictionary
probability = di_bigram[k]/di_unigram[v]
print(probability)
#print("done")
break
#print(di_unigram[k]) #dpt values
#print(k) #dpt keys
''' for line in sent:
for k in range(len(line.split())-1):
probability = di_unigram.items()[k]
print(probability)
'''
#probability = di_bigram.items()/di_unigram.items()
#print("The probability is :")
#print(probability)
''' unifile = open("E:/Zaim/3rd Year 1st Sem 2018_2019 sem 2/NLP/Python ngram/unigram.dat","w")
bifile = open("E:/Zaim/3rd Year 1st Sem 2018_2019 sem 2/NLP/Python ngram/bigram.dat","w")
trifile = open("E:/Zaim/3rd Year 1st Sem 2018_2019 sem 2/NLP/Python ngram/trigram.dat","w")
sent = [s for s in infile[0].split(".")]
for line in sent:
for j in range(len(line.split())-1):
uni = line.split()[j] #unigram words
bi = line.split()[j]+" "+line.split()[j+1] #bigram words pairing
#kene create dictionary for unigram, bigram, calculate probability just divide
unifile = open("unigram.dat","a")
bifile = open("bigram.dat","a")
unifile.write(str(uni)+"\n")
bifile.write(str(bi)+"\n")
unifile.close()
bifile.close()
for k in range(len(line.split())-2):
trifile = open("trigram.dat","a")
tri = line.split()[k]+" "+line.split()[k+1]+" "+line.split()[k+2] #trigram words pairing
trifile.write(str(tri)+"\n")
trifile.close()
'''
ngram()
|
f1040f6df9cdffcbf08c2b6db00a610b31cf5558 | BMariscal/study-notebook | /coding_interview_patterns/sliding_window/max_sum_arr_size_k.py | 557 | 3.515625 | 4 | # Given an array, find the average of all contiguous subarrays of size ‘K’ in it.
# Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5
# Output: [2.2, 2.8, 2.4, 3.6, 2.8]
def max_sum_arr_size_k(arr, k):
ans = []
windowStart, windowSum = 0, 0
for windowEnd in range(len(arr)):
windowSum += arr[windowEnd]
if windowEnd >= k - 1:
ans.append(windowSum)
windowSum -= arr[windowStart]
windowStart += 1
return max(ans)
arr = [1, 3, 2, 6, -1, 4, 1, 8, 2]
k = 5
print(max_sum_arr_size_k(arr, k))
|
666050ba17111078e5fe3e3636e4e4766a424a05 | lsom11/coding-challenges | /leetcode/September LeetCoding Challenge/Largest Number.py | 231 | 3.5 | 4 | class Solution:
def largestNumber(self, nums):
compare = lambda a, b: -1 if a+b > b+a else 1 if a+b < b+a else 0
print(compare)
return str(int("".join(sorted(map(str, nums), key = cmp_to_key(compare))))) |
50ab1993cd58c396a6d4e51cb9d0d3aff66f4bc1 | ivo-douglas/OlaMundo | /CalcularNota.py | 2,493 | 4.125 | 4 | """ Nome: Douglas Ivo Martins de Moraes
1. a) Sabe Programar: Não, ja experimentei algumas coisas de scripting structure nas minhas horas de lazer / hobbie, mas formalmente nunca programei ou aprendi uma linguagem de programação
b) Ja trabalha na aréa de computação? : Não
c) Ja estudou ou fez algum outro curso na área de computação? : Ja fiz um curso de informatica básica mas nada nunca avançado como programação. Coisas simples como gerenciamento de arquivo, como utilizar o word/excel/powerpoint."""
#===============================================================================================
P1 = float(input("Entre a nota da sua Prova 1, se decimal, utilizar ponto em vez de virgula: ")) #aqui o usuário entrará o resultado da p1
P2 = float(input("Entre a nota da sua Prova 2, se decimal, utilizar ponto em vez de virgula: ")) #aqui o usuário entrará o resultado da p2
P3 = float(input("Entre a notada sua Prova 3, se decimal, utilizar ponto em vez de virgula: ")) #aqui o usuário entrará o resultado da p3
MP = (P1 + P2 + P3)/3 #A média arítimetica de prova sera calculada
print("Media de prova: ", MP) #A nível de curiosidade a média de prova sera mostrada na tela
#===============================================================================================
E1 = float(input("Entre a nota do seu Teste 1, se decimal, utilizar ponto em vez de virgula: ")) # Aqui o usuário entrará o resultado do Teste 1
E2 = float(input("Entre a nota do seu Teste 2, se decimal, utilizar ponto em vez de virgula: ")) # Aqui o usuário entrará o resultado do Teste 2
ME = (E1 + E2)/2 # Aqui a média arítimetica dos testes será calculada
print("Média de teste: ", ME) # A nível de curiosidade a média do teste sera mostrada na tela
#===============================================================================================
T = float(input("Entre a nota do seu Trabalho, se decimal, utilizar ponto em vez de virgula: ")) # Aqui o usuário entrará o resultado do Trabalho
#===============================================================================================
MAo = (0.7*MP) + (0.2*ME) + (0.1*T) # Aqui serão aplicados os pesos em cada média, e no final, a soma de todos eles
MAf = int(MAo*10)/10 # Aqui o resultado de MAo será multiplicado por 10 como numero inteiro e posteriormente divido por 10 para ser mostrado apena uma unica casa decimal
print("A sua média total sera: ", MAf) # Aqui o resultado da média final será mostrado na tela
|
6c3a4c023b51f31c3baf0cad6d26f9ac17cf2d32 | Dacode45/gh5server | /court_locator.py | 9,649 | 3.65625 | 4 | import sys
import json
### COURT LOCATOR SCRIPT (court_locator.py)
###
### Author: Elliott Battle (09-13-2015)
### Event: GlobalHack V
### Team: Rush Hour 3
###
### Purpose: Process queries from a JSON database by taking geographic points (represented as a lattitude and a longitude)
### and identifying which court in the desired county (if any) services that area.
# PATHING CONSTANTS (Hardcoded for now)
# A JSON database of geographic information for all of the municipalities in the county.
muni_filename = "stl_munis.json"
# A JSON database detailing location and contact information for all courts in the county.
court_filename = "stl_courts.json"
# A JSON database used to map together entries in the prior two databases based-on which courts
# service which areas.
service_map_filename = "stl_service_map.json"
def point_is_in_bounds(x, y, bounds):
# POINT IS IN BOUNDS
#
# Checks if the point (x, y) is contained in the region bounded by the bounds variable, which is
# an array of points defining the boundary of a polygon.
#
# Credit for Algorithm: http://www.ariel.com.au/a/python-point-int-poly.html
n = len(bounds)
inside = False
p1x, p1y = bounds[0]
for i in range(n+1):
p2x,p2y = bounds[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
def point_is_in_poly(x, y, poly):
# POINT IS IN POLYGON
#
# Checks if the point (x, y) is contained in a particular GEOJSON polygon.
# Because this data is based-on the GEOJSON standard, the polygon object is a nested array of points.
# Each inner array of points describes a closed curve. The first curve is the outter boundary of the polygon,
# and all subsequent curves describe areas "cut-out" of the polygon, i.e. regions within the outermost curve
# which are "holes" in the shape and therefore not considered part of the polygon.
# Again, this comes first by GEOJSON convention. All other curves describe exclusion regions.
outer_bound = poly[0]
# We first check naively whether the point is even contained in the "whole" version of the polygon.
if point_is_in_bounds(x, y, outer_bound):
# Now we need to check if the point lies in a region excluded from the polygon.
if len(poly) == 1:
# The polygon has no holes and the point is inside its outer boundary. Polygon contains the point.
return True
else:
# The polygon has some nonzero number of holes. Check to make sure the point isn't in any of them.
for hole in poly[1:len(poly)]:
if point_is_in_bounds(x, y, hole):
#If in a hole, it's not contained by the polygon. Return false immediately.
return False
# The point is not excluded by any subsequent curves; it lies within the polygon.
return True
else:
# Point is outside of the polygon's bounding region entirely. Return false.
return False
def point_is_in_multipoly(x, y, multipoly):
# POINT IS IN MULTIPOLYGON
#
# Checks if the point (x, y) is contained in a particular GEOJSON multipolygon.
# A multipolygon is an array of regular GEOJSON polygons which may or may not be contigious when rendered in
# a plane. A point is considered to be contained by a composite polygon if it is considered contained by any
# one of the constituent polygons.
# We simply iterate through the array, and return true if any are true, and false if all are false.
for poly in multipoly:
#print("Next poly has", len(poly), "points.")
if point_is_in_poly(x, y, poly):
return True
return False
def muniForPoint(x, y):
# MUNICIPALITY FOR POINT
#
# Determines which municipality (if any) within the county specified intersects lattitude x and longitude y.
# While this method may return None, the driver and calling functions check for this sentinel condition.
# Load the list of municipal boundaries as JSON objects (each being geometrically either a polygon or a multipolygon).
# Save them into an array and iterate over it.
file = open(muni_filename, 'r')
muni_json_data = json.loads(file.read())
file.close()
munis = muni_json_data["munis"]
# Iterate through those objects and look for one containing the point (x, y) within its bounds.
for muni in munis:
# Before we can iterate, we must know what type of polygon we're dealing with.
muni_geometry = muni["geometry"]
#print("Checking for match in:", muni["properties"]["name"])
if muni_geometry["type"] == "Polygon":
# Geometry is a polygon. Use basic containment algorithm.
if point_is_in_poly(x, y, muni_geometry["coordinates"]):
return muni
elif muni_geometry["type"] == "MultiPolygon":
# Geometry is a multipolygon.
# Use the iterative containment algorithm over all member polygons.
if point_is_in_multipoly(x, y, muni_geometry["coordinates"]):
# Return if we have a match.
return muni
else:
# Log that there was a geometry error, but don't stop iterating immediately;
# the point could still be in a subsequent municipality and we don't want to miss it.
print("ERROR. INVALID GEOMETRY TYPE")
# Return nothing if there's no match.
return None
def courtForMuni(muni):
# COURT FOR MUNICIPALITY
#
# Input: A municipality, as stored in a JSON object.
# Output: Either the court presiding over that municipality or (if there is none or there's an unexpected error)
# the default option county courts
file = open(court_filename, 'r')
court_json_data = json.loads(file.read())
courts = court_json_data["courts"]
file.close()
if muni == None or muni["properties"]["muni_id"] == 0:
# The if-statement above covers a few critical edge cases:
# 1) The area is unincorporated and under county jurisdiction.
# 2) The user inputs a point to which no municipality in the county corresponds
# (e.g. picks a point somewhere outside the county or even the state).
# 3) The user picks a valid point within the county, but it is on the boundary between two municipalities.
# This is an edge case from the point containment algorithm which could have real-life consequences:
# tickets issued so close to a municipal boundary could be under ambiguous jurisdiction as-is.
# 4) A point is in an unincorporated area without a name. This is caused by an oversight in the database.
# 5) Some other general database error causes a valid municipality to not be found.
# In each of these cases, we should return the county-level courthouse in this siutation (always at index 0) so
# that the user can get some human assistance.
return courts[0]
else:
# Otherwise, look-up the municipality in the service mapping table,
# and return the court with the corresponding id.
file = open(service_map_filename, 'r')
service_map_json_data = json.loads(file.read())
service_mappings = service_map_json_data["service_mappings"]
file.close()
# Iterate through the list of service mappings to find the
# court_id servicing the municipality given.
for s_map in service_mappings:
if s_map["municipality"].lower() == muni["properties"]["name"].lower():
court_id = s_map["servicing_court_id"]
for court in courts:
if court_id == court["court_id"] or muni["properties"]["name"].lower() == court["city"].lower():
return court
# A court serving a municipality with the same name was found in our mapping file,
# but neither the court's municipality name nor id is in our list of courts.
# This may mean the JSON is incomplete or corrupt, so we have no choice but to return the default.
return courts[0]
# If we don't get a match anywhere, then that means we forgot to include
# an incorporated municipality in our mapping JSON file.
# Direct the user to the county-level offices for further assistance.
return courts[0]
def main():
# MAIN DRIVER ROUTINE:
#
# Takes the x and y coordinates the user wishes to query as arguments.
# Send to the ostream via print() JSON objects for the municipality and
# court relevant to the query.
## FOR TESTING FUNCTIONS ONLY (DISABLE WHEN USING COMAND-LINE ARGS!!!)
##
## print("Enter x, then y!")
## x = eval(input())
## y = eval(input())
# Unpack the command-line arguments into lattitude x and longitude y
x = float(sys.argv[1])
y = float(sys.argv[2])
#print x, y
# Find the municipality containing a point at lattitude x and longitude y
muni = muniForPoint(x, y)
#print(muni["properties"]["name"])
# Find the court servicing that area. Default to the county court if one cannot be found.
court = courtForMuni(muni)
# Export the results of the query to the server-side software calling this script via a
# print() statement
print(":^)"+json.dumps(court))
main()
|
5626722b6c9ad0cf2318b7a8aaf655f6f6f274b7 | rgayatri23/Python_prac | /allSort.py | 5,850 | 3.890625 | 4 | import random
#######################################################Quick Sort #########################################################################
def quickSort(arr) :
# print("Quick sort")
if len(arr) <= 1 :
return arr
pivot = arr[len(arr)/2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quickSort(left) + middle + quickSort(right)
#######################################################Merge Sort #########################################################################
def merge(a,b) :
c = []
while len(a) != 0 and len(b) !=0 :
if a[0] < b[0] :
c.append(a[0])
a.remove(a[0])
else :
c.append(b[0])
b.remove(b[0])
if len(a) == 0 :
c += b
else :
c += a
return c
def mergeSort(arr) :
print("Merge sort")
if len(arr) == 1 or len(arr) == 0 :
return arr
else :
middle = len(arr)/2
a = mergeSort(arr[:middle])
b = mergeSort(arr[middle:])
return merge(a,b)
#######################################################Insertion Sort #########################################################################
def swap(arr, a, b) :
arr[a],arr[b] = arr[b],arr[a]
def insertionSort(arr) :
print("Insertion Sort")
change = 0; index = 0; posn=0; currVal = 0
for index in range(0,len(arr)-1) :
if arr[index] > arr[index+1] :
currVal = arr[index + 1]
posn = index+1
while posn > 0 and currVal < arr[posn-1] :
swap(arr, posn-1, posn)
posn-=1
return arr
#######################################################Selection Sort #########################################################################
def findMin(arr) :
iMin = arr[0]
for x in arr :
if x < iMin :
iMin = x
return iMin
def findMinIndex(arr) :
iMin = 0
for index in range (0,len(arr)) :
if arr[index] < arr[iMin] :
iMin = index
return index
def selectionSort(arr) :
print("Selection Sort")
for i in range(0,len(arr)) :
for j in range(i+1, len(arr)) :
if arr[i] > arr[j] :
swap(arr,i,j)
return arr
#######################################################Heap Sort #########################################################################
def heapify(arr, n, i) :
largest = i
l = 2*i+ 1 # left child
r = 2*i+ 2 # right child
#Check if left child exists and is greater than the root
if l < n and arr[i] < arr[l] :
largest = l
#Check if right child exists and is greater than the root
if r < n and arr[largest] < arr[r] :
largest = r
#Swap the root if needed and heapify the root again
if largest != i :
swap(arr, largest,i)
heapify(arr, n, largest)
# return arr
def heapSort(arr) :
arrSize = len(arr)
# Build a maxheap.
for i in range(arrSize, -1, -1):
heapify(arr, arrSize, i)
# One by one extract elements
for i in range(arrSize-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
return arr
#######################################################Selection Sort #########################################################################
def bubbleSort(arr) :
for j in range(0, len(arr)) :
for i in range(0, len(arr)-1) :
if arr[i] > arr[i+1] :
swap(arr,i,i+1)
return arr
#######################################################MAIN#########################################################################
def main() :
print("********This is a program which implements various sorts***********")
numSorts = 6
print(" *******The sorting algorithms are numbered as shown below*************")
print("\n")
print("1 : Quick Sort")
print("2 : Merge Sort")
print("3 : Insertion Sort")
print("4 : Selection Sort")
print("5 : Heap Sort")
print("6 : Bubble Sort")
sortNum = int(raw_input("enter the corresponding number of the sort that you want to try : "))
while sortNum > numSorts :
print("Wrong Input")
sortNum = int(raw_input("enter the corresponding number of the sort that you want to try : "))
numElements = 10
arr = [49,100,32,62,72,17,65,69,29,73]
# arr = []
# for x in range (0, numElements) :
# arr.append( int(random.randint(0,100)))
print("\n")
print(" Original array ")
print(arr)
print("\n")
#QUICK SORT ****************************************
if sortNum == 1 :
arr = quickSort(arr)
print ("Quick Sorted array ")
print(arr)
print("\n")
#Merge Sort ****************************************
if sortNum == 2 :
arr = mergeSort(arr)
print ("Merge Sorted array ")
print(arr)
print("\n")
#Insertion Sort ****************************************
if sortNum == 3 :
arr = insertionSort(arr)
print ("Insert Sorted array ")
print(arr)
print("\n")
#Selection Sort ****************************************
if sortNum == 4 :
arr = selectionSort(arr)
print ("Selection Sorted array ")
print(arr)
print("\n")
#Heap Sort ****************************************
if sortNum == 5 :
arr = heapSort(arr)
print ("Heap Sorted array ")
print(arr)
print("\n")
#Bubble Sort ****************************************
if sortNum == 6 :
arr = bubbleSort(arr)
print ("Bubble Sorted array ")
print(arr)
print("\n")
if __name__ == '__main__' :
main()
|
06735541954a85c263fd2b0e1a3abc0e2f209459 | kashyap92/python-training | /MyMath.py | 289 | 3.578125 | 4 | #!/usr/bin/python
def add(a,b):
return a+b
def mul(a,b):
return a*b
def sub(a,b):
return a-b
def div(a,b):
return a/b
if __name__ == "__main__":
print add(10,20)
print mul(10,20)
print sub(4,2)
print div(10,2)
print __name__
|
22df68a087f09a8337ecf5774eec62c6fbab3ce0 | nwthomas/code-challenges | /src/interview-cake/product-of-every-integer-but/product_of_every_integer_but.py | 1,124 | 4.0625 | 4 | """
Write a function get_products_of_all_ints_except_at_index() that takes a list of integers and returns a list of the products.
For example, given:
[1, 7, 3, 4]
your function would return:
[84, 12, 28, 21]
by calculating:
[7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3]
Python 3.6
Here's the catch: You can't use division in your solution!
"""
from copy import copy
def get_products_of_all_ints_except_at_index(int_list):
"""Takes in a list of ints and returns the product for each except"""
if type(int_list) != list:
raise TypeError(
"The argument for get_products_of_all_ints_except_at_index must be of type list.")
if len(int_list) <= 1:
raise Exception("The length of the integer list must be 2 or greater.")
product_list = [None] * len(int_list)
product_so_far = 1
for i in range(0, len(int_list)):
product_list[i] = product_so_far
product_so_far *= int_list[i]
product_so_far = 1
for i in range(len(int_list) - 1, -1, -1):
product_list[i] *= product_so_far
product_so_far *= int_list[i]
return product_list
|
7b79eb125ee7453c86a991a8003dcf61974e35fc | r002/interview_prep | /strings/q201.py | 1,494 | 3.890625 | 4 | from base.question import *
class Str201(Question):
description = "201) Given a string, s, find the longest palindromic substring in s."
i = 0 # Number of iterations my solution takes
def __init__(self):
# s = 'racecar'
# s = 'tracecars'
# s = 'ab'
# s = 'abcbgh'
s = 'abcabcabcqqqzzmzzabcd'
# s = 'cabcabcqqq'
# s = ''
print(f"Original string: {s}")
print(f"Original length: {len(s)}")
print(f"Worst-case O(n) should be ~ n*(n/2): {len(s)*(len(s)/2)}\n")
p_cand = s
champ = ''
while True:
print(f"This iteration's candidate: {p_cand}")
if len(p_cand) <= len(champ):
print(f"Since len(p_cand) <= len(champ), we can just quit!")
break
it_cand = self.check_if_any_exist(p_cand)
if len(it_cand) > len(champ):
print(f"\t\tNew champ! {it_cand}")
champ = it_cand
# Code the exit condition
if len(p_cand) < 2:
break
else:
p_cand = p_cand[1:]
print(f"\nFinal Champ: {champ}")
print(f"Total iterations: {self.i}")
def check_if_any_exist(self, p_cand):
while True:
self.i += 1
if p_cand == p_cand[::-1]:
print(f"\tPalindrome found! {p_cand}")
return p_cand
else:
p_cand = p_cand[:-1]
|
330f9c4fab16ed56a8f42bda8175d6fa33641d73 | alhulaymi/cse491-numberz | /sieve_iter/test.py | 825 | 3.734375 | 4 | #The first prime number is 2 but im following the outcome of sieve-fn.py and starting by 3
import sieve
def test1():
print "--<<test 1>>--"
print "should get to one value above 29 and stop"
x = 0
for i in sieve.adder():
x = i
if i > 29:
break
assert x == 31
print "=>Success"
def test2():
print "--<<test 2>>--"
print "Should get us the first two (3,5)"
x = sieve.adder()
y = x.next()
assert y == 3
y = x.next()
assert y == 5
print "=>Success"
def test3():
print "--<<test 3>>--"
print "will loop to one prime above 6, then one more manually by next()"
x = sieve.adder()
for i in x:
if i > 6:
break
y = x.next()
assert y == 11
print "=>Success"
test1()
test2()
test3() |
f37d04970030ab66bc49713e178dac54b4c29f64 | yistar-traitor/LeetCode | /LinkedList/ReverseLinkedList.py | 1,570 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/15 15:41
# @Author : tc
# @File : ReverseLinkedList.py
"""
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
参考:https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/
递归:记住递归要返回的是什么,以及递归出栈后,后面的代码要怎么写?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 递归解法
def reverseList(head):
if not head or not head.next:
return head
p = reverseList(head.next)
head.next.next = head # 关键:这里head指向的节点是最关键的,
head.next = None
return p
# 迭代解法 这个解法是有问题的
def reverseList2(head):
curr = head
prev = ListNode()
while curr:
tmp = curr.next # 保留当前节点的下一个节点
curr.next = prev # 让当前节点指向上一个节点
prev = curr # 前一个节点向后移动
curr = tmp # 当前结点向后移
return prev # 注意返回的是prev 不是curr
if __name__ == '__main__':
root = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
root.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
res = reverseList(root)
|
705010c88fdc1e0c4a5cda6963a2eb4981ea629e | VinayakaSridharKVV/Spice_in_python | /ee19b058_file1.py | 1,901 | 4.09375 | 4 | """ EE2703 ASSIGNMENT 1
NAME: VINAYAKA SRIDHAR K V V
ROLL NO.: EE19B058
"""
# PYTHON PROGRAM FOR READING A NETLIST AND PRINTING IN THE REVERSE ORDER
from sys import argv, exit #importing module sys
pycode = argv[0]
CIRCUIT = '.circuit' # defining the constants
END = '.end'
""" Sanity Check whether there is a input file given or not"""
if len(argv) != 2:
#if the there is no input file mentioned and print the usage method
print("\nPlease give a input file: Usage: %s <input file name>" % pycode)
exit()
filename = argv[1] # Calling the argument after the python file in the commandline as the filename
try:
with open(filename) as f: #Taking the input file as f
#Initialising values of start and end
start=1
end=0
lines = f.readlines() #reading the input file line by line and storing them in the list "lines"
for line in lines:
word = line.split() # Checking if there is line starting with .circuit
if word[0]==CIRCUIT: # if there is a line starting with .circuit then make its index as start
start = lines.index(line)
if word[0]==END: # Checking if there is line starting with .end
end = lines.index(line) # if yes then make its index as end
""" Sanity check: whether input file has valid circuit defintion
that is whether its starts with .circuit and ends with .end"""
if start >= end:
print("Invalid Circuit Definition") #if the file fails to comply with the circuit defintion then print out error statement
exit(0)
#printing the lines in the reverse order
for i in range(end-1,start,-1):
tokens = lines[i].split("#")[0].split() #removing the comments and splitting the lines into words and calling them tokens
print(" ".join(reversed(tokens))) #printing the tokens in reverse order
# if no file exists with the name given by the user
#then issue an IOError saying invalid file
except IOError:
print("Invalid File")
exit(0)
|
6370c81e41d004a2c089097976d406350346664b | mfcrespo/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 324 | 3.84375 | 4 | #!/usr/bin/python3
""" Module that manipulates lists
"""
class MyList(list):
""" Class that inherits from list
"""
def print_sorted(self):
""" Prints self sortedly, without modifying the
original list
"""
new_list = self[:]
new_list.sort()
print(new_list)
|
aed24f58dc924174df5c95c5e3839251a4190d28 | jgsneves/algoritmo-python | /poo/encapsulamento/exercicio8.py | 624 | 3.5 | 4 | class Funcionario:
def __init__(self, nome, salario, matricula, funcao):
self.nome = nome
self.__salario = salario
self.__matricula = matricula
self.funcao = funcao
@property
def matricula(self):
return self.__matricula
@property
def salario(self):
return 'R$ {0:.2f}'.format(self.__salario)
@salario.setter
def salario(self, novo_salario):
if novo_salario == self.__salario * 1.20:
self.__salario = novo_salario
else:
print('Só é possível dar aumentos de 20%. Não é possível diminuir o salário.')
|
c827732bd723bd387ddeccc1a4b4ed48135831a4 | jamalamar/Python-function-challenges | /challenges.py | 1,182 | 4.28125 | 4 |
#Function that takes a number "n" and returns the sum of the numbers from 1 to "n".
# def sum_to(n):
# x = list(range(n))
# y = sum(x) + n
# print(y)
def sum_to(num):
sum = 0
for i in range(num + 1):
sum += i
print("The sum from 1 to "+ str(num) + ": " + str(sum))
sum_to(10)
#Function that takes a list parameter and returns the largest element in that list.
#You can assume the list contents are all positive numbers.
def largest(list):
largest = 0
for i in list:
if(i>largest):
largest = i
print("Largest on list: " + str(largest))
largest([1,2,34,5,6])
#Function that counts the number of occurrances of the second string inside the first string.
def occurances(one, two):
occur = 0
for i in one:
if(i == two):
occur += 1
print("Number of " + "'" + two + "'" + " occurances: " + str(occur))
occurances('fleeeeep floop', 'e')
#Function that takes an arbitrary number of parameters, multiplies them all together, and returns the product.
#Only need "*", args is just a convention:
def multi(*args):
product = 1
for i in args:
product *= i
print("The product of this numbers is: " + str(product))
multi(2, 2, 2, 2)
|
23cb91e6de15c782f3eb396edbf495a783e7f967 | ermteri/PythonTraining | /Exercises.py | 12,929 | 3.90625 | 4 | # Exercises taken from http://www.practicepython.org/
def ex1():
import datetime
now = datetime.date.today().year
name=input("Enter your name:")
age = int(input("Enter your age:"))
num = int(input("Enter how many times:"))
for i in reversed(range(1,99)):
print(i)
print('Dear {} you will be 100 {}'.format(name,now+100-age))
def ex2():
num = int(input("Enter an integer: "))
if num % 2 == 0:
if num % 4 == 0:
print("quadruple!!")
else:
print("Even number!!")
else:
print("Odd number!!")
def ex3():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print (list(filter(lambda x: x>3,a)))
def ex4():
num = int(input("Enter an integer: "))
def isdiv(x):
return num % x == 0
print(list(filter(isdiv, range(1, num))))
print(list(filter(lambda x: num % x == 0, range(1,num))))
def ex5():
import random
first = []
second = []
for x in range(random.randint(10,20)):
first.append(random.randint(1,20))
for y in range(random.randint(10,20)):
second.append(random.randint(1,20))
print(sorted(first))
print(sorted(second))
print(set(sorted(list(filter(lambda val: val in second,first)))))
def ex6():
palindrome = input("Enter a string: ")
print(palindrome,palindrome[::-1])
if palindrome == ''.join((reversed(palindrome))):
print("Is a palindrome")
else:
print("Is NOT a palindrome!!")
def ex7():
import random
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
a = []
for x in range(random.randint(90,100)):
a.append(random.randint(0,1000))
print(a[::2])
print(list(filter(lambda x: x % 2 == 0,a)))
def ex8():
import random
def get_second_choice():
choice =['r','s','p']
return choice[random.randint(0,2)]
first = ""
second = ""
first_points = 0
second_points = 0
print("Use r for rock, s for scissor, p for paper and q for quit.")
while first !="q" or second != "q":
first = input("First player, enter your choice (r,s,p,q):")
if first == "q":
break
#second = input("Second player, enter your choice (r,s,p,q):")
if second == "q":
break
second = get_second_choice()
print("Second choose:",second)
if first == "r":
if second == "r":
# even
print("Even")
elif second == "s":
# second win
print("First win")
first_points+=1
elif second == "p":
# first win
print("Second win")
second_points+=1
if first == "s":
if second == "r":
# second win
print("Second win")
second_points+=1
elif second == "s":
# even
print("Even")
elif second == "p":
# first win
print("First win")
first_points+=1
if first == "p":
if second == "r":
# first win
print("First win")
first_points+=1
elif second == "s":
# second win
print("Second win")
second_points+=1
elif second == "p":
# even
print("Even")
else:
print("Invalid choice:",first)
print("First {}, second {}".format(first_points,second_points))
print("Final result: First {}, second {}".format(first_points,second_points))
def ex9():
import random
guess = ""
number_of_guesses = 0
number = random.randint(1, 9)
while guess != 'exit':
guess = str(input("Guess number:"))
number_of_guesses+= 1
if int(guess) == number:
print("Great you were right")
break
elif int(guess) > number:
print("Too high!")
elif int(guess) < number:
print("Too low!")
print("You guessed ", number_of_guesses)
def ex10():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = [x for x in a for y in b if x==y]
d =[]
d = [x for x in c if c.count(x) == 1 ]
print(list(c))
print (list(d))
def ex11_ets(number):
import math
import time
start = time.time()
#number = int(input("Enter an integer:"))
#Step 1 and 2
nums = [x for x in range(2,number+1) if x%2!=0 or x == 2]
i=1
# step 3
next = nums[i]
#print(next,list(nums))
# step 4 5
while next < math.sqrt(number):
nums = [x for x in nums if x%next!=0 or x == next]
#print(list(nums))
i+=1
next = nums[i]
#print(next)
# step 6
print(time.time() - start)
print(len(nums),list(nums))
return nums
def ex11():
import time
max = int(input("Enter an integer:"))
start = time.time()
#max = int(input("Enter an integer:"))
#print(list(range(2,number)))
#print(number%2)
#result = [x for x in range(2,number) if number % x == 0]
#print(list(result))
#if len(result) > 0:
result = []
for number in range(1,max):
if len([x for x in range(2,number) if number % x == 0]) > 0 or number == 1:
#print("Prime-number")
#print("Not a prime number")
x=1
else:
result.append(number)
print(time.time() - start)
print(len(result),list(result))
result2 = ex11_ets(max)
print(result == result2)
def ex12():
def get_first_last(alist):
return [x for ind,x in enumerate(alist) if ind== 0 or ind==len(alist)-1]
a= [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73]
print(list(get_first_last(a)))
def ex13():
count = int(input("Enter number of fibonacci numbers:"))
result = [1,1]
while len(result) < count:
result.append(result[len(result)-1] + result[len(result)-2])
print(list(result))
def ex14():
def clean_list(alist):
return list(set(alist))
a = [1, 1, 2, 3, 5, 2, 13, 21, 13, 3, 89]
print(list(clean_list(a)))
def ex15():
def yoda(message):
result = message.split()
return result[::-1]
sentence = str(input("Enter a sentence"))
print(" ".join(yoda(sentence)))
def ex16():
import string
import random
# 1. at least one from each group
# 2. Min-len 4, max any
pwlen = 10
source = list()
source.append(string.ascii_uppercase)
source.append(string.ascii_lowercase)
source.append(string.punctuation)
source.append(string.digits)
print(list(source))
pw = ""
for x in range(pwlen):
pw += "".join(random.sample(source[x%4],1))
#print(pw)
print(pw)
def ex17():
import requests
from bs4 import BeautifulSoup
url = "http://www.nytimes.com/"
r = requests.get(url)
r_html = r.text
soup = BeautifulSoup(r_html,"html.parser")
result = soup.find_all('a')
for link in result:
print(link.get('href'),link.contents)
for story_heading in soup.find_all(class_="story-heading"):
if story_heading.a:
print(story_heading.a.text.replace("\n", " ").strip())
else:
print(story_heading.contents[0].strip())
def ex18():
import random
def check_cows_bulls(n):
cow = 0
bull = 0
for ind,x in enumerate(n):
if x == number[ind]:
cow+=1
elif x in number:
bull+=1
print("C:", cow, "B:", bull)
number = "{0:0>4}".format(random.randint(0,9999))
print("Secret:",number)
count = 0
while True:
guess = str(input("Enter number: "))
count += 1
if guess == number:
print("Correct!")
break
else:
check_cows_bulls(guess)
print("You guessed",count,"number of time(s)")
def ex18a():
import random
def compare_numbers(number, user_guess):
cowbull = [0, 0] # cows, then bulls
for i in range(len(number)):
if number[i] == user_guess[i]:
cowbull[1] += 1
else:
cowbull[0] += 1
return cowbull
if __name__ == "__main__":
playing = True # gotta play the game
number = str(random.randint(0, 9999)) # random 4 digit number
print(number)
guesses = 0
print("Let's play a game of Cowbull!") # explanation
print("I will generate a number, and you have to guess the numbers one digit at a time.")
print("For every number in the wrong place, you get a cow. For every one in the right place, you get a bull.")
print("The game ends when you get 4 bulls!")
print("Type exit at any prompt to exit.")
while playing:
user_guess = input("Give me your best guess!")
if user_guess == "exit":
break
cowbullcount = compare_numbers(number, user_guess)
guesses += 1
print("You have " + str(cowbullcount[0]) + " cows, and " + str(cowbullcount[1]) + " bulls.")
if cowbullcount[1] == 4:
playing = False
print("You win the game after " + str(guesses) + "! The number was " + str(number))
break # redundant exit
else:
print("Your guess isn't quite right, try again.")
def ex21():
with open('kalle.txt','r') as my_file:
# my_file.write("Hello world again\n")
print(my_file.read())
print("Ready!")
def ex22():
with open("Exercises.py",'r') as myfile:
content = myfile.read().split()
result = {}
for word in content:
if word in result.keys():
result[word]+=1
else:
result[word] = 1
for k in sorted(result):
print(result[k],k)
def ex23():
pn = []
hn = []
with open("primenumbers.txt",'r') as primes:
pn = list(primes.read().split())
with open("happynumbers.txt", 'r') as happy:
hn = list(happy.read().split())
res = [x for x in hn if x in pn]
print(res)
def ex27():
game = [['-','-','-'],
['-','-','-'],
['-','-','-']]
def check_winner():
for row in game:
if len(set(row)) == 1:
if row[0] != '-':
print(row[0],"win!")
return True
for col in zip(*game):
if len(set([i for i in col])) == 1:
if col[0] != '-':
print(col[0],"win!")
return True
if len (set([game[0][0],game[1][1],game[2][2]])) == 1 and game[0][0] != '-':
print(game[0][0],"win!")
return True
if len (set([game[0][2],game[1][1],game[2][0]])) == 1 and game[0][2] != '-':
print(game[0][2],"win!")
return True
return False
def print_board():
space_left = False
for row in game:
for col in row:
print(col," ",end='')
if col == '-':
space_left = True
print()
if check_winner():
return True
elif not space_left:
print("No winner!")
return True
else:
return False
def get_input(user):
answer = str(input(user + "(x,y): "))
pos = list(answer.split(","))
if game[int(pos[0])][int(pos[1])] == '-':
game[int(pos[0])][int(pos[1])] = user
return False
else:
return True
print_board()
while True:
while get_input('X'):
print("Illegal pos")
if print_board():
break
while get_input('O'):
print("Illegal pos")
if print_board():
break
def ex34():
import json
FILENAME = "birthdays.json"
NAME = "name"
BIRTHDAY = "birthday"
def store_new_person(res):
print(res)
with open(FILENAME,"w")as bd:
bd.write(json.dumps(res,indent=2,sort_keys=True))
with open(FILENAME,'r') as bd:
result = json.loads(bd.read())
result.append({"name":"Mattias","birthday":"930725"})
print("before",result)
result.append([{"name":"LiQi","birthday":"920914"},{"name":"Ding Fung","birthday":"670430"}])
print("after",result)
name = str(input("Enter person to lookup:"))
found = False
for person in result:
if person[NAME] == name:
print("Birthday:",person[BIRTHDAY])
found = True
if not found:
birthday = str(input("Not, found. Enter birthday:"))
result.append({NAME: name, BIRTHDAY: birthday})
store_new_person(result)
ex34()
|
b4553f670eefb5c12ae6261b3b8aa57bfb890f05 | ksoftlabs/labsheets1001 | /Tutorial 7 (Aditional) 06-05-2016/queue_using_dequeue.py | 167 | 3.640625 | 4 | from collections import deque
queue=deque([])
print(queue)
queue=deque(["a","b","c","d","e"])
print(queue)
queue.append("f")
print(queue)
queue.popleft()
print(queue)
|
cd097fcb70e992d098a162539705130d5a937e41 | LiuAllan/Seng265 | /lab5/word_counter.py | 275 | 3.640625 | 4 | import sys
words = sys.stdin.read().split()
#word = lines.split(" ") ; word
print("Number of words:{}".format(len(words)))
count = [0] * 256
for word in words: count[len(word)] += 1
for i, c in enumerate(count):
if c > 0: print("Word length: {:02} = {}".format(i, c))
|
a73e5abefed6a9feec5c8db434c50fa6bdeb22cd | 8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions | /Chapter01/0039_re_groups_alternative.py | 436 | 3.5625 | 4 | """
Listing 1.39
Groups are also useful for specifying alternative patterns. Use the
pipe symbol (|) to indicate that either pattern should match.
"""
from re_test_patterns_groups import test_patterns
def main():
test_patterns(
"abbaabbba",
[
(r"a((a+)|(b+))", "a then seq. of a or seq. of b"),
(r"a((a|b)+)", "a then seq. of [ab]")
]
)
if __name__ == "__main__":
main()
|
979a26178f187c901e74383d293c848d2f02fae9 | Riopradheep007/Leetcode-problem-solving | /Easy/longest_common_prefix_in_list.py | 264 | 3.71875 | 4 | def longestCommonPrefix(strs):
if len(strs) == 0:
return ''
res = ''
strs = sorted(strs)
for i in strs[0]:
print(strs[-1])
if strs[-1].startswith(res+i):
res += i
else:
break
return res
n=input.split()
print(longestCommonPrefix(n))
|
3444f08fdf55b410a0dd91619f2a35f5d51b346e | Dombrauskas/Apart_-_Stuff | /Matemática/MDC/mdc.py | 1,628 | 4.125 | 4 | """
"
" Autor Maurício Freire
" Cálculo do Máximo Divisor Comum consiste em encontrar o maior termo comum a
" dois (ou mais) números capaz de dividir ambos.
" Calcule of the Greatest Common Divisor consists in finding the greatest value
" common to two (or more) number that is able to divide both.
"""
def mdc(x, y):
# Impede a seleção de números iguais ou negativos.
# Prevents the choice of equal or negative numbers.
if x < 0 or y < 0:
print("Impossível calcular o MDC!")
x = y
# Define o maior número, ou os define como iguais.
# Define the highest number, or define them as equals.
if x > y:
mx = x
mn = y
elif x < y:
mx = y
mn = x
else:
print('Informe números diferentes!\n')
return True
# Evita uma possível divisão por zero.
# Avoid a possible ZeroDivisionError.
try:
a = int(mx / mn)
b = mx % mn
#print("{} / {} = {}".format(mx,mn,b))
# Se b for diferente de zero o MDC ainda não alcançado.
# If b is non-zero the GCD has not been reached yet.
if b != 0:
mdc(mn, b)
else:
print("MDC {}".format(mn))
except ZeroDivisionError:
print("MDC não existe!")
e = True
while e:
# Garante que sejam informados apenas inteiros.
# Ensures that just integers to be informed.
try:
s = int(input('Informe o 1º número: '))
r = int(input('Informe o 2º número: '))
e = mdc(s, r)
except ValueError:
print("Informe números inteiros apenas!")
e = True
|
8bf6ea9bdc046346c27b066bab593cf24d179745 | andrea9888/domaci2 | /zad1.py | 236 | 3.546875 | 4 | lista=list(range(1,11))
lista1=[]
lista2=[]
k=0
import random
while k!=5:
lista2.append(random.choice(lista))
k=k+1
for i in lista:
if lista2.count(i)==0:
lista1.append(i)
print (list(zip(lista1, lista2))) |
54260f6335ff9e44f259bd691ab8f9e85995d021 | MarynaHaiduk/pthn | /HackerRank/on_sale.py | 306 | 3.65625 | 4 | #!/usr/bin/python
if __name__ == "__main__":
fruits = ["banana", "apple", "pineapple", "oranges"]
on_sale = ["banana", "apple", "tomatoes"]
print("All: ", set(on_sale) | set(fruits))
print("On Sale: ", set(on_sale) & set(fruits))
print("Others on Sale: ", set(on_sale) - set(fruits))
|
dd2ec105719515708ac9dd1c18175fa919403981 | bmcgahee/Math | /compositefunctions.py | 506 | 3.609375 | 4 | def f(x):
y = x*x + 5
return y
def g(x):
y = x - 2
return y
def fog(x):
t = g(x)
y = f(t)
return y
def gof(x):
t = f(x)
y = g(t)
return y
#Test 1
fy = f(3) #f(3) = 3^2 + 5 = 14
gy = g(3) #g(3) = 3 - 2 = 1
print "f(3) = " + str(fy)
print "g(3) = " + str(gy)
#Test 2
fog = fog(-2) #f(g(-2)) = f(-4) = (-4)^2 + 5 = 21
gof = gof(-2) #g(f(-2)) = g(9) = 9 - 2 = 7
print "f(g(-2)) = " + str(fog)
print "g(f(-2)) = " + str(gof)
|
9c4686b06584a5bc515094a34f05c15422b17b2f | pulakanamnikitha/nikki | /552.py | 100 | 3.5 | 4 | p,o= map(int,raw_input().split())
s=p*o
if (p % 2) == 0:
print ("even")
else:
print ("odd")
|
8fd59853e3650e070730289521f54e30de20f0da | ucsb-cs8-m17/Lecture3_0810 | /turtle_demo_01.py | 206 | 3.734375 | 4 | import turtle
t = turtle.Turtle()
# Invoke the shape method,
# passing the string "turtle"
# as a parameter
t.shape("turtle")
# A simple T
t.forward (50)
t.goto (25, 0)
t.right (90)
t.forward (100)
|
4cced7ff49070e5bf42dfc6dcbc9c8cee03fb945 | flowxcode/pySnips | /elgamal/appro1/likelyPrime.py | 1,997 | 3.609375 | 4 | #! /usr/bin/python
'''Implementation of the Miller-Rabin primality test. '''
from random import randint
# import gcd
from math import log
# from math import pow
from math import gcd
from mrabingfg import *
def isMillerRabinPsuedoPrime(n,a):
if n % 2 == 0:
return False #even numbers aren't prime
m = n-1; k = 0
#find number of times 2 divides n-1
while m % 2 == 0:
m = int(m/2)
k = k + 1
# y = pow(a,m,n)
y = pow(a,m,n)
if y == 1:
return True
for i in range(k):
if y == n-1:
return 1
y = y*y % n
return False
def isLikelyPrime(n, pFail):
'''Return True if n is prime with probability > 1 - pFail.
Return False if n is found to be composite.
>>> isLikelyPrime(12304079, 10**-10)
True
>>> isLikelyPrime(32451611, 10**-10)
True
>>> isLikelyPrime(12304079*32451611, 10**-10)
False
'''
t = int(1 - log(pFail)/log(4)) # use conservative fraction witnessses > 3/4
for i in range(t):
a = randint(1,n-1)
#if gcd(a,n) != 1 or not isMillerRabinPsuedoPrime(n,a):
if gcd(a,n) != 1 or not miillerTest(n,a):
return False
return True
def likelyPrime(bits, pFail):
'''Return a random number with the specified number of bits that is prime
with probability > 1 - pFail.'''
assert bits > 1, 'No 1-bit prime'
nLow = (1 << (bits-1)) + 1
nHigh = (1 << bits) - 1
while(True):
n = randint(nLow, nHigh)
if isLikelyPrime(n, pFail):
return n
## Practical testing shows the 1/4 inaccuracy bound in Miller-Rabin
## is extremely conservative.
def fractionFailMillerRabin(n, tries):
'''n is the number to test for the given number of tries.
Return the fraction of Miller-Rabin tests not passed.
'''
count = 0
for i in range(tries):
a = randint(1,n-1)
if gcd(a,n) != 1 or not isMillerRabinPsuedoPrime(n,a):
count += 1
return 1.0*count/tries
if __name__ == '__main__':
import doctest
doctest.testmod() #verbose=True)
|
3e9958c4ab2b639055165ad73ad7e1eb1d20635c | apollomat/TechInterview | /problems/math/hammingDistance.py | 527 | 4.21875 | 4 | '''
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
'''
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
res = x ^ y # gives all bits that are different
count = 0
while res > 0:
if res & 1:
count += 1
res = res/2
return count
|
df57c1e40ca51c77bc1d6d8b088132f9ea23688b | jandrovins/cp | /CP/10106-Product/sol.py | 275 | 3.59375 | 4 | from sys import stdin
cont =0;
for line in stdin:
if(cont+1 == 2):
cont = 0
b = line
print(int(a) * int(b))
continue
elif cont == 0:
a = line
cont += 1
#while (a = int(input())) && b = int(input()):
# print(a*b)
|
9fb78d6f57282958c4c3d28463b2ae175552704e | vish9767/python | /programes/mix.p/def.while.for.py | 249 | 4.03125 | 4 | def star():
name=('vishal','akshay','rohan','somnath')
for e in name:
print("\n")
print(e)
a=int(input("enter the value for star how star you want"))
i=0
while(i<a):
print("*",end="")
i=i+1
star()
|
dbf4d77a4a43b63e608a0e1d9a48fd2f668b9d29 | ramanaidu07/python | /Assignment1_area_of_triangle.py | 134 | 3.859375 | 4 | i1=input('enter base length:')
i2=input('enter height:')
b=float(i1)
h=float(i2)
area=1/2*(b*h)
print('area of triangle=',area)
|
109d597939aaea63c16562a4a64bcc7243fbb570 | macdit3/PasswordGeneratorApp | /PasswordGeneratorApp.py | 1,558 | 4.59375 | 5 | # This program will generate password by
# substring first 2 characters and display
# combined character.
import random
#1. Crreate a greeting for your program
print('Welcome Strong password generator app')
# Create an array to store the user's inputs
inputs = []
new_password = []
random_pass = []
#2. Ask the user for his/her mother's middle name
mother_middle_name = input('What is your mother middle name:')
# Add to the list
inputs.append(mother_middle_name)
#3. Ask the user for his/her pet's name
pet_name = input('What is your pet name: ')
inputs.append(pet_name)
#4. Ask the user for his/her older' son name
older_son_name = input('What is your older son name: ')
inputs.append(older_son_name)
#5. Ask the user for his/her city of birth name
city_of_birth = input('What is the name of city of your brith? ')
inputs.append(city_of_birth)
# Generate strong password using provided information
for x in inputs:
print(x)
first_two_chars = x[0:2]
#first_two_chars = x[2:-2]
new_password.append(first_two_chars)
# Get the first 2 character of each element
# store it inside new array - new password
#new_password.append((x[0:2]))
# Profile information like first name, last name, SSN, Phone number,
# address, email should not be included in the generated password
# Add all characters of array new_password
for y in new_password:
print(y)
# print('Your new generated password is : '+ new_password)
joined_password = ''.join(new_password)
# Display the output
print("The generated password is : " + joined_password)
|
e5b16b157d098e0c7220232e7c37ccc58cd3eb83 | h-j-13/Algorithms-Soulution | /剑指offer/丑数.py | 1,438 | 3.53125 | 4 | # -*- coding:utf-8 -*-
class Solution:
"""
题目描述
把只包含因子2、3和5的数称作丑数(Ugly Number)。
例如6、8都是丑数,但14不是,因为它包含因子7。
习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
"""
def GetUglyNumber_Solution(self, index):
# 丑数的定义是1或者因子只有2 3 5,可推出丑数=丑数*丑数,假定丑数有序序列为:a1,a2,a3.......an
# 所以可以将以上序列(a1除外)可以分成3类,必定满足:
# 包含2的有序丑数序列:2*a1, 2*a2, 2*a3 .....
# 包含3的有序丑数序列:3*a1, 3*a2, 3*a3 .....
# 包含5的有序丑数序列:5*a1, 5*a2, 5*a3 .....
# 以上3个序列的个数总数和为n个,而且已知a1 = 1了,将以上三个序列合并成一个有序序列即可
# 程序中t2,t3,t5实际就是合并过程中三个序列中带排序的字段索引
if index < 7:
return index
ugly = [1]
i2, i3, i5 = 0, 0, 0
for i in xrange(1, index):
ugly.append(min(ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5))
if ugly[i] == ugly[i2] * 2:
i2 += 1
if ugly[i] == ugly[i3] * 3:
i3 += 1
if ugly[i] == ugly[i5] * 5:
i5 += 1
return ugly[index - 1]
|
b408ca04a4a29b1830a8a589a5c3cd6e003afb76 | kouma1990/AtCoder-code-collection | /contests/ABC1-100/ABC54/a.py | 188 | 3.796875 | 4 | a, b = (int(i) for i in input().split())
if a==b:
print("Draw")
elif a==1:
print("Alice")
elif b==1:
print("Bob")
elif max(a,b) == a:
print("Alice")
else:
print("Bob") |
7229619a5ab3e53b5fd8a54139cd77ed84d78d0e | mand2/python-study | /day05/create_decorator2.py | 544 | 4.15625 | 4 | """
ref: https://www.datacamp.com/community/tutorials/decorators-python
application of create_decorator1.py
succeed to decorator_test.py
advantages of using these type:
- don't have to assign decorator_function
- just put @decorator to what-you-want-to-use function
- and just call the what-you-want-to-use function !
"""
def greeting_decorator(function):
def wrapper():
return function().upper()
return wrapper
@greeting_decorator
def evening():
return 'good evening!'
print(evening()) # GOOD EVENING!
|
d60ee8a6c5b0ba4bb4a2a2fc0f909e75a87c632e | shreezan123/Python-Interview-Practice-Problems | /sumpairs.py | 461 | 3.5625 | 4 | def sumnums(arr,sum):
anslist = []
dict = {}
for each in arr:
if each not in dict:
dict[each] = 1
else:
dict[each] += 1
print(dict)
for each in dict:
if dict[each] == 0:
break
target = sum - each
if target in dict:
anslist.append((each,target))
dict[each] -= 1
dict[target] -= 1
return anslist
print(sumnums([1,2,3,2,4,0],4)) |
643aa2b85d8ff2ede6411a374582d7683857a896 | zhouyinfan/socket | /class49/4.16.py | 7,362 | 3.765625 | 4 | # lis1=[1,2,34,56,7,2,4,2]
# print(id(lis1))
# lis2=[3,4,[5,6]]
# lis3=lis1+lis2
# print(lis3)
# lis4=lis3[1:3:1]
# print(lis4)
# for i in lis3:
# print(i)
#内置函数
##增
#append 整体加进去
# lis1.append([1,2,3,4])
# print(lis1)
# print(id(lis1))
#extend将元素拆分开加进去,可迭代对象
# lis1.extend([1,2,3])
#中间加元素
# lis1.insert(2,"hello")
# print(lis1)
##删
# del lis1[0]
#print(lis1)--关键字,del下标或者列表名
# lis1.pop(1)
# print(lis1)
# lis1.remove(2)
# print(lis1)
#remove 要删除特定的值,可以通过循环来删
# for i in lis1:
# if i==2:
# lis1.remove(i)
# print(lis1)
#-------------------练习分割线
# 1.创建一个列表,内部嵌套了3个列表
# a=['xiaoming','student',10],
# b=['xiaohong','coder',23],
# c=['xiaohuang','boss',35],
# 打印第2个列表的第1个元素,打印第3个列表的所有数据,
# 删除第2个列表,打印整个大列表数据。
# lis=[['xioaming','student',10],['xiaohong','coder',23],['xiaohuang','boss',35]]
# print(lis[1][0])
# print(lis[2])
# lis.remove(2)
# print(lis)
##查
#查找元素下标,找到返回下标,默认匹配第一个元素
# print(list1.index(3))
# 统计元素个数
# print(list1.count(3))
#改
# list1[0]=9
# print(list1)
# list1.reverse()
# print(list1)
# list1.sort()
# print(list1)
# list1.reverse()
# print(list1)
# list1.sort(reverse=True)
# print(list1)
# 2.将第1题中的大列表的末尾添加一个元素10。
# lis=[['xioaming','student',10],['xiaohong','coder',23],['xiaohuang','boss',35]]
# a) 将添加的元素通过列表打印出来。
# lis.append(10)
# print(lis)
# b)输出大列表中出现10这个元素的次数。
# count=0
# num=0
# for i in lis:
# if i==10:
# count+=1
# else:
# num+=i.count(10)
# print(count+num)
# print(lis.count(10))
# c)输出第1个子列表中出现第一个元素‘10’的位置。
# print(lis[1].index(10))
# d)对此列表进行反序输出。
# lis.reverse()
# print(lis)
# e)移除第2个子列表中的第3个元素,输出整个列表。
# del(lis[1][2])
# print(lis)
# list[1].pop(2)
# print(lis)
# f)移除整个列表中所有出现‘10’的元素并输出。
# 3. 在歌星大奖赛中,有10个评委为参赛的选手打分,分数为1~100分。
# 选手最后得 分为:去掉一个最高分和一个最低分后其余8个分数的平均值。请编写一个程序实现。
# sl=[]
# for i in range(0,10):
# score=eval(input("输入分数"))
# sl.append(score)
# print(sl)
# sl.sort()
# sl.pop(0)
# sl.pop()
# sum=0
# for i in sl:
# sum+=i
# print(sum/8)
#sl=[]
# for i in range(0,10):
# score=eval(input("请输入一个分数"))
# tup=("a",12,43,65,12)
# print(type(tup))
# print(tup[3])
# tup1=(6,)
# tup2=tup+tup1
# print(tup2)
# print(tup[1:4])
# for i in tup:
# print(i)
# print(tup.index(12))
# print(tup.count(12))
# print(tup)
# print(len(tup))
# 1.创建一个元组,分别进行索引、添加、长度计算、切片操作。
# yuanzu=("z","y","f",1,2,3)
# print(yuanzu.index("f"))
#
# print(len(yuanzu))
# yuanzu2=yuanzu[0:3]
# print(yuanzu2)
# 2.创建两个元组,进行连接操作。
# yuanzu3=yuanzu+yuanzu2
# print(yuanzu3)
# 3.创建一个列表和元组,将其连接后打印出
# 集合
# set1={2,3,4}
# set2={2,3,5}
#交集set3=set1&set2
#并集set3=set1|set2
#差集set3=set1-set2
#差集set3=set2-set1
#表示set2与set1不一样的元素
# set2.add(6)
# print(set2)
# set1.update(set2)
# print(set1)
# 1.使用花括号和set创建各一个集合。
# 2.对第1题中的集合进行交、并、差集运算。
# dic={"k1":1,"k2":[1,2,3],"k3":10,"k4":"hello"}
# for i in dic:
# if dic[i]==10:
# print(i)
#dic["k2"]="hello"
# dic2={1:"a",2:"b"}
# dic.update(dic2)
# dic1=dic.fromkeys([3,4],"hello")
# print(dic1)
# a=dic.setdefault(2,"hello")
# b=dic.setdefault(3,"hello")
# a=dic.get("k2")
# print(a)
# del dic["k1"]
# dic.pop(2)
# dic.clear()
# print(dic)
# a=dic.keys()
# a=list(a)
# print(a[0])
# a=dic.values()
# print(a)
# a=list(a)
# print(a[0])
#1. 创建一个字典dic1,并练习增删查改的操作。
# dic1={"k1":1,"k2":2,"k3":3,"k4":4}
#增
# dic1["k5"]=5
# print(dic1)
# dic2={"k6":6,"k7":7}
# dic1.update(dic2)
# print(dic1)
# dic1.setdefault("k8",8)
# print(dic1)
# dic2=dic1.fromkeys([1,2,3,4,5,6],"hello")
# print(dic2)
#查找
#dic1={"k1":1,"k2":2,"k3":3,"k4":4}
# a=dic1.setdefault("k1",2)
# print(a)
# print(dic1["k2"])
# print(dic1.get("k3"))
#改
# dic1["k2"]=5
# print(dic1)
#删
# dic2={"k1":1,"k2":2,"k3":3,"k4":4}
# del dic2
# print(dic2)
#其他操作
# dic1={"k1":1,"k2":2,"k3":3,"k4":4}
# a=dic1.keys()
# print(a)
# a=list(a)
# b=a[1]
# print(b)
# b=dic1.values()
# print(b)
# b=list(b)
# c=b[2]
# print(c)
# 2.创建一个列表,里面的有两个元素,每个元素是一个字典:
# dic1 = {'name':'zhangsan','age':'20'}
# dic2 = {'name':'lisi','age':'22'}
# 1)对此列表中的第2个元素(字典)中的age修改为23。
# lis1 = [{'name':'zhangsan','age':'20'},{'name':'lisi','age':'22'}]
# a=lis1[1]
# a['age']=23
# print(lis1)
# 2)向此列表再添加一个元素,仍然为字典dict3 = {'name':'wang','age':'30'}。
# dict3 = {'name':'wang','age':'30'}
# lis1.append(dict3)
# print(lis1)
# 3)打印列表中第一个元素的所有键。
# c=lis1[1]
# d=c.keys()
# print(d)
# 要求:以上不能直接操作dic,而是操作列表。
# 3.给定一个成绩单(字典),找出最大最小值,并求出平均成绩。成绩自己定义!
#最重要的就是要讲字典转化为元组
# sc={"a":89,"b":67,"c":54,"d":33}
# score=sc.values()
# score=set(score)
# score1=max(score)
# score2=min(score)
# avg=sum(score)/len(score)
# print(score1)
# print(score2)
# print(avg)
# 4.已知列表score =[45,98,65,87,43,83,68,74,20,75,85,67,79,99] ,
# 统计并以字典的形式输出各成绩等级的人数。
# 等级A:(90~100)B:(80~89) C:(70~79) D:(60~69) E:(60以下)
# score =[45,98,65,87,43,83,68,74,20,75,85,67,79,99]
# dic1={}
# a = 0
# b = 0
# c = 0
# d = 0
# e = 0
# for i in score:
# if i>=90 and i<=100:
# a+=1
# elif i>=80 and i<=89:
# b+=1
# elif i>=70 and i<=79:
# c+=1
# elif i>=60 and i<=69:
# d+=1
# else:
# e+=1
# dic1["A级"]=a
# dic1["B级"]=b
# dic1["C级"]=c
# dic1["D级"]=d
# dic1["E级"]=e
# print(dic1)
# A=0
# B=0
# C=0
# D=0
# E=0
# score =[45,98,65,87,43,83,68,74,20,75,85,67,79,99]
# for i in score:
# if i<101 and i>=90:
# A+=1
# elif i>=80 and i<=89:
# B+=1
# elif i>=70 and i<=79:
# C+=1
# elif i>=60 and i<=69:
# D+=1
# else:
# E+=1
# dic4={}
# dic4['A:']=A
# dic4['B:']=B
# dic4['C:']=C
# dic4['D:']=D
# dic4['E:']=E
# print(dic4)
# 5.分别输入年、月、日,判断此日期是当年的第几天。
# (把闰年考虑进去,能被4整除且不能被100整除或者能被400整除的为闰年)
year=eval(input("今年是哪一年:"))
month=eval(input("现在几月:"))
day=eval(input("今天是该月第几天:"))
if (year%4==0 and year%100!=0)or year%400==0:
dic1={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
num=0
for i in range(month+1):
if i in dic1.keys():
num+=dic1[i]
day=day+num
print("现在是今年第%d天"%(day))
|
5840c22e07786544e10d9fef99467fd87a02a051 | prabhuyellina/Assignments_Python | /assignments/panagram.py | 361 | 4.0625 | 4 | import string
def panagram(x):
x=x.lower()
if len(x)<26:
return False
else:
x.replace(' ','')
count=0
for i in string.ascii_lowercase:
if i in x:
count+=1
if count==26:
return True
return False
print panagram(raw_input('Enter the sentence'))
|
fab57b68ddc6edc25d7a8718ac6a62ba48428cff | ThibautBernard/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/1-search_replace.py | 248 | 3.90625 | 4 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
counter = 0
new = []
for i in my_list:
if i == search:
new.append(replace)
else:
new.append(i)
counter += 1
return new
|
5b8c8344c07956fc8291710ce56dac080ac4b77e | vaclav0411/algorithms | /Задания 14-го спринта/Простые задачи/A. Генератор скобок.py | 592 | 3.625 | 4 | def generate_brackets(n: int, k: int, prefix='', lead=0, trailing=0):
if n == 0:
print(prefix)
else:
if lead < k and trailing > 0:
generate_brackets(n-1, k, prefix+'(', lead+1, trailing+1)
generate_brackets(n-1, k, prefix+')', lead, trailing-1)
elif trailing > 0:
generate_brackets(n-1, k, prefix+')', lead, trailing-1)
elif lead < k:
generate_brackets(n-1, k, prefix+'(', lead+1, trailing+1)
if __name__ == "__main__":
half = int(input())
amount = 2 * half
generate_brackets(amount, half)
|
8f568416ca19c096f136ee7e8ec54c6f5c76fd72 | idimitrov07/blockchain-tutorials | /simple_blockchain_python/blockchain.py | 2,013 | 3.625 | 4 | from block import Block
class Blockchain:
def __init__(self):
self.chain = []
self.all_transactions = []
self.genesis_block()
def genesis_block(self):
transactions = {}
gen_block = Block(transactions, '0')
self.chain.append(gen_block)
return self.chain
# print blockchain
def print_blocks(self):
for i in range(len(self.chain)):
current_block = self.chain[i]
print("Block {} {}".format(i, current_block))
current_block.print_block()
# add block to the chain
def add_block(self, transactions):
previous_block_hash = self.chain[len(self.chain) - 1].generate_hash
new_block = Block(transactions, previous_block_hash)
self.chain.append(new_block)
def validate_chain(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i-1]
if current.hash != current.generate_hash():
return False
if previous.hash != previous.generate_hash():
return False
return True
# implement proof of work
def proof_of_work(self,block, difficulty=2):
diff_str = difficulty * "0"
proof = block.generate_hash()
while True:
block.nonce = block.nonce + 1
if proof[0:2] == diff_str:
block.nonce = 0
break
else:
proof = block.generate_hash()
return proof
# add new blocks
def add_block(self, transactions):
previous_block_hash = self.chain[len(self.chain) - 1].hash
new_block = Block(transactions, previous_block_hash)
proof = self.proof_of_work(new_block)
self.chain.append(new_block)
return(proof, new_block)
new_transactions = [{'amount': '30', 'sender':'alice', 'receiver':'bob'},
{'amount': '55', 'sender':'bob', 'receiver':'alice'}]
my_blockchain = Blockchain()
my_blockchain.add_block(new_transactions)
my_blockchain.print_blocks()
my_blockchain.chain[1].transactions = "fake_transactions"
print("Chain is valid: {}".format(my_blockchain.validate_chain())) |
741baa24e19cdaaff28c899211a30edf91b315fd | ltjhappy/PythonCode | /Base/TestVar.py | 592 | 3.90625 | 4 | # python 推荐使用 纯小写加下划线的方式做变量名
alex_of_age = 19
name = "ucs"
print(name)
x = 100
wu = x
xf = x
del (x)
# print(x)
print(wu)
国家 = "Korea"
print(国家)
# id 反映的是变量值的内存地址,内存地址不同id则不同
print(id(alex_of_age))
# type 不同类型的值用来表示记录不同的状态
print(type(alex_of_age))
x1 = "-9"
y1 = "-9"
print(id(x1))
print(id(y1))
x2 = 'algorithm,898989:,os'
y2 = 'algorithm,898989:,os'
print(id(x2),id(y2))
# is: 比较两个值身份id是否相等
# ==: 比较左右两个值他们的值是否相等
|
60916981adb969986be808b4350a30569851577f | floydawong/LeetCode | /python/003.py | 975 | 3.625 | 4 | # https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
'''
3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
'''
class Solution(object):
def lengthOfLongestSubstring(self, s):
d = {}
start = 0
ans = 0
for i, c in enumerate(s):
if c in d:
start = max(start, d[c] + 1)
d[c] = i
ans = max(ans, i - start + 1)
return ans
|
8570f00103807439cd9777031db3efa33ae4a929 | matsub/sandbox | /python/pythonchallenge/prob_01.py | 509 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
'''http://www.pythonchallenge.com/pc/def/map.html'''
import string
def decode(code):
l = string.ascii_lowercase
tbl = str.maketrans(l, l[2:]+l[:2])
return code.translate(tbl)
if __name__ == '__main__':
code = '''\
g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc
dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.
sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.
'''
print(decode(code))
|
b6fd47c4ccbe6b0a205d2dbd487389fe401d5c1a | nilavann/HackerRank | /Regex/Applications Challenges/Split the Phone Numbers.py | 247 | 3.8125 | 4 | #!/bin/python3
import re
Regex = r"^(\d+)( |-)(\d+)\2(\d+)$"
for _ in range( int( input())):
result = re.match( Regex, input())
print( "CountryCode={},LocalAreaCode={},Number={}".format(result.group(1), result.group(3), result.group(4))) |
52e2ef102aa34ac7d6f9170d1118937f058ef997 | mofei952/algorithm_exercise | /leetcode/141 Linked List Cycle.py | 1,221 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mofei
# @Time : 2018/9/23 14:35
# @File : test141.py
# @Software: PyCharm
"""
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
"""
from utils import ListNode
class Solution(object):
def hasCycle(self, head):
"""
判断链表是否有环
:type head: ListNode
:rtype: bool
"""
s = set()
while head is not None:
if head in s:
return True
s.add(head)
head = head.next
return False
def hasCycle2(self, head):
"""
判断链表是否有环,O(1)空间复杂度
:type head: ListNode
:rtype: bool
"""
if not head:
return False
fast = head
slow = head
while fast and fast.next and slow:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
if __name__ == '__main__':
head = ListNode.create_linked_list([1, 2])
# head.next.next.next = head
res = Solution().hasCycle2(head)
print(res)
|
5b13d0c96abd99078b76a222a25046b63384589a | AstroOhnuma/Unit3 | /gauss.py | 358 | 4.1875 | 4 | #Astro Ohnuma
#9/29/17
#gauss.py - using a loop to add up all the numbers from 1 to 100
num1 = int(input('Enter a number: '))
num2 = int(input('Enter another number: '))
num3 = int(input('Enter the difference you want between each term: '))
total = 0
for i in range(num1,num2+1,num3):
total += i
print('The sum of the numbers from',num1,'to',num2,'is',total)
|
8389c2391d5ea11090be1a8e397cc81851b6c7ad | Cold-Front-520/valgundriy | /domashka3-zd1.py | 710 | 3.765625 | 4 | x = []
razm = int(input("введите количество элементов и сами значения "))
for i in range(razm):
x.append(int(input()))
print("это твой массив короче: ", x, "теперь введи циферку - скажу где она")
f = int(input())
for i in range(razm):
if f == x[i]:
slot = i + 1
print("эта циферка стоит на ", slot, "слоте")
# я подумал что для юзера будет полезнее видеть не конкретно "индекс"
# а типо номер в списке. так будет типо понятнее для юзера. поэтому сделал i+1
|
77fd82069aa2648fea685fec4567123642a507cf | subhashiniperni-test/python | /Tested programs code/writingtoexcel.py | 360 | 3.625 | 4 | import xlwt
from xlwt import Workbook
wk: Workbook=xlwt.Workbook()
ws=wk.add_sheet("testing")
r=input("enter how many rows")
c=input("enter how many columns")
#for i in range(0,(r>i),1):
# for j in range(0,(c>j),1):
# ws.write(i,j,"Testing world")
# ws.write(i,j,"www.testing world.com")
# wk.save("C:/DRIVE DATA/Testingworld.xls")
|
d40b5706c173dbc03b7c1289239abddcec3313cd | ofenbach/GuitarSongGenerator | /code/song_generator.py | 960 | 3.5 | 4 | import sys
import random
# Chords
d_chords = ['D', 'Dm']
e_chord = ['E', 'Em']
a_chords = ['A', 'Am']
f_chords = ['F', 'Fm']
g_chords = ['G', 'Gm']
chords = [d_chords, e_chord, a_chords, f_chords, g_chords]
def generate_chords(amount):
""" Generates basic chords.
param: amount of chords (int) """
final_chords = []
for i in range(amount): # TODO fix double chords
final_chords.append(chords[random.randint(0,4)][random.randint(0,1)])
return final_chords
def main():
# setup
arg_list = sys.argv[1:]
intro_chord_list = []
bridge_chord_list = []
refrain_chord_list = []
# generate chords TODO: if (arg_list[0] == "-chords"):
intro_chord_list = generate_chords(4)
bridge_chord_list = generate_chords(2)
refrain_chord_list = generate_chords(4)
# display chords
print("Intro Chords: " + str(intro_chord_list))
print("Bridge Chords: " + str(bridge_chord_list))
print("Refrain Chords: " + str(refrain_chord_list))
main()
|
1eed20de1c866e6da25008911752fd187ae10a07 | Murilo-ZC/FATEC-MECATRONICA-MURILO | /LTP2-2020-2/Pratica08/prog03.py | 544 | 3.875 | 4 | personagens = {"dps": [] , "healer": [], "support": [], "tank": []}
quantidade_de_personagens = int(input("Quantidade de personagens:"))
contador = 0
while contador < quantidade_de_personagens:
nome = input("Qual o nome do personagem:")
classe = input("Qual a classe do personagem:").lower()
#Verifica se a classe informada é válida
if classe in personagens.keys():
personagens[classe].append(nome)
#Avança para o próximo registro
contador += 1
else:
print("Classe de personagem invalida!")
print(personagens)
|
52abfcdb90597de144d573de45daca10a81a9092 | dvbridges/regularExpressions | /alternations.py | 643 | 4.40625 | 4 | import re
# Optional items are declared using '?'
# However, you can also search for one of several regex patterns
# This is achieved using the '|' Or logical operator
# This example checks for multiple destinations in a string
pattern = r"Destination.*(Paris | Rome | London)"
msg = "Destination is London"
match = re.search(pattern, msg)
print(match.group())
# This example is useful for filtering emails in a list
pattern = r"(^To:|^From:) (David|Bridges)"
emails = ["To: Admin", "From: Admin",
"To: David", "From: Bridges"]
for email in emails:
match = re.search(pattern, email)
if match:
print(match.group())
|
9e49dd6f783c051fac38e0c429f707e32083f8c6 | kaci65/Nichola_Lacey_Python_By_Example_BOOK | /Strings/rhyme_and_slice.py | 282 | 4.125 | 4 | #!/usr/bin/python3
"""Get input string from user, slice it using indexing then display it"""
string = input("Enter line of a nursery rhyme: ")
print(len(string))
begin = int(input("Enter a starting number: "))
end = int(input("Enter an ending number: "))
print(string[begin:end])
|
dbb8991e2684ef54c23be4dff6b5bbec3172de75 | islanrodrigues/learn-python | /src/08_manipulacao_de_arquivos.py | 1,980 | 4.09375 | 4 | # A manipulação de arquivos se torna bastante fácil com Python.
# A função open() permite que um arquivo seja aberto e;ou criado informando o caminho, o nome do arquivo e o modo de manipulação. Caso o caminho não seja especificado, será considerado o diretório corrente.
'''
Algumas opções dos modos de manipulação:
r -> somente leitura
w -> somente escrita (exclui e cria novamente, caso o arquivo já exista)
x -> escrita exclusiva (se o arquivo já existir, um erro será disparado)
a -> leitura e escrita (não exclui caso o arquivo já exista)
b -> modo binário
t -> modo de texto
A combinação de alguns modos também é possível.
'''
arquivo = open("src/arquivos/meu_primeiro_arquivo.txt", "w")
arquivo.write("Hello World! Meu primeiro arquivo com Python. \n")
arquivo.close()
# A instrução 'with' permite simplicar o gerenciamento de recursos comuns, como o fluxo de manipulação de arquivos. é uma abordagem usada no tratamento de exceções e que torna o código mais limpo e legível.
# Através do bloco 'with' o processo de fechar o arquivo de forma automática.
with open("src/arquivos/meu_primeiro_arquivo.txt", "a") as arquivo:
arquivo.write("\nAqui vai mais uma linha.\n")
# Abrindo o arquivo apenas em modo de leitura.
with open("src/arquivos/meu_primeiro_arquivo.txt", "r") as arquivo:
for linha in arquivo.readlines():
print(linha)
# Salvando um dicionário de dados em um arquivo.
usuarios = {
"maria01": {"nome": "Maria da Silva", "idade": 25, "sexo": "feminino", "login": "maria01"},
"pedro_1": {"nome": "Pedro do Nascimento", "idade": 23, "sexo": "masculino", "login": "pedro_1"},
"jorge.r": {"nome": "Jorge Rodrigues", "idade": 28, "sexo": "masculino", "login": "jorge.r"},
"teresinha": {"nome": "Teresa de Jesus", "idade": 35, "sexo": "feminino", "login": "teresinha"}
}
with open("src/arquivos/usuarios_bd.txt", "a") as arquivo:
for chave, valor in usuarios.items():
arquivo.write(chave + " : " + str(valor) + "\n") |
5db32ff562b9f83b755c099098f2fa32bea33722 | raviranjan145/python-programs | /Tuple_5.py | 4,461 | 4.46875 | 4 | #1. Write a Python program to create a tuple.
# x =()
# print(x)
# fruits = ("apple", "banana", "cherry")
# print(fruits[1])
#2. Write a Python program to create a tuple with different data types.
# diffdatatype = (1,'ram', 50.5,True)
# print(diffdatatype)
#3. Write a Python program to create a tuple with numbers and print one item.
# numbers= (1, 2, 3, 4, 5, 6, 11, 15)
# print(numbers)
# print(numbers[2])
#5.Write a Python program to add an item in a tuple.
# numbers= (1, 2, 3, 4, 5, 6, 11, 15)
# print(numbers)
#
# numbers = numbers +(9, )
# print(numbers)
#
# numbers = numbers[:5]+(21, 14, 7, ) +numbers[:5]
# print(numbers)
#6 write a python program to convert a tupple to string .
# tup = ('e','f', 'g', 'h')
# str = ''.join(tup)
# print(str)
# print(tup[len(tup)-2])
#7 write a python program to get the 4th element and 4th element from the last of the list .
# num = (1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13)
# print(num[3])
# print(num)
# print(num[len(num)-4])
#8 write a python program to find the repeated iteam of a tupple .
# num = (1, 2, 3, 1, 10, 15, 18, 2, 2, 1, 1)
# print(num)
# count = num.count(2)
# count1 = num.count(1)
# print(count)
# print(count1)
# 10 write a python program to check weather the element exits within a tupple
# num = (1, 2, 3, 1, 10, 15, 18, 2, 2, 1, 1)
# print(1 in num)
# print(11 in num)
# 11. Write a Python program to convert a list to a tuple
# num = [1, 2, 3, 1, 10, 15, 18, 2, 2, 1, 1]
#
# print(num)
#
# num = tuple(num)
# print(num)
# 13. Write a Python program to slice a tuple.
# tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
# #used tuple[start:stop] the start index is inclusive and the stop index
# slice = tuplex[3:5]
# #is exclusive
# print(slice)
# #if the start index isn't defined, is taken from the beg inning of the tuple
# slice = tuplex[:6]
# print(slice)
# #if the end index isn't defined, is taken until the end of the tuple
# slice = tuplex[5:]
# print(slice)
# #if neither is defined, returns the full tuple
# slice = tuplex[:]
# print(slice)
# #The indexes can be defined with negative values
# slice = tuplex[-8:-4]
# print(slice)
# #create another tuple
# tuplex = tuple("HELLO WORLD")
# print(tuplex)
# #step specify an increment between the elements to cut of the tuple
# #tuple[start:stop:step]
# slice = tuplex[2:9:2]
# print(slice)
# #returns a tuple with a jump every 3 items
# slice = tuplex[::3]
# print(slice)
# #when step is negative the jump is made back
# slice = tuplex[9:2:-4]
# print(slice)
#14 Write a Python program to find the index of an item of a tuple.
# num = (1, 2, 3, 4, 'ram', 'rohan', 5)
# print(num)
# index = num. index(5)
# print(index)
#15. Write a Python program to find the length of a tuple
# num = (1, 2, 3, 4, 'ram', 'rohan', 5)
# print(len(num))
#16. Write a Python program to convert a tuple to a dictionary.
# tuplex = ((2,'w'),(1,'a'))
# dict1 = {}
#
# for x,y in tuplex:
# dict1[x] = y
#
# print(dict1)
# 17. Write a Python program to unzip a list of tuples into individual lists.
# num = ((1, 2, 3, 4,) ,('ram', 'rohan', 5))
# print(list(zip(*num)))
#18. Write a Python program to reverse a tuple
# num = (1, 2, 3, 4, 'ram', 'rohan', 5)
# rev =reversed(num)
# print(tuple(rev))
# x = ("w3resource")
# # Reversed the tuple
# y = reversed(x)
# print(tuple(y))
# x = (5, 10, 15, 20)
# # Reversed the tuple
# y = reversed(x)
# print(tuple(y))
# 19. Write a Python program to convert a list of tuples into a dictionary.
#
#
# def Convert(tup, di):
#
# for a, b in tup:
# di.setdefault(a, []).append(b)
# return di
#
# tup = [("akash", 10), ("gaurav", 12), ("anand", 14),
# ("suraj", 20), ("akhil", 25), ("ashish", 30)]
#
# dicton = {}
#
# print(Convert(tup, dicton))
# 20. Write a Python program to print a tuple with string formatting. Go to the editor
#Sample tuple : (100, 200, 300)
# Output : This is a tuple (100, 200, 300)
# num = (100, 200, 300)
# print(num)
# Write a Python program to replace last value of tuples in a list.
# Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
# Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
# list1 = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
# list2 =[]
# for i in list1:
# k = list(i)
# k[-1] = 100
# list2.append(tuple(k))
#
# print(list2)
|
8e25f9638d1b6d128c26f19027afe04a02bf8d78 | asswecanfat/git_place | /杂项/新水仙花.py | 823 | 3.625 | 4 | def sure(x,y):
b = []
while True:
if y > 1000 and x >=100:
y = int(input('请重新输入上限:'))
elif x < 100 and y < 1000:
x = int(input('请重新输入下限:'))
elif y > 1000 and x < 100:
x = int(input('请重新输入下限:'))
y = int(input('请重新输入上限:'))
elif y <= 1000 and x >= 100:
break
for a in range(x,y):
ass = (a%100-a%10)/10
can = a % 10
see = (a-a%100)/100
if a == ass**3+can**3+see**3:
b.append(a)
print(a)
if len(b) == 0:
print('在这个范围内没有水仙花数')
print('x,y两个数均在100到1000以内')
x = int(input('请输入下限:'))
y = int(input('请输入上限:'))
sure(x,y)
|
c6bbbe21f5ced8eb7b395ef1418e318291a34382 | WillMc93/AS.605.620 | /Project2/code/hashing.py | 11,119 | 4.03125 | 4 | """
hash_table takes care of storing, maintaining, and interacting with
the hash table.
@authour Will McElhenney
@date 11/6/2019
"""
class hash_table:
"""
Constructor for hash table
@param size: integer for the size of the table
@param mod: integer for the class modulo hash function
@param bucket_size: integer for the size of the buckets
@param collision: string for the collision method to be used
@param c: c values for quadratic collisions
@param hash_func: string for class hash or student hash
"""
def __init__(self, size=120, mod=120, bucket_size=1, collision='quadratic', \
c=[0.5,0.5], hash_func='class'):
# dictionary of accepatable collision types, mapped to the proper func.
collisions = {'linear': self.linear, 'quadratic': self.quadratic, \
'chaining': self.chaining}
# dictionary of accptable hash types, mapped yadda-yadda
hashes = {'class': self.class_hash, 'student': self.my_hash}
# Store the parameters for this table iff acceptable, default otherwise
self.size = size if size > 0 else 120
self.bucket_size = bucket_size if bucket_size > 0 else 1
self.mod = mod if mod > 1 else 120
self.prim_coll_count = 0 # collision count
self.unplaced = [] # items that couldn't be added
self.entered = 0 # number of items entered into the table
# Set actual size if bucket_size > 1
if bucket_size > 1:
self.size = int(self.size / self.bucket_size)
# Tell user if we defaulted
if size <= 0:
print(f"Given size, {size}, is not valid. Defaulting to 120.")
if bucket_size <= 0:
print(f"Given bucket size, {bucket_size}, is not valid. ", \
"Defaulting to 3.")
if mod <= 1:
print(f"Given mod, {mod}, is not valid. Defaulting to 120")
# Initialize collision and c
self.collision = None
self.c = list()
# Error check and set collision and c
if collision in collisions.keys():
self.collision = collisions[collision]
self.c = c
else:
# Tell user what we're defaulting
print(f"The specified collision method {collision} is not valid. ", \
"Defaulting to Quadratic with c=[0.5,0.5]")
# Default
self.collision=self.quadratic
self.c = [0.5,0.5]
# Initialize the table
self.table = list()
# if bucket size == 1 (and not chaining) table consists of empty of Nones
if self.bucket_size == 1 and self.collision != self.chaining:
self.table = [None] * self.size
# otherwise table consists of empty lists unless chaining
elif self.bucket_size > 1 and self.collision != self.chaining:
self.table = [[None for _ in range(self.bucket_size)] \
for _ in range(self.size)]
elif self.collision == self.chaining:
self.table = [self.link() for _ in range(self.size)]
# Initialize freespace stack for chaining
self.freespace = None
if self.collision == self.chaining:
self.freespace = [i for i in range(self.size)]
# Set the hash function (class vs mine)
self.hash_func = None
if hash_func in hashes.keys():
self.hash_func = hashes[hash_func]
else:
print(f"The hash-type, {hash_type}, is not valid. Defaulting to ", \
"the in-class hash.")
self.hash_func = self.class_hash
"""
Internal link object for "node" in chained hash
"""
class link:
"""
Constructor
@param value: value to be entered into hash_table
@param next_link: int representing the index of the next link
"""
def __init__(self, value=None, next_link=None):
self.value = value
self.next_link = next_link
"""
Function for calculating how full table is
"""
def fill_ratio(self):
return self.entered / (self.size * self.bucket_size)
"""
Linear probing function
@param hash_key: hash key originally generated
@param size: gives the maximum this hash should be
(useful for bucket_size > 1)
"""
def linear(self, hash_key, size=None):
# keep track of probes
count = 0
# default if unset
if size == None:
size = self.size
# keep yielding hashes until we find a usable bucket
new_hash = hash_key
while count < size:
count += 1
new_hash = new_hash + 1 if new_hash + 1 < size else 0
yield new_hash
if count == size:
yield None
return
"""
Quadratic probing function.
Could be combined with linear, but it was messy when I tried.
@param hash_key: hash key originally generated
@param size: gives the maximum this hash should be
(useful for bucket_size > 1)
"""
def quadratic(self, hash_key, size=None):
# keep track of probes (i)
count = 0
# default if unset
if size == None:
size = self.size
# keep yielding hashes until we find a useable bucket
new_hash = hash_key
while count < size:
count += 1
c1, c2 = self.c
new_hash = (new_hash + c1 * count + c2 * count**2) % self.mod
# Dr. Chlan specified mod 41 for the buckets but it don't work
if new_hash >= size:
new_hash = size - 1
yield int(new_hash)
if count == size:
yield None
return
"""
Chaining collision function. Maintains free space in self.freespace, and
updates previous link in chain.
@param hash_key: hash key originally generated
"""
def chaining(self, hash_key):
# linear probe for space but make reference in link
count = 0
assert(self.freespace != None)
# if table is full skip all this
if len(self.freespace) < 1:
return None
new_hash = hash_key
occupant = self.table[hash_key]
# Traverse the chain of already collided entries
while occupant.next_link != None:
new_hash = occupant.next_link
occupant = self.table[new_hash]
# Pop Next Free Slot off stack
new_hash = self.freespace.pop()
occupant.next_link = new_hash
return new_hash
"""
Function to add items to the hash table. Tries to put the item in by calling
the hash function, but if it can't it calls the probing function.
Could be neater.
@param elem: value to be added to the hash table
"""
def add(self, elem):
hash_key = self.hash_func(elem)
# split function based on bucket size
if self.bucket_size == 1:
# error check
if hash_key > self.size:
hash_key = self.size - 1
# split bucket_size == 1 on chaining
if self.collision != self.chaining:
# if empty, place here
if self.table[hash_key] is None:
self.table[hash_key] = elem
# otherwise, probe for an empty bucket
else:
for p in self.collision(hash_key):
# increment collision count
self.prim_coll_count += 1
# if hash found and empty, place here
if p is not None and self.table[p] is None:
self.table[p] = elem
break
# otherwise if no hash was found (table full)
elif p is None:
self.unable.append(elem)
self.prim_coll_count -= 1 # last one don't count
break
# special case for chaining
else:
# if empty place here and remove freespace entry
if self.table[hash_key].value is None:
self.table[hash_key].value = elem
self.freespace.remove(hash_key)
else:
# increment collision counter
self.prim_coll_count += 1
# find a hash
hash_key = self.collision(hash_key)
# if suitable hash was found place it
if hash_key is not None:
self.table[hash_key].value = elem
else:
self.unplaced.append(elem)
# bucket size > 1
else:
slot = hash_key[1]
hash_key = hash_key[0]
# if space in this bucket, place here
#print(hash_key, slot, elem, self.mod)
if self.table[hash_key][slot] == None:
self.table[hash_key][slot] = elem
# otherwise, search for hash
else:
for p in self.collision(hash_key):
for s in self.linear(slot, self.bucket_size):
self.prim_coll_count += 1
# if p is not None and there is room in this bucket
if p is not None and s is not None and self.table[p][s] is None:
self.table[p][s] = elem
self.entered += 1
return
# if bucket is full
if s is None and p is not None:
break
# uh-oh (full table)
elif p is None and s is None:
self.prim_coll_count -= 1 # last one don't count
self.unplaced.append(elem)
return
self.entered += 1
"""
class_hash is the default hash function
@param elem: value to be added to the hash table
"""
def class_hash(self, elem):
hash_key = elem % self.mod
# Dr. Chlan gave 41 as modulo for a 40 slot table when bucket size = 3
# which can't work?
if self.bucket_size == 1:
return hash_key
elif self.bucket_size > 1:
hash_key = hash_key if hash_key < self.size else self.size - 1
slot = elem % self.bucket_size
return hash_key, slot
"""
my_hash is the hash I provide. It is riff on middle-square hashing,
technically a type of multiplicative hashing.
@parm elem: value to be added to the hash table
"""
def my_hash(self, elem):
# middle-square
hash_key = str(elem**2)
# if result is too big
if len(hash_key) > len(str(self.size)):
cut = len(hash_key) - len(str(self.size))
if cut % 2 == 0:
cut = int(cut / 2)
hash_key = hash_key[cut:]
hash_key = hash_key[:-cut]
else:
ceil = int((cut - 1) / 2)
floor = int((cut + 1) / 2)
hash_key = hash_key[ceil:]
hash_key = hash_key[:-floor]
assert(len(hash_key) <= 3 and len(hash_key) > 0)
# fit to table
# Here's where I had to get a little creative. Because the table is
# short and includes {11} we have to fit the middle-square to the table
if len(hash_key) == len(str(self.size)):
if int(hash_key) > self.size:
temp = int(hash_key)
if temp > self.size:
temp = temp % self.size
hash_key = str(temp)
return int(hash_key)
"""
Function to produce a string representation of the table.
"""
def to_string(self, nothing=5):
# string we'll output later
outp = str()
# counter for keeping the number of entries per line
prints = 0
# typed this one too many times
_nothing = "-" * nothing
# takes prints and outp from the loop and gives it an increment and a
# newline if need be
def _next_line(prints, outp):
prints += 1
if prints > 4:
outp += "\n"
prints = 0
return prints, outp
# returns appropriate amount of space for length of given value
def _fill(value):
return " " * (len(_nothing) - len(str(value)))
# Split on bucket size and chaining strat
if self.bucket_size == 1 and self.collision != self.chaining:
for bucket in self.table:
if bucket == None:
outp += _nothing
else:
outp += _fill(bucket) + str(bucket)
outp += " "
prints, outp = _next_line(prints, outp)
# if we didn't use chaining and our bucket size > 1
elif self.bucket_size > 1 and self.collision != self.chaining:
for i in range(self.size):
outp += str(i) + _fill(i)
for elem in self.table[i]:
if elem is None:
outp += _nothing + " "
else:
outp += _fill(elem) + str(elem) + " "
outp += "\n"
# if we did use chaining
elif self.collision == self.chaining:
for bucket in self.table:
if bucket.value == None:
outp += _nothing
else:
outp += _fill(bucket.value) + str(bucket.value)
outp += " "
prints, outp = _next_line(prints, outp)
return outp |
ab863b68668454567fdc65f0da0aca8a15474b8e | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/gigasecond/181bd8c14d8e426db4b98959af77ed93.py | 2,991 | 3.65625 | 4 | #!/usr/bin/env python
from datetime import date
from math import *
def add_gigasecond(birthday):
bday = updateDate(birthday)
bday.setToNewYear()
return bday.incrementSecs(1000000000)
class updateDate:
def __init__(self, basedate):
self.basedate = basedate
self.year = basedate.year
self.month = basedate.month
self.day = basedate.day
self.secs = 0
def _isLeapYear(self, year):
if type(year) is not int:
print "Value provided is not an int."
raise ValueError
if not year % 4:
if (not(year % 100) and (year % 400)) :
return False
return True
return False
def setToNewYear(self):
self.secs = self.secs + (self.day - 1)*24*60*60
self.day = 1
for month in range(1,self.month):
if month == 2:
if self._isLeapYear(self.year):
self.secs = self.secs + 29*24*60*60
else:
self.secs = self.secs + 28*24*60*60
elif(((month < 8) and (month % 2)) or
((month > 8) and not (month % 2))):
self.secs = self.secs + 31*24*60*60
else:
self.secs = self.secs + 30*24*60*60
self.month = 1
def incrementSecs(self, secs):
if type(secs) is not int:
print "Value provided is not an int."
raise ValueError
self.secs = self.secs + secs
self._updateYear()
self._updateMonth()
self._updateDay()
return date(self.year, self.month, self.day)
def _updateYear(self):
while self._yearRemainder():
if self._isLeapYear(self.year):
self.secs = self.secs - 366*24*60*60
self.year = self.year + 1
else:
self.secs = self.secs - 365*24*60*60
self.year = self.year + 1
def _updateMonth(self):
for month in range(self.month, 13):
secs = 0
if month == 2:
if self._isLeapYear(self.year):
secs = 29*24*60*60
else:
secs = 28*24*60*60
elif(((month < 8) and (month % 2)) or
((month > 8) and not (month % 2))):
secs = 31*24*60*60
else:
secs = 30*24*60*60
if self.secs >= secs:
self.secs = self.secs - secs
else:
self.month = month
break
def _updateDay(self):
self.day = self.day + int(self.secs/(24*60*60))
def _yearRemainder(self):
if self._isLeapYear(self.year):
if self.secs >= 366*24*60*60:
return True
else:
return False
else:
if self.secs >= 365*24*60*60:
return True
else:
return False
|
b0693ca2020f4e30e9f0388739b8363374a492ea | Linjiayu6/LeetCode | /Algorithms/tree/EASY/590_N-ary Tree Postorder Traversal.py | 868 | 3.859375 | 4 | # https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
# For BST or BT, left -> right -> root
# For N-ary, children -> root
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def __init__(self):
self.L = []
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root is not None:
self.traverse(root)
return self.L
def traverse(self, node):
if node is not None:
for child in node.children:
self.traverse(child)
self.L.append(node.val) |
4513ff87de71790ef509b716ab2457c32241ac06 | nan0445/Leetcode-Python | /Power of Three.py | 250 | 3.8125 | 4 | class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0: return False
while n>1:
n, m = divmod(n, 3)
if m!=0: return False
return True
|
bce1abeae3549d5bf953d24b826f2151b9996b9d | Eldwitch/CSE | /Everett Garrison - Guess Game.py | 323 | 3.953125 | 4 | import random
random = (random.randint(1, 10))
for i in range(5):
guess = int(input("Guess a number, any number: "))
if guess < random:
print("Guess is too low.")
elif guess > random:
print("Guess is too high.")
elif guess == random:
print()
print("You win!")
break
|
a2d721cf8baa3f28ecd055ef4f515ba3bbbd445a | ggrecco/python | /basico/coursera/converte_segundos_em_horas_minutos_e_segundos.py | 289 | 3.84375 | 4 | segundos = int(input("Por favor, entre com o número de segundos que deseja converter: "))
horas = segundos // 3600
segundosRestantes = segundos % 3600
minutos = segundosRestantes // 60
resto = segundosRestantes % 60
print("{} horas, {} minutos, {} segundos.".format(horas,minutos,resto))
|
aa3fa4560cf8e7e57d1b2643cfcc68b04a22b9ab | Youga810/ProgrammingContest | /202/B.py | 181 | 3.8125 | 4 | s = input()
s2 = []
for elem in reversed(s):
if(elem == '6'):
print('9', end="")
elif(elem == '9'):
print('6', end="")
else:
print(elem, end="")
|
d6a02c55ff4ab382b723aeb2b3330909a282a7b1 | Sindhumeenakshi/guvi | /codekatta/letter or num.py | 221 | 3.75 | 4 | si=input()
letter_flag = False
number_flag = False
for b in si:
if b.isalpha():
letter_flag = True
if b.isdigit():
number_flag = True
if letter_flag and number_flag:
print('Yes')
else:
print('No')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.