blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
017df190a9e6ad31ef89fb5dc929f5c58551c2b7 | klq/euler_project | /euler5.py | 660 | 3.859375 | 4 | def least_common_multiple(numbers):
lcm = 1
for i in range(len(numbers)):
factor = numbers[i]
if factor != 1:
lcm = lcm * factor
for j in range(len(numbers)):
if numbers[j] % factor == 0 :
numbers[j] = numbers[j] / factor
return lcm
def euler5():
# Problem:
"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
# Solve:
return least_common_multiple(range(1,21)) #232792560
euler5() |
3b7fce6dfa1739f58a0a5a451f0dc8c14425ac9b | klq/euler_project | /euler20.py | 412 | 4.0625 | 4 | import math
def euler20():
"""
n! means n x (n - 1) x ... x 3 x 2 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
number = math.factorial(100)
sum_digits = sum( [int(d) for d in str(number)])
return sum_digits
print euler20()
|
c0bbbecf90a0e6128b03981b56a3c8a175f82a0b | klq/euler_project | /euler32.py | 1,272 | 3.796875 | 4 | def euler32():
"""
Pandigital products:
We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 x 186 = 7254,
containing multiplicand, multiplier,
and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product
identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
"""
pandigital_set = set('123456789')
products_set = set()
for m1 in range(1,2000):
for m2 in range(1,5000):
p = m1 * m2
totalstr = str(m1) + str(m2) + str(p)
if len(totalstr) == len(set(totalstr)) and set(totalstr) == pandigital_set:
print m1, m2, p
products_set.add(p)
return sum(products_set)
print euler32()
"""
4 1738 6952
4 1963 7852
12 483 5796
18 297 5346
27 198 5346
28 157 4396
39 186 7254
42 138 5796
48 159 7632
138 42 5796
157 28 4396
159 48 7632
186 39 7254
198 27 5346
297 18 5346
483 12 5796
1738 4 6952
1963 4 7852
45228
"""
|
78b2dadaa067264258ed93da5a4e13ebf692ec6a | klq/euler_project | /euler41.py | 2,391 | 4.25 | 4 | import itertools
import math
def is_prime(n):
"""returns True if n is a prime number"""
if n < 2:
return False
if n in [2,3]:
return True
if n % 2 == 0:
return False
for factor in range(3, int(math.sqrt(n))+1, 2):
if n % factor == 0:
return False
return True
def get_primes(maxi):
"""return a list of Booleans is_prime in which is_prime[i] is True if i is a prime number for every i <= maxi"""
is_prime = [True] * (maxi + 1)
is_prime[0] = False
is_prime[1] = False
# is_prime[2] = True and all other even numbers are not prime
for i in range(2,maxi+1):
if is_prime[i]: # if current is prime, set multiples to current not prime
for j in range(2*i, maxi+1, i):
is_prime[j] = False
return is_prime
def get_all_permutations(l):
# returns n-length iterable object, n = len(l)
# in lexical order (which means if input is [5,4,3,2,1], output will be in strictly decreasing order)
return itertools.permutations(l)
def list2num(l):
s = ''.join(map(str, l))
return int(s)
def get_sorted_pandigital(m):
"""returns a (reversed) sorted list of all pandigital numbers given m digits"""
perms = get_all_permutations(range(m,0,-1))
for perm in perms:
# per is a m-length tuple
perm = list2num(perm)
yield perm
def euler41():
"""https://projecteuler.net/problem=41
Pandigital Prime
What is the largest n-digit pandigital prime that exists?
"""
# Method 1: -----Turns out 1.1 itself is too costly
# 1. Get all the primes
# 2. Get all the pandigital numbers (sorted)
# 3. Test if prime from largest to smallest, stop when first one found
# is_prime = get_primes(987654321) taking too long
# Method 2: ----
# 1. Get all the pandigital numbers (sorted)
# 2. Test if prime from largest to smallest, stop when first one found
# !!! There will not be 8-digit or 9-digit pandigital prime numbers
# !!! Because they are all divisible by 3!
# !!! Only check 7-digit and 4-digit pandigital numbers
for m in [7,4]:
for pd in get_sorted_pandigital(m):
if is_prime(pd):
print pd
return
# Answer is:
# 7652413
def main():
euler41()
if __name__ == '__main__':
main() |
43e039d8f937cbdad0da0a04204611436eb10ba2 | jjfiv/mm2019 | /mm10534.py | 643 | 3.734375 | 4 |
import time
name=input("What's your name?\n")
time.sleep(1)
print("HELLO", name)
time.sleep(1)
print("I'm Anisha.")
time.sleep(1)
feel=input("How are you today?\n")
time.sleep(1)
print("Glad to hear you're feeling", feel, "today!")
time.sleep(1)
print("Anyway in a rush g2g nice meeting you!")
# import sys
# from typing import List
#
# # This is the main program:
# def main(args: List[str]):
#
# # loop through main arguments
# for arg in args:
# print("You said: {0}".format(arg))
#
# # or else print instructions
# if len(args) == 0:
# print("Try this script with arguments!")
#
# if __name__ == '__main__':
# main()
|
37c3dcf02898d3d6f510814948f0a4c4de72d2d9 | geekbaba/happy_python | /square.py | 345 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#类4边形
import turtle
colors=['red','blue','green','orange']
t=turtle.Pen()
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colors[x%4]) #设置画笔的颜色
t.width(x/100+1) #笔尖的宽度
t.forward(x) #笔向前移动多少
t.left(90) #笔的角度调整 90度 |
d838b971f537f51123defb0358633a9041fd2732 | Haribabu1433/gitpython | /test.py | 176 | 4.03125 | 4 | print("Hello World")
print("Hello from Hari")
list1 = [x*2 for x in [1,2,3]]
print(list1)
dict1 = {'x':1,'y':2}
print(dict1['x'])
set1 = set([1,2,3,4,4,3,2,4])
print(set1)
|
5ddf987c72fed9f1576ddd4fc236693c0cab0101 | hsnbskn/sqlite-python | /sqlAuthDemo.py | 1,069 | 3.515625 | 4 | #!/usr/bin/python3
import sqlite3
dbConnect = sqlite3.connect('userAuthData.db') #Veritabanina baglan.
dbCursor = dbConnect.cursor() #imlec olustur.
dbCursor.execute("""CREATE TABLE IF NOT EXISTS users (username,password)""") #Kullanici adi ve parola tutan bir tablo ekle.
datas = [('admin','123456'),('hasan','2021'),('haydar','hay123dar')] #Kullanici verileri olustur.
for data in datas:
dbCursor.execute("""INSERT INTO users VALUES %s"""%(data,)) #Kullanici verileri tek ogeli bir demet ile tabloya yerlestir.
dbConnect.commit() #Verileri veritabanina isle.
userName = raw_input("Username: ") #Kullanici adi giris
passWord = raw_input("Password: ") #Parola giris
dbCursor.execute("""SELECT * FROM users WHERE username = '%s' AND password = '%s'"""%(userName,passWord)) #Kullanici adi ve Parolayi Veritabanindan dogrula
dataFromDb = dbCursor.fetchone() #Bir tane veriyi al.
if dataFromDb:
print("Login Success, welcome {}".format(dataFromDb[0]))
else:
print("Access Denied !")
|
085357eaa91ec17fcad387c048b18b4858eb6c6b | schumanzhang/python | /pandas_demo.py | 1,068 | 3.953125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
#dataframe is like a python dictonary
web_stats = {'Day' : [1, 2, 3, 4, 5, 6],
'Visitors' : [34, 56, 34, 56, 23, 56],
'Bounce_Rate' : [65, 74, 23, 88, 93, 67]}
#how to convert above to a dataframe?
df = pd.DataFrame(web_stats)
#print(df)
#print first 5 rows
print(df.head())
#print the last 5 rows
print(df.tail())
#print the last 2 rows
print(df.tail(2))
#look at index, time series data, index should be Day
#the following returns a new dataframe, second line modifies the dataframe
df.set_index('Day')
df.set_index('Day', inplace=True)
print(df.head())
#reference a column
print(df['Visitors'])
print(df.Visitors)
#show two columns
print(df[['Bounce_Rate', 'Visitors']])
#convert a column to a list
print(df.Visitors.tolist())
#use numpy to convert to a numpy array
print(np.array(df[['Bounce_Rate', 'Visitors']]))
#create new dataframe
df2 = pd.DataFrame(np.array(df[['Bounce_Rate', 'Visitors']]))
print(df2) |
199e8640a08e85102ba40a418487ce262137ac22 | jkarwacki/Mosh-s-Python-course | /Examples and excercises/secret_number.py | 410 | 3.921875 | 4 | secretNumber = 9
noOfGuesses = 0
maxGuesses = 3
while noOfGuesses < maxGuesses:
guess = int(input('Guess: '))
noOfGuesses += 1
if guess == secretNumber:
print("You won!")
break
else: # else statement to the while loop; if the condition is not longer fulfilled
print("Sorry, you failed") # and no break was made, this code is run
|
9981ba51c093c04e7458a5ce0394d2736c6647e3 | bgagan911/Python_edX | /test.py | 545 | 4 | 4 | # [ ] review and run example
student_name = "Joana"
# get last letter
end_letter = student_name[-1]
print(student_name,"ends with", "'" + end_letter + "'")
# [ ] review and run example
# get second to last letter
second_last_letter = student_name[-2]
print(student_name,"has 2nd to last letter of", "'" + second_last_letter + "'")
# [ ] review and run example
# you can get to the same letter with index counting + or -
print("for", student_name)
print("index 3 =", "'" + student_name[3] + "'")
print("index -2 =","'" + student_name[-2] + "'")
|
f6ae082ababd05373fa7170573662f83c6686a00 | sososeng/DigitalCrafts_Exercises | /function_exercises/degree_conversion.py | 242 | 3.671875 | 4 | import matplotlib.pyplot as plot
import math
def f(x):
# put your code here
return x +1
c = int(input("Celsius? "))
xs = list(range(c, int(c *(9/5)+ 32)))
ys = []
for x in xs:
ys.append(f(x))
plot.plot(xs, ys)
plot.show()
|
55016de6c8eb6bfd69668f561b4686f0d23a9f9a | sososeng/DigitalCrafts_Exercises | /python_exercises_2/loop/multiplication_table.py | 89 | 3.578125 | 4 | for i in range(1,11):
for j in range(1,11):
print("{0} X {1} = {2}".format(i,j,(i*j))) |
0fbd1ecb479efa0ab654ae686d8ecc3acdab53b4 | sososeng/DigitalCrafts_Exercises | /python_exercises_2/list/matrix_addition.py | 196 | 4.03125 | 4 | one = [ [1, 3],
[2, 4]]
two = [ [5, 2],
[1, 0]]
three=[ [0,0],
[0,0]]
for i in range (0, len(one)):
for j in range(0,len(one)):
three [i][j] = (one[i][j] + two[i][j])
print(three) |
11e4e6ec3b1d406dc98967eebbe6f040e28a5704 | sososeng/DigitalCrafts_Exercises | /python_exercises_1/tip_calc.py | 374 | 3.84375 | 4 | bill = input("Total bill amount? ")
level = input("Level of service? ")
tip = 0.0
if(level == "good"):
tip = "{:.2f}".format(float(bill) * .20)
if(level == "fair"):
tip = "{:.2f}".format(float(bill) * .15)
if(level == "bad"):
tip = "{:.2f}".format(float(bill) * .1)
print ("Tip amount:", tip)
print ("Total bill amount: " , "{:.2f}".format(float(bill) + float(tip))) |
e6f4754b851d4f078593a7dc5c4976f0dd43b3be | A-ZHANG1/CS61ACS88 | /part1.py | 12,227 | 3.640625 | 4 | #CS61A,CS88
#Textbook from http://composingprograms.com/
"""
#######Local state,Recursion Text book#############################
"""
# def outer(f,x):
# def inner():
# return f(x)
# return inner
# g=outer(min,[5,6])
# print(g())
# def outer(f,x):
# return inner
# def inner():
# return f(x)
# g=outer(min,[5,6])
# print(g())
# def letters_generator():
# current='a'
# while current<='d':
# yield current
# current=chr(ord(current)+1)
#
# letters=letters_generator()
# type(letters)
#
# caps=map(lambda x:x.upper(),b_to_k)
# def cascade(n):
# """Print a cascade of prefixes of n."""
# print(n)
# if n >= 10:
# cascade(n//10)
# print(n)
#
# cascade(1234)
# def inverse_cascade(n):
# grow(n)
# print(n)
# shrink(n)
# def f_then_g(f,g,n):
# if n:
# f(n)
# g(n)
# grow=lambda n:f_then_g(grow,print,n//10)
# shrink=lambda n:f_then_g(print,shrink,n//10)
# def split(n):
# return n//10,n%10
# def sum_digits(n):
# if n<10:
# return n
# else:
# all_but_last,last=split(n)
# return sum_digits(all_but_last)+last
# def luhm_sum(n):
# if n<10:
# return n
# else:
# all_but_last,last=split(n)
# return luhm_sum_double(all_but_last)+last
# def luhm_sum_double(n):
# all_but_last,last=split(n)
# luhm_digit=luhm_sum(2*last)
# if n<10:
# return luhm_digit
# else:
# return luhm_sum(all_but_last)+luhm_digit
# print(luhm_sum(32))
# def partitions(n,m):
# if n==0:
# return Link(Link.empty)
# elif n<0 or m==0:
# return Link.empty
# else:
# using_m=partitions(n-m,m)
# with_m=map_link(lambda s:Link(s,m),using_m)
# without_m=partitions(n,m-1)
# return with_m+without_m
# def reduce(reduce_fn,s,initial):#!!
# reduced=initial
# for x in s:
# redudced=reduce_fn(redudced,x)
# return reduced
# reduce(mul,[2,4,8],1)
"""
####2.3 tree from textbook#################################
"""
# def tree(root,branches=[]):#!!
# for branch in branches:
# assert is_tree(branch),'Branch must be a tree.'
# return [root]+list(branches)
# def root(tree):
# return tree[0]
# def branches(tree):
# return tree[1:]
# def is_tree(t):#!!
# if type(t) is not list or len(t)<0:
# return False
# for branch in branches(t):
# if not is_tree(branch):
# return False
# return True
# def is_leaf(tree):
# return not branches(tree)
# ####general parts for tree implementation ends#
# ####specific functioning functions begins######
# # def fib_tree(n):#!!
# # if n==0 or n==1:
# # return tree(n)
# # else:
# # left,right=fib_tree(n-1),fib_tree(n-2)
# # fib_n= root(left)+root(right)
# # return tree(fib_n,[left,right])
# # print(fib_tree(5))#!!
# #
# # def partition_tree(n,m):
# # if n==0:
# # return tree(True)#!!
# # if n<0 or m==0:
# # return tree(False)#!!
# # left=partition_tree(n-m,m)
# # right=partition_tree(n,m-1)
# # return tree(m,[left,right])#!!
# # def print_parts(tree,partition=[]):
# # if is_leaf(tree):#
# # #if root(tree):#??
# # print('+'.join(partition))#a string
# # #method takes a list of things to join with the string.
# # else:
# # left,right=branches(tree)
# # m=str(root(tree))
# # print_parts(left,partition+[m])
# # print_parts(right,partition)
# # print_parts(partition_tree(6,4))
# #
# # def right_binarize(tree):
# # if is_leaf(tree):
# # return tree
# # if len(tree)>2:
# # tree=[tree[0],tree[1:]]
# # return [right_binarize(b) for b in tree]
# # print(right_binarize([1,2,3,4,5,6,7]))
# ###2.3 tree####################################
"""
# ##hw5 tree#####################################
"""
# def print_tree(t,indent=0):
# print(' '*indent+str(root(t)))
# for branch in branches(t):
# print_tree(branch,indent+1)
# print_tree(tree(1,[tree(2)]))
#
# def make_pytunes(username):
# return tree(username,[tree('pop',[tree('justinbieber',[tree('single',[tree('what do you mean?')])]),tree('105 pop mashup')]),
# tree('trace',[tree('darude',[tree('sandstorm')])])])
# print_tree(make_pytunes('I love music'))
#
# def num_leaves(t):
# if is_leaf(t):
# return 1
# else:
# #return 1+num_leaves(branches(t))??
# return sum([num_leaves(branch) for branch in branches(t)])
# print(num_leaves(make_pytunes('music')))
#
# def num_leaves_2(t):
# if is_leaf(t):
# return 1
# else:
# leaves=0
# for b in branches(t):
# leaves+=num_leaves_2(b)
# return leaves
# print(num_leaves_2(make_pytunes('music')))
#
# ###crtl+F#######################
# def find(t,target):
# if root(t)==target:
# return True
# else:
# return any([find(branch,target) for branch in branches(t)])#
# def find_2(t,target):
# if root(t)==target:
# return True
# else:
# for branch in branches(t):
# if find(branch,target):
# return True
# return False
# my_account = tree('kpop_king',
# [tree('korean',
# [tree('gangnam style'),
# tree('wedding dress')]),
# tree('pop',
# [tree('t-swift',
# [tree('blank space')]),
# tree('uptown funk'),
# tree('see you again')])])
# print(find(my_account, 'bad blood'))
#
# ###add to tree#################
# def add_song(t,song,category):
# if root(t)==category:
# return tree(category,branches(t)+[tree(song)])
# else:
# #for b in branches(t):
# #all_branches=add_song(b,song,category)
# #link! jianya!
# return tree(root(t),[add_song(b,song,category) for b in branches(t)])
# ##test#######################
# indie_tunes = tree('indie_tunes',
# [tree('indie',
# [tree('vance joy',
# [tree('riptide')])])])
# new_indie = add_song(indie_tunes, 'georgia', 'vance joy')
# print_tree(new_indie)
#
# ####delete###################
# def delete(t, target):
# kept_branches=[b for b in branches(t) if root(b)!=target]
# return tree(root(t),kept_branches)
# ######test##################
# my_account = tree('kpop_king',[tree('korean',[tree('gangnam style'),tree('wedding dress')]),tree('pop',[tree('t-swift',[tree('blank space')]),tree('uptown funk'),tree('see you again')])])
# new = delete(my_account, 'pop')
# print_tree(new)
"""
# ###mutable#################
"""
# #not passing test because nonloca not available in python 2.x#
# def make_withdraw(balance, password):
# attempt=[]#!!
# def withdraw(amount,p):
# nonlocal balance#!!
# for i in range(3):
# if p!=password:
# attempt+=[p]
# else:
# break;
# if i==3:
# return "Your account is locked. Attempts: "+str(attempt)
# if amount > d['y']:
# return 'Insufficient funds'
# d['y'] = d['y'] - amount
# print(d['y'])
# return withdraw
# ##
#
# def make_joint(withdraw, old_password, new_password):
# error = withdraw(0,old_passord)
# if type(error)==str:#nice way to decide whether return value is a 'insufficient funds'or valid amount
# return error
# def joint(amount,password_attempt):#READ the question
# if password_attempt==new_password:
# return withdraw(amount,old_passord)
# return withdraw(amount,password_attempt)
# return joint
"""
##dispatch dictionary################################
"""
#abstract data type : account
# def account(initial_balance):#constructor
# def deposit(amount):
# dispatch['balance'] += amount
# return dispatch['balance']
# def withdraw(amount):
# if amount > dispatch['balance']:
# return 'Insufficient funds'
# dispatch['balance'] -= amount
# return dispatch['balance']
# dispatch = {'deposit': deposit, #store the local state of account
# 'withdraw': withdraw,
# 'balance': initial_balance}
# # message : number or functions
# #functions here have access to the dispatch library
# #thus can read or write balance
# return dispatch
#
# def withdraw(account, amount):#function to withdraw
# return account['withdraw'](amount)
# def deposit(account, amount):#function to withdraw
# return account['deposit'](amount)
# def check_balance(account):#selector
# return account['balance']
#####test##########################
# a = account(20)
# deposit(a, 5)
# withdraw(a, 17)
# print(check_balance(a))
"""
##########text book 2.3.7 linked list########################
"""
###initialization#############
# empty='empty'
# def is_link(s):
# return s is empty or len(s)==2 and is_link(s[1])
# def link(first,rest):
# assert is_link(rest)
# return [first,rest]
# def first(s):
# assert is_link(s)
# assert s!=empty
# return s[0]
# def rest(s):
# assert is_link(s)
# assert s!=empty
# return s[1]
# four=link(1,link(2,link(3,link(4,empty))))
# print(is_link(four))
# print(rest(four))
# print(first(four))
###functions######################
# def len_link_recursive(s):#don't use the name 'len' for it's internally defined
# if s is empty:
# return 0
# return len_link(rest(s))+1
# def len_link_using_built_in_len(s):
# return 1+len(rest(S))
# def len_link_loop(s):
# return 1+len(rest(s))
# length=0
# while s is not empty:
# s=rest(s)
# length+=1
# return length
# print(len_link_loop(four))
# def getitem_link(s,i):
# while i !=1:
# s,i=rest(s),i-1
# return first#not s[0] (abstraction barrier)
# print(getitem_link(four,2))
# def extend_link(s,t):
# assert is_link(s),is_link(t)
# if s==empty:
# return t
# else:
# return link(first(s),extend_link(rest(s),t))#cotect form for recursion
# print(extend_link(four,link(5,'empty')))
# import math
# def apply_to_all_link(f,s):
# assert is_link(s)
# if s==empty:
# return s
# else:
# return link(f(first(s)),apply_to_all_link(f,rest(s)))#same as above
# print(apply_to_all_link(math.sqrt, four))
# def keep_if_link(f, s):
# assert is_link(s)
# if s==empty:
# return s
# else:
# kept=keep_if_link(f,rest(s))
# if f(first(s)):#create a linked list with recursion
# return link(first(s),kept)
# else:
# return kept
# print(keep_if_link(lambda x:x%2, four))
# def join_link(s, separator):
# assert is_link(s)
# if s==empty:
# return ""
# if rest(s)==empty:
# return str(first(s))
# else:
# return str(first(s))+str(separator)+join_link(rest(s),separator)
# print(join_link(four,","))
###OOP Textbook 2.5 2.6 2.9###########################################
# def make_instance(cls):
# def get_value(name):
# if name i attributes:
# return attributes[name]
# else:
# value = cls['get'](name)#??
# return bind_method(value,instance)
# def set_value(name,value):
# attributes[name]=value
# attributes={}
# instance={'get':get_}
#haven't finished this sample code
####################################################################
|
492736dac8fb52067c21b4561ba9731337f8b84c | merveky/BASKENT-TBY414-Bahar2020 | /3 Mart 2020/beden kutle indeksi.py | 1,244 | 3.84375 | 4 | # Beden kütle indeksi - Sağlık göstergesi hesaplama
# TBY414 03.03.2020
# ADIM 1 - Kullanıcı girdilerinden indeksi hesaplamak
# ağırlık (kg) boy (metre) olacak şekilde bki = a/(b*b)
agirlik = float( input("Lütfen ağırlığınızı giriniz (kg): ") )
# ^ bir sayı olması gereken bir girdi alıyoruz.
boy = float( input("Lütfen boyunuzu giriniz (cm):") )
boy = boy / 100.0 # metreye çevirdik
bki = agirlik / (boy * boy)
print("BKİ değeri: ", bki)
# ADIM 2 - Kullanıcının sınıflandırmasını yapmak
# <18.5 <25 <30 <35 <40 --
# zayıf sağlıklı az kilolu 1. obez 2. obez 3. obez
if bki <18.5:
print("Zayıfsınız")
print("Sağlıklı biçimde kilo alabilirsiniz")
if boy<1.40:
# Belki de çocuk?
print("Çocuklar için BKİ formülü farklıdır.")
elif bki < 25:
print("Sağlıklısınız")
elif bki <30:
print("Az kilolusunuz")
elif bki<35:
print("Dikkat! 1. Obez")
elif bki<40:
print("Dikkat! 2. Obez")
else:
print("Dikkat 3. Obez")
# ADIM 3 - Bir kilo alma/verme hedefi oluşturmak
# Bu aynı zamanda ikinci ödevin bir parçası.
# Not: Birinci ödev github hesabı açamak idi.
|
9c030cd12cc6af8ecde57f52ed0063e5acc4bf5e | artraya/scrapeDB | /Template Scripts/FlixmetricScrape.py | 2,205 | 3.625 | 4 | import requests
import http.client
from bs4 import BeautifulSoup
MetaUrl = 'https://flickmetrix.com/watchlist'
MetaHeaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
# result = requests.get(MetaUrl, headers=MetaHeaders)
with open("Flick.html", "r") as f: #open the HTML file
contents = f.read()
html_soup = BeautifulSoup(contents, 'html.parser') #parse the contents of the html file that we've opened
type(html_soup) #have no idea what this does
movie_title, movie_date = html_soup.find_all('div', class_ = 'title ng-binding'), html_soup.find_all('div', class_ = 'film-section ng-binding') #double variable control
for i, j in zip(movie_title[::2], movie_date[::3]): # [::2] and [::3] iterates over every 2nd and 3rd element in each list respectively.
title = i.text
title = title.replace(" ", "+")
title = title.replace(":", "%3A") #URL encoding for each title for a later POST request
date = j.text #storing movie date into a variable for accurate search results
date = date.replace("(", "")
date = date.replace(")", "")
#print(title, date)
url = "https://api.themoviedb.org/3/search/movie?api_key=2b5c62f4ed3da916c3b4c6ca47003e46&language=en-US&page=1&include_adult=false&query={}&year={}".format(
title, date)
payload = "{}"
response = requests.request("GET", url, data=payload)
results = response.json()
#print(results)
if results["results"] and results["results"][0]["release_date"][:4] == date:
movie_id = results["results"][0]["id"]
conn = http.client.HTTPSConnection("api.themoviedb.org")
payload = "{\"media_id\":%s}" % movie_id
headers = {'content-type': "application/json;charset=utf-8"}
conn.request("POST",
"/3/list/127145/add_item?api_key=2b5c62f4ed3da916c3b4c6ca47003e46&session_id=9ef3454015fb183f7611e6e510ff77bb52db2b74",
payload, headers)
res = conn.getresponse()
data = res.read()
print(data)
print("added:", title, date, "to your list")
else:
print(title, "was not added to your list because your code is crap!")
|
684ed7e9ab5c2bce663e47c8791f4e23465dd0c6 | Romihime/Algo3.2.tp1 | /aed3-tp3-master/cargar.py | 1,242 | 3.875 | 4 | #!/usr/bin/python
import sys
def leer_datos(path):
xs = []
ys = []
ds = []
with open(path, 'r') as f:
#Ignoro las primeras 3 lineas
nombre_archivo_salida = str(f.readline().split()[2])
nombre_archivo_salida = nombre_archivo_salida + ".in"
for i in range(2):
f.readline()
#Leo la cantidad de nodos
line = f.readline()
p, s, t = line.split()
n = int(t)
#print(n)
#Ignoro la siguiente linea y leo la capacidad de los camiones
f.readline()
line = f.readline()
p, s, t = line.split()
c = int(t)
#print(c)
#Ignoro la siguiente linea y por cada id y coordenada voy guardando
f.readline()
for i in range(n):
line = f.readline()
_id, x, y = line.split()
xs.append(x)
ys.append(y)
#Ignoro la siguiente linea y guardo la demanda segun cada id
f.readline()
for i in range(n):
line = f.readline()
_id, d = line.split()
ds.append(d)
#print(ds)
with open(nombre_archivo_salida, 'w') as f2:
f2.write('{} {}\n'.format(n, c))
for i in range(n):
f2.write('{} {} {}\n'.format(xs[i], ys[i], ds[i]))
return 0
def main():
nombre_archivo = sys.argv[1] #tomamos el nombre dle archivo
datos = leer_datos( nombre_archivo )
if __name__ == '__main__':
main()
|
7f311d686d93dd4894dfac265c66eea3e8ae7f38 | senzuo/tryleetcode | /leetcode5Bruce.py | 1,747 | 3.90625 | 4 | # 自己写的暴力求解
def longestPalindrome(s):
"""
:type s: str
:rtype: str
"""
imax = len(s)
longest = s[0]
for k in range(imax - 1):
# 两种情况考虑 1. xxxaaxxx 2.xxaxx
# 但是 xxxaaaxxx GG
# 只能乖乖都执行了……
if s[k] == s[k + 1]:
i, j = k, k + 1
# while i > 0 and j < imax - 1 and s[i - 1] == s[j + 1]:
# i -= 1
# j += 1
# if j - i + 1 > len(longest):
# longest = s[i: j + 1]
else:
i, j = k, k
while i > 0 and j < imax - 1 and s[i - 1] == s[j + 1]:
i -= 1
j += 1
if j - i + 1 > len(longest):
longest = s[i: j + 1]
return longest
# print(longestPalindrome('cbbd'))
# print(longestPalindrome('babad'))
# print(longestPalindrome('a'))
# print(longestPalindrome('bbb'))
# print('Wrong!')
# 人家的暴力求解
def longestPalindromeBruteForce(s):
"""
:type s: str
:rtype: str
"""
ans, pal_str = 0, ''
for i in range(len(s)):
for j in range(i, len(s)):
print(s[i:j + 1])
if s[i:j + 1] == s[i:j + 1][::-1]:
length = j - i + 1
if length > ans:
ans = length
pal_str = s[i:j + 1]
return pal_str
# print(longestPalindromeBruteForce('cbbd'))
print(longestPalindromeBruteForce('babad'))
# print(longestPalindromeBruteForce('a'))
# print(longestPalindromeBruteForce('bb'))
### 对比
# 出发点不同,自己的函数从每个点向两边拓展,别人的是检查每个字串是否是回文
# 自己函数效率稍微高一些,别人的函数代码简洁一些
|
969dcb391cd130eb1f02357eac75c53c0c4427ac | wonnacry/hw | /task_generator_password.py | 164 | 3.5 | 4 | import random
import string
def password_generator(n):
while 1:
a = []
for i in range(n):
a.append(random.choice(string.ascii_letters))
yield ''.join(a)
|
ba0392de63e38ed23e776be5de7c09ed61510360 | JinnieJJ/leetcode | /67-Add Binary.py | 571 | 3.5 | 4 | class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = ""
value = 0
carry = 0
if len(a) < len(b):
return self.addBinary(b, a)
for i in range(len(a)):
val = carry
val += int(a[-(i + 1)])
if i < len(b):
val += int(b[-(i + 1)])
carry, val = int(val/2), val % 2
result += str(val)
if carry:
result += str(carry)
return result[::-1]
|
a6fe9e17e19a70fc6b383af53ccbe645469a7a39 | JinnieJJ/leetcode | /430-Flatten a Multilevel Doubly Linked List.py | 944 | 3.84375 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
curr, stack = head, []
while curr:
if curr.child:
# If the current node is a parent
if curr.next:
# Save the current node's old next pointer for future reattachment
stack.append(curr.next)
curr.next, curr.child.prev, curr.child = curr.child, curr, None
if not curr.next and len(stack):
# If the current node is a child without a next pointer
temp = stack.pop()
temp.prev, curr.next = curr, temp
curr = curr.next
return head
|
363aed625a6b0236330372b0355d6d3c4a032020 | JinnieJJ/leetcode | /437-Path Sum III.py | 698 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def pathSum(self, root, target):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
res = 0
queue = deque([(root, [])])
while queue:
node, prev = queue.popleft()
if node:
tmp = [node.val + p for p in prev] + [node.val]
res += sum([v == target for v in tmp])
queue.extend([(node.left, tmp), (node.right, tmp)])
return res
|
862bf3f795351c97753078b73cd9992b89b24d50 | JinnieJJ/leetcode | /680-Valid Palindrome II.py | 467 | 3.515625 | 4 | class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left = 0
right = len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return s[left+1:right+1] == s[left+1:right+1][::-1] or s[left:right] == s[left:right][::-1]
#[::-1]要分开写
return True
|
c7b2c1ef58c980fa43b866a1c81ab6c5e79069bc | JinnieJJ/leetcode | /269-Alien Dictionary.py | 1,768 | 3.78125 | 4 | from collections import deque
class Solution:
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
self.visited = {}
self.graph = {}
self.results = deque()
characters = set()
for word in words:
for char in word:
self.visited[char] = 0
self.graph[char] = []
characters.add(char)
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i+1]
success = self.addEdge(word1, word2)
if not success:
return ""
for char in characters:
success = self.topologicalSort(char)
if not success:
return ""
return "".join(list(self.results))
def topologicalSort(self, char):
if self.visited[char] == -1: # detected cycle
return False
if self.visited[char] == 1: #char has been visited and completed topological sort on
return True
self.visited[char] = -1
for neigh in self.graph[char]:
success = self.topologicalSort(neigh)
if not success:
return False
self.visited[char] = 1
self.results.appendleft(char)
return True
def _addEdge(self, var1, var2):
self.graph[var1].append(var2)
def addEdge(self, word1, word2):
for char1, char2 in zip(word1, word2):
if char1 != char2:
self._addEdge(char1, char2)
return True
if len(word1) > len(word2):
return False
return True
|
741b914a0720c6637a7c7a39b6e744e6ec873fd3 | JinnieJJ/leetcode | /298-Binary Tree Longest Consecutive Sequence.py | 956 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
stack = [(root, 1)]
maxlen = 1
while stack:
e = stack.pop()
if e[0].left:
if e[0].left.val == e[0].val + 1:
stack.append((e[0].left, e[1]+1))
maxlen = max(maxlen, e[1]+1)
else:
stack.append((e[0].left, 1))
if e[0].right:
if e[0].right.val == e[0].val + 1:
stack.append((e[0].right, e[1]+1))
maxlen = max(maxlen, e[1]+1)
else:
stack.append((e[0].right, 1))
return maxlen
|
40ace747a74a8261a90b44a01292e40a9ff56877 | Rakeshgsekhar/DataStructure | /QCodes/swapNodesInPair.py | 492 | 3.5625 | 4 | class Solution:
def swapPairs(self, head: ListNode):
if head is None or head.next is None:
return head
tempx = ListNode(0)
tempx.next = head
temp2 = tempx
while tempx.next is not None and tempx.next.next is not None:
first = tempx.next
sec = tempx.next.next
tempx.next = sec
first.next = sec.next
sec.next = first
tempx = tempx.next.next
return temp2.next |
2b92afe371f111e0353ac1276c33d79a17f2c6e1 | Rakeshgsekhar/DataStructure | /QCodes/printMiddleNodeofList.py | 628 | 3.75 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
def printMiddleElement(head):
temp = head
temp1 = head
if temp is None:
print ('No Elements Found')
count = 0
while temp is not None:
count += 1
temp = temp.next
mid = count//2 + 1
for i in range(1,mid):
temp1 = temp1.next
print(temp1.data)
l1 = Node(1)
l2 = Node(2)
l3 = Node(3)
l4 = Node(4)
l5 = Node(5)
l6 = Node(6)
l7 = Node(7)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
l5.next = l6
l6.next = l7
head = None
head = l1
printMiddleElement(head)
|
ea7bccb74b723915301aa7328f7c1baaeadaffa1 | Nesters/python-workshop | /intro/solutions/animals/cat.py | 169 | 3.5 | 4 | from animals.animal import Animal
class Cat(Animal):
def __init__(self, name):
super(Animal,self).__init__()
def meow(self):
print('meow') |
734c2933e3fc24ecb3efc7ca1e468d5264d53ea3 | hrldcpr/cryptopals | /set2/challenge9.py | 418 | 3.765625 | 4 |
import utilities
def pad(text, n):
m = n - len(text)
return text + bytes([m] * m)
def unpad(text, n):
if text:
m = text[-1]
if m < n and text.endswith(bytes([m] * m)):
return text[:-m]
return text
@utilities.main
def main():
x = b'YELLOW SUBMARINE'
y = pad(x, 20)
assert y == b'YELLOW SUBMARINE\x04\x04\x04\x04'
assert unpad(y, 20) == x
print(y)
|
c18a67801410dab787e4cbe3e2915074a040377e | lidannili/IIPP-Part1 | /stopwatch.py | 1,992 | 3.59375 | 4 | # template for "Stopwatch: The Game"
import simplegui
# define global variables
width = 150
height = 150
interval=100
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
# t is in 0.1 seconds
# A:BC.D
A=0
B=0
C=0
D=0
win = 0
trial = 0
#time = str(A) + ":" + str(B)+str(C) + "." + str(D)
def format(t):
global A
global B
global C
global D
if t< 600:
B= (t-600*(t/600) )/100
C= ((t-600*(t/600) )%100-(t-600*(t/600) )%10)/10
D= (t-600*(t/600) )%10
return str(A) + ":" + str(B)+str(C) + "." + str(D)
else:
A = A+t/600
B= (t-600*(t/600) )/100
C= ((t-600*(t/600) )%100-(t-600*(t/600) )%10)/10
D= (t-600*(t/600) )%10
return str(A) + ":" + str(B)+str(C) + "." + str(D)
# define event handlers for buttons; "Start", "Stop", "Reset"
def Start():
global trial
if not timer.is_running():
trial = trial + 1
timer.start()
def Stop():
global win
if timer.is_running() and D==0:
win = win + 1
timer.stop()
def Reset():
global time
global win
global trial
timer.stop()
time = 0
win = 0
trial = 0
# define event handler for timer with 0.1 sec interval
time = 0
def timer_handler():
global time
time=time+1
# define draw handler
def draw(canvas):
canvas.draw_text(format(time), [80,150], 60, "White")
canvas.draw_text("player :"+ str(win) + "/" + str(trial),[200,50],20,"Red")
# create frame
frame = simplegui.create_frame("Home", 300, 300)
timer = simplegui.create_timer(interval,timer_handler)
# register event handlers
frame.set_draw_handler(draw)
frame.add_button("Start", Start, 100)
frame.add_button("Stop", Stop, 100)
frame.add_button("Reset", Reset, 100)
# start frame
frame.start()
# Please remember to review the grading rubric
|
a084d4b1a3a99cd2b6dcfc996af18aa6514245f1 | QaisZainon/Learning-Coding | /Automate the Boring Stuff/Ch.13 - Working with Excel Spreadsheets/TextFilestoSpreadsheet.py | 952 | 3.96875 | 4 | #! python3
# Reads text files, put them into lists and then input into an excel file
import openpyxl, os
def TextToExcel(folder):
wb = openpyxl.Workbook()
sheet = wb.active
num_column = 0
# Going through the file
for foldername, subfolders, filenames in os.walk(folder):
for fl_int in range(len(filenames)):
filename = list(filenames)
file_ = open(foldername + '\\' + filename[fl_int],'r')
# Acquiring the text form .txt
text_ = file_.readlines()
text_ = text_[0].split(' ')
for num_row in range(len(text_)):
sheet.cell(row = num_row + 1, column = num_column + 1).value = text_[num_row]
print(text_[num_row])
num_column += 1
wb.save('TextToExcel.xlsx')
TextToExcel(r'C:\Users\Dr. Wan Asna\Desktop\Python Projects\Automate the Boring Stuff\Ch.13 - Working with Excel Spreadsheets\num') |
cb24203b039fe1ad617c34c1c14b920c8ca3a8fc | QaisZainon/Learning-Coding | /Statistics for Financial Analysis/Week 3/Population&Sample.py | 1,219 | 4.03125 | 4 | import pandas as pd
import numpy as np
#Create a Population DataFrame with 10 data
data = pd.DataFrame()
data['Population'] = [47, 48, 85, 20, 19, 13, 72, 16, 50, 60]
#Draw sample with replacement, size=5 from Population
a_sample_with_replacement = data['Population'].sample(5, replace=True)
print(a_sample_with_replacement)
a_sample_without_replacement = data['Population'].sample(5, replace=False)
print(a_sample_without_replacement)
#Calculate mean and variance
population_mean = data['Population'].mean()
population_var = data['Population'].var(ddof=0)
print('Population mean is', population_mean)
print('Population variance is', population_var)
#Calculate sample mean and sample standard deviation, size=10
#You will get different mean and variance every time when yuo execute the below code
a_sample = data['Population'].sample(10, replace=True)
sample_mean = a_sample.mean()
sample_var = a_sample.var()
print('Sample mean is ', sample_mean)
print('Sample variance is ', sample_var)
#Average of an unbiased estimator
sample_length = 500
sample_variance_collection =[data['Population'].sample(10, replace=True).var(ddof=1) for i in range(sample_length)]
print(sample_variance_collection) |
0f8ded0901ca84c9b277aaba67b9578f799d75de | QaisZainon/Learning-Coding | /Practice Python/Exercise_24.py | 249 | 3.890625 | 4 | #Returns a board based on user input
def board(width, height):
top_bot = ' ---'
vertical = '| '
for i in range(height):
print(top_bot*(width))
print(vertical*(width + 1))
print(top_bot*(width))
board(3, 3) |
e077c341cf3f4dc0825b712a24ffd1ad2378dac0 | QaisZainon/Learning-Coding | /Practice Python/Exercise_31.py | 482 | 4.03125 | 4 | # make a hangman game?-ish
random_word = 'BALLISTOSPORES'
def hangman():
print('Welcome to Hangman!')
missing = ['_ ' for i in range(len(random_word))]
while '_ ' in missing:
print(''.join(missing))
guess = input('Guess your letter: ').upper()
# word checker and updater
for i in range(len(random_word)):
if random_word[i] == guess:
missing[i] = guess + ' '
print(''.join(missing))
hangman() |
1ba8cda2d2376bd93a169031caa473825b3912da | QaisZainon/Learning-Coding | /Practice Python/Exercise_02.py | 795 | 4.375 | 4 | '''
Ask the user for a number
Check for even or odd
Print out a message for the user
Extras:
1. If number is a multiple of 4, print a different message.
2. Ask the users for two numbers, check if it is divisible, then
print message according to the answer.
'''
def even_odd():
num = int(input('Enter a number\n'))
if num % 4 == 0:
print('This number is divisible by 4')
if num % 2 == 0:
print('This is an even number')
elif num % 2 == 1:
print('This is an odd number')
print('Give me two numbers,the first to check and the second to divide')
check = int(input('Check number'))
divide = int(input('Divider'))
if num / divide == check:
print('Correct!')
else:
print('Incorrect!')
even_odd()
|
297253a153c50c6a2c4c64a1242584fe98801ae7 | QaisZainon/Learning-Coding | /Automate the Boring Stuff/Ch.10 - Organizing Files/DeletingUnneededFiles.py | 561 | 3.59375 | 4 |
from pathlib import Path
import os
p = Path.cwd()
#Walk through a folder tree
for foldername, subfolders, filename in os.walk(p):
print(f'checking folders {foldername}...')
for filenames in filename:
try:
#searches for large files, > 100MB
size = os.path.getsize(os.path.join(foldername,filenames))
print(size)
if size >= 1*10**8:
#Print these files on the screen
print(f'The size of {filenames} is {size}.')
except:
continue
|
3ce261f1cc1721461582343902df008991a61382 | Rain-Sun/ABCA | /ABCA_topK.py | 13,643 | 3.984375 | 4 | """ A Python Class
A simple Python graph class, demonstrating the essential
facts and functionalities of graphs.
"""
#import queue
import math
from random import choice
#import copy
import sys
import time
from collections import deque
#from numba import jit
class Graph(object):
def __init__(self, graph_dict=None):
""" initializes a graph object
If no dictionary or None is given,
an empty dictionary will be used
"""
if graph_dict == None:
graph_dict = {}
self.__graph_dict = graph_dict
def self_dict(self):
return self.__graph_dict
def bfs_dict(self):
return self.__bfs_dict
def vertices(self):
""" returns the vertices of a graph """
return list(self.__graph_dict.keys())
def edges(self):
""" returns the edges of a graph """
return self.__generate_edges()
def num_vertices(self):
""" returns the number of vertices of a graph """
return len(self.__graph_dict.keys())
def num_edges(self):
""" returns the number of edges of a graph """
return len(self.__generate_edges())
def add_vertex(self, vertex):
""" If the vertex "vertex" is not in
self.__graph_dict, a key "vertex" with an empty
list as a value is added to the dictionary.
Otherwise nothing has to be done.
"""
if vertex not in self.__graph_dict:
self.__graph_dict[vertex] = {}
def delete_vertex(self,vertex):
if vertex not in self.__graph_dict.keys():
print("The vertex is not in the graph")
else:
for node in self.__graph_dict[vertex]:
self.__graph_dict[node].remove(vertex)
self.__graph_dict.pop(vertex)
def add_edge(self, edge):
""" assumes that edge is of type set, tuple or list;
between two vertices can be multiple edges!
"""
edge = set(edge)
(vertex1, vertex2) = tuple(edge)
if vertex1 in self.__graph_dict.keys() and vertex2 in self.__graph_dict.keys():
if vertex2 in self.__graph_dict[vertex1] and vertex1 in self.__graph_dict[vertex2]:
return
self.__graph_dict[vertex1].add(vertex2)
self.__graph_dict[vertex2].add(vertex1)
elif vertex1 not in self.__graph_dict.keys() and vertex2 in self.__graph_dict.keys():
self.__graph_dict[vertex1] = {vertex2}
self.__graph_dict[vertex2].add(vertex1)
elif vertex1 in self.__graph_dict.keys() and vertex2 not in self.__graph_dict.keys():
self.__graph_dict[vertex2] = {vertex1}
self.__graph_dict[vertex1].add(vertex2)
else:
self.__graph_dict[vertex1] = {vertex2}
self.__graph_dict[vertex2] = {vertex1}
def delete_edge(self, edge):
edge = set(edge)
(vertex1, vertex2) = tuple(edge)
if vertex1 in self.__graph_dict.keys() and vertex2 in self.__graph_dict[vertex1]:
self.__graph_dict[vertex1].remove(vertex2)
#if vertex2 in self.__graph_dict.keys() and vertex1 in self.__graph_dict[vertex2]:
self.__graph_dict[vertex2].remove(vertex1)
else:
print("This edge is not in the graph.")
def __generate_edges(self):
""" A static method generating the edges of the
graph "graph". Edges are represented as sets
with one (a loop back to the vertex) or two
vertices
"""
edges = []
for vertex in self.__graph_dict:
for neighbor in self.__graph_dict[vertex]:
if {neighbor, vertex} not in edges:
edges.append({vertex, neighbor})
return edges
# the bfs_dict need to be renewed every time the node changed in graph
def bfs(self, vertex_s):
"""
use bfs explore graph from a single vertex
return a shortest path tree from that vertex
"""
nd_list = list(self.vertices())
visited = dict((node, 0) for node in nd_list)
nq = deque()
pre_dict, dist = {}, {}
nq.append(vertex_s)
visited[vertex_s]=1
dist[vertex_s] = 0
loop_counts = 0
while nq:
s = nq.popleft()
for node in self.__graph_dict[s]: # for each child/neighbour of current node 's'
loop_counts += 1
#if not node in visited:
if not visited[node]:
nq.append(node) # let 'node' in queue
pre_dict[node] = [s] # the 'parent' (in terms of shortest path from 'root') of 'node' is 's'
dist[node] = dist[s] + 1 # shortest path to 'root'
visited[node]=1 # 'node' is visted
#if node in visited and dist[node] == dist[s] + 1: # still within the shortest path
if visited[node] and dist[node] == dist[s] + 1: # still within the shortest path
if s not in pre_dict[node]: # if this path have NOT been recorded, let's do that now
pre_dict[node].append(s)
if visited[node] and dist[node] > dist[s] + 1: # the previous 'recorded' path is longer than our current path (via node 's'); let's update that path and distance
pre_dict[node] = [s]
dist[node] = dist[s] + 1
#print(" #loops: %d" %loop_counts)
#current_bfs[vertex_s] = pre_dict
return pre_dict
def read_edgelist(self, file):
f = open(file, 'r')
while True:
line = f.readline()
if not line:
break
v1, v2 = line.strip().split()
if v1 != v2: # no self loop
self.add_edge({v1,v2})
def is_connect(self, s, t):
#current_bfs = dict()
pre_map = self.bfs(s)
if t in pre_map:
return [True, pre_map]
return[False, pre_map]
def __str__(self):
res = "vertices: "
for k in self.__graph_dict:
res += str(k) + " "
res += "\nedges: "
for edge in self.__generate_edges():
res += str(edge) + " "
return res
class Node(object):
"""Generic tree."""
def __init__(self, name='', children=None):
self.name = name
if children is None:
children = []
self.children = children
def add_child(self, child):
self.children.append(child)
####not in graph class#############
def bfs_counting(graph, root_vertex, bottom_vertex): # perform analysis twice: 1) set root_vertex = 't'; 2) set root_vertex = 's'
"""
use bfs explore graph from a single vertex
return a shortest path tree from that vertex
"""
#visited = dict()
nd_list = graph.keys()
visited = dict((node, 0) for node in nd_list)
visited[bottom_vertex]=0
nq = deque()# queue for recording current nodes
pre_dict, dist, parents, node_count_dict = {}, {}, {}, {}
nq.append(root_vertex)
visited[root_vertex]=1
dist[root_vertex] = 0
parents[root_vertex]=['fake_root']
node_count_dict['fake_root']=1
while nq:
s = nq.popleft() # dequeue
node_count_dict[s] = 0
for p in parents[s]: # count is defined as the sum of counts from all parents
node_count_dict[s] += node_count_dict[p]
#for node in self.__graph_dict[s]: # for each child/neighbour of current node 's'
if not s in graph.keys():
continue
for node in graph[s]:
#if not node in visited:
if not visited[node]:
nq.append(node) # let 'node' in queue
pre_dict[node] = [s] # the 'parent' (in terms of shortest path from 'root') of 'node' is 's'
dist[node] = dist[s] + 1 # shortest path to 'root'
visited[node]=1 # 'node' is visted
parents[node]=[s] # record 'parents' of this node
else:
parents[node].append(s) # record 'parents' of this node
pre_dict[node].append(s)
node_count_dict.pop('fake_root')
return [pre_dict, node_count_dict] # two returns: 1) tree; 2) node count dictionary
def dfs(root, total_count):
#visited = []
leaf_count = dict()
#total_count = dict()
dfs_helper(root, leaf_count, total_count)
n = leaf_count['root']
for k in total_count.keys():
total_count[k] = total_count[k]/n
return total_count
def dfs_helper(v, leaf_count, total_count):
# Set current to root of binary tree
#visited.append(v.name)
if len(v.children) == 0:
leaf_count[v.name] = 1
else:
leaf_count[v.name] = 0
for nd in v.children:
#print(nd.name)
dfs_helper(nd, leaf_count, total_count)
leaf_count[v.name] += leaf_count[nd.name]
#print(leaf_count)
total_count[nd.name] += leaf_count[nd.name]
#print(total_count)
return
def add_branch(tree_map, current_node, total_count):
total_count[current_node.name] = 0
if current_node.name not in tree_map.keys():
return
children = tree_map[current_node.name]
for child in children:
child_node = Node(child)
current_node.add_child(child_node)
add_branch(tree_map, child_node, total_count)
return
def set_m(graph, eta):
m = int(math.log2((graph.num_vertices()**2)/(eta**2)))
print("m = %d" %m)
return m
#@jit
def cal_bc(graph, m, s_list, t_list): # m must be much smaller than the number of edges
nd_list = list(graph.vertices())
bc_dict = dict((node, 0) for node in nd_list)
for i in range(m):
#ndl_copy = copy.copy(nd_list)
print(i)
if len(nd_list) >=2:
s = choice(nd_list)
s_list.add(s)
nd_list.remove(s)
t = choice(nd_list)
t_list.add(t)
bfsts1 = time.time()
connect, pre_g = graph.is_connect(s, t)
bfsts2 = time.time()
print(" BFS: Duration: %f seconds" %(bfsts2-bfsts1))
dfsts1 = time.time()
if connect:
pre_g_rev, count1 = bfs_counting(pre_g,t,s)
pre_g_rev2, count2 = bfs_counting(pre_g_rev,s,t)
count = dict((node, count1[node] * count2[node]) for node in count1.keys())
count = dict((node, count1[node] / count[t]) for node in count1.keys())
count.pop(s)
count.pop(t)
for node in count.keys():
bc_dict[node] += count[node]
else:
#print("The two vertice are not connected")
continue
dfsts2 = time.time()
print(" BFS counting: Duration: %f seconds" %(dfsts2-dfsts1))
else:
break
return [bc_dict, s_list, t_list]
def maxBC(dict): #to be finished, default remove highest 1
#return sorted(dict, key=dict.get, reverse=True)[:n]
max_value = max(dict.values()) # maximum value
max_keys = [k for k, v in dict.items() if v == max_value]
#print(max_keys)
return max_keys
def get_set(g1, percent = 1.0, eta = 0.1):
#print(g1)
#g1 = read_udgraph('Wiki-Vote.txt')
#bc_dict = dict()
high_bc_set = []
vertice_list_s = {-1}
vertice_list_t = {-1}
m = set_m(g1, eta)
#m = 10
#print(m)
init, vertice_list_s, vertice_list_t = cal_bc(g1, m, vertice_list_s, vertice_list_t) # first calculation
#print(init)
num_nodes = g1.num_vertices()
for i in range(num_nodes**2): # set to 2
#print (i)
vi = maxBC(init)
high_bc_set += vi
if len(high_bc_set) >= percent * num_nodes:
for i in high_bc_set:
print(i)
break
for node in vi:
#print(node)
g1.delete_vertex(node)
init, vertice_list_s, vertice_list_t = cal_bc(g1, m, vertice_list_s, vertice_list_t)
return high_bc_set
if __name__ == "__main__":
graph = Graph()
#path = "email-Eu-core.txt"
path = sys.argv[1]
#path = "compositePPI_bindingOnly_edges.txt"
graph.read_edgelist(path)
#graph.read_edgelist("compositePPI_bindingOnly_edges.txt")
print("Vertices of graph:")
#print(graph.vertices())
print(graph.num_vertices())
print("Edges of graph:")
ts1 = time.time()
m = set_m(graph, 0.1)
#bc_set = get_set(graph, 0.5, 0.1)
percentage = float(sys.argv[2]) # in this version the percentrage is the top1%, 5% etc
bc_set = get_set(graph, percentage, 0.1)
ts2 = time.time()
print("Duration: %d seconds" %(ts2-ts1))
outfile = open(path.split('.')[0] + "_" + str(percentage) +"percentage_high_bc_set.txt", "w")
for i in bc_set:
outfile.write(i)
outfile.write('\n')
outfile.close()
|
29bc7b008f6dfe00a089dafda4b1a606408bd68d | ErikZornWallentin/Fun_Challenges | /Python/Length_Converter/length_converter.py | 3,447 | 4.1875 | 4 | #!/usr/bin/python
'''
Author: Erik Zorn - Wallentin
Created: May. 10 / 2016
This program was created to polish and improve my Python programming skills during my spare time.
This was created in several languages in my repository of code to show the differences in each language with the same functionality.
The script is on Length Conversion, if you don't know what that is, see below link:
http://www.metric-conversions.org/length/centimeters-to-feet.htm
The program will calculate Centimetre to Feet, and Feet to Centimetre.
It starts off by waiting for user input with a menu displayed to the user.
Menu:
1) Centimetre to Feet (cm to ft)
2) Feet to Centimetre (ft to cm)
3) Quit the program (q)
Choosing an option from the menu will allow you to do a specific conversion and ask for more input.
Once it gives you the result from the conversion it will return you to the menu.
The program has error checking to determine if the input from user was valid or not.
'''
import sys, timeit, datetime
import time
import os
'''
Purpose: The main menu that is displayed to the user
Parameters: NONE
Return: NONE
'''
def menu():
print("Please choose one of the following using (1,2,3):")
print("1) Centimetre to Feet (cm to ft)")
print("2) Feet to Centimetre (ft to cm)")
print("3) Quit the program (q)")
'''
Purpose: Checks if the input is only numbers, and gives a correct return value ( success or failure ) depending on the result
Parameters: input ( string input to be checked if it's only numbers )
Return: result (EXIT_SUCESS is 0 or EXIT_FAILURE is 1 or higher)
'''
def checkIsNumber(input):
periodCounter = 0
negativeNumber = False
for i in range(len(input)):
if (input[i] == '-' and i == 0):
#Do nothing as we will accept negative numbers
negativeNumber = True
elif (input[i] == '.'):
periodCounter = periodCounter + 1
if (periodCounter > 1):
print ("Entered input is not a number!\n")
return 0
elif (input[i].isdigit() == False):
print ("Entered input is not a number!\n")
return 0
return 1
userInput = '0'
checker = 1
os.system('clear')
menu()
while (checker == 1):
userInput = raw_input("Please enter a menu option: ")
if (userInput == '1'):
os.system('clear')
#Variables we will use our formula on
feetConverted = 0.0
centimetreInput = 0.0
input = "0"
print("*** Converting Centimetre to Feet (cm to ft) ***\n")
input = raw_input("Please enter Centimetre value: ")
#Check if the input is acceptable
result = checkIsNumber(input)
if (result == 1):
centimetreInput = float(input)
#Convert from Centimetre to Feet
feetConverted = centimetreInput * 0.032808
print("Feet result: %f\n" % feetConverted)
menu()
elif (userInput == '2'):
os.system('clear')
#Variables we will use our formula on
centimetreConverted = 0
feetInput = 0
input = "0"
print("*** Feet to Centimetre (ft to cm) ***\n")
input = raw_input("Please enter Feet value: ")
#Check if the input is acceptable
result = checkIsNumber(input)
if (result == 1):
feetInput = float(input)
#Convert from Feet to Centimetre
centimetreConverted = feetInput / 0.032808
print("Centimetre result: %f\n" % centimetreConverted)
menu()
elif (userInput == '3' or userInput == 'q'):
print("\nNow quitting the program!\n")
checker = 0
else:
os.system('clear')
print("Incorrect input, try again!\n")
menu() |
6426ac00f17c7d1c5879ddf994938cfa0a412e62 | ChienSien1990/Python_collection | /Ecryption/Encrpytion(applycoder).py | 655 | 4.375 | 4 | def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers, and spaces.
shift: 0 <= int < 26
returns: dict
"""
### TODO
myDict={}
for i in string.ascii_lowercase:
if((ord(i)+shift)>122):
myDict[i] = chr(ord(i)+shift-26)
else:
myDict[i] = chr(ord(i)+shift)
for i in string.ascii_uppercase:
if((ord(i)+shift)>90):
myDict[i] = chr(ord(i)+shift-26)
else:
myDict[i] = chr(ord(i)+shift)
return myDict
|
7dddf0cba7cb5f97137282a09323a090931f31f2 | xingchenwan/NeuAcademy | /initialisation.py | 2,893 | 3.9375 | 4 | # Initialisation routine for first time login of an user
import pandas as pd
import numpy as np
from settings import *
from utils import *
def init_user(udata: pd.DataFrame) -> pd.DataFrame:
"""
Initialise a new user in the system
:param udata: the user data df
:return: the updated user data df containing the new information
"""
user_data = pd.Series(0, index=udata.columns)
while True:
user_id = input("Welcome to NeuAcademy v.1. Please enter your preferred ID: ")
if user_id in udata['ID']:
print("ID " + user_id + " already exists. Choose another ID")
else:
user_data['ID'] = user_id
break
while True:
try:
level = int(input("Select your syllabus: \n Physics Aptitude Test (PAT): 1"))
break
except ValueError:
print("Please enter an integer number.")
if level == 1:
print("Syllabus PAT selected.")
response = generate_pat_questionnaire()
# Update user profile using the response to the initial questionnaire
udata = update_user_profile_from_questionnaire(user_data, response)
else: # This will be updated when we have question data for other syllabi
print("Syllabus" + str(level) + "not currently available.")
save_user_data_csv(udata)
return udata
def generate_pat_questionnaire() -> list:
"""
Generate survey question for each and every PAT topic.
:return: A list of integers (length = number of PAT topics) in the range of [1,5] which gauges the self-assessed
ability of the student in each topic.
"""
print("The next few questions are intended to survey your understanding across five broad categories of the PAT"
"syllabus. On a scale of 1 (least understanding) to 5 (best understanding), select your response.")
responses = [0] * NUM_PAT_TOPICS
for i in range(NUM_PAT_TOPICS):
while True:
try:
responses[i] = int(input("Enter an integer from 1 to 5 for"+ PAT_TOPICS[i] + ": "))
if responses[i] >= 1 and responses[i] <= 5:
break
else:
print("Please enter an integer between 1 to 5")
except ValueError:
print("Please enter an integer number.")
return responses
def update_user_profile_from_questionnaire(user_id: pd.Series, responses: list) -> pd.DataFrame:
"""
Update user profile from the questionnaire response
:param user_data: data of the single user presented as a pandas series
:param responses: responses from the questionnaire - a list by default
todo: we have to design an algorithm that assigns appropriate weight to this initial questionnnaire!
:return: a new userdata dataframe that contains the updated information about this user
"""
pass
|
1105fd4cb3e9b95294e5e918b0017e7f109d1aac | sujit4/problems | /interviewQs/InterviewCake/ReverseChars.py | 1,023 | 4.25 | 4 | # Write a function that takes a list of characters and reverses the letters in place.
import unittest
def reverse(list_of_chars):
left_index = 0
right_index = len(list_of_chars) - 1
while left_index < right_index:
list_of_chars[left_index], list_of_chars[right_index] = list_of_chars[right_index], list_of_chars[left_index]
left_index += 1
right_index -= 1
# Tests
class Test(unittest.TestCase):
def test_empty_string(self):
list_of_chars = []
reverse(list_of_chars)
expected = []
self.assertEqual(list_of_chars, expected)
def test_single_character_string(self):
list_of_chars = ['A']
reverse(list_of_chars)
expected = ['A']
self.assertEqual(list_of_chars, expected)
def test_longer_string(self):
list_of_chars = ['A', 'B', 'C', 'D', 'E']
reverse(list_of_chars)
expected = ['E', 'D', 'C', 'B', 'A']
self.assertEqual(list_of_chars, expected)
unittest.main(verbosity=2) |
a88d70f775bc70026cb338561fecd88be94058fb | michaelstreyle/CS160 | /Exercises/Exercise8B.py | 1,263 | 4.03125 | 4 | """
Tree building exercise
Michael Streyle
LIST IMPLEMENTATION
"""
def BinaryTree(r):
return [r, [], []]
def insert_child_left(root, new_branch):
t = root.pop(1)
if len(t) > 1:
root.insert(1, [new_branch, t, []])
else:
root.insert(1, [new_branch, [], []])
return root
def insert_child_right(root, new_branch):
t = root.pop(2)
if len(t) > 1:
root.insert(2, [new_branch, [], t])
else:
root.insert(2, [new_branch, [], []])
return root
def get_root_val(root):
return root[0]
def set_root_val(root, new_val):
root[0] = new_val
def get_child_left(root):
return root[1]
def get_child_right(root):
return root[2]
def clockwise(root):
"""Clockwise tree traversal"""
print(get_root_val(root), end=" ")
if get_child_right(root):
clockwise(get_child_right(root))
if get_child_left(root):
clockwise(get_child_left(root))
def build_tree_lst() -> list:
"""Build a tree and return it"""
tree = BinaryTree('a')
insert_child_left(tree, 'b')
insert_child_right(get_child_left(tree), 'd')
insert_child_right(tree, 'c')
insert_child_left(get_child_right(tree), 'e')
insert_child_right(get_child_right(tree), 'f')
return tree |
2003afa4046346dda230a99effaebb4f337413a6 | fanwangwang/fww_study | /doc/py_example/femknowledge/change.py | 558 | 3.53125 | 4 | #给定一个$5×4$ 的矩阵,把它变成 $4×5$ $2*10$ 的列向量,并且每隔 $4$ 行取一个元素
import numpy as np
A = np.array([[1,2,3,3],[1,2,3,4],[1,1,2,3],[2,0,0,2],[0,0,1,2]])
print(A)
a = np.reshape(A,(4,5))
print(a)
B = np.reshape(A,(4,5),order = 'F')
C = np.reshape(A,(4,5),order = 'C')
print(B)
print(C)
# 变换的时候默认是‘C’,如果加‘order = 'F'’,则是按列排列,例如变换成 $m×n$ 矩阵,
# 则取先取第一列的前 $m$ 个元素组成一行,再接着按列取$m$个元素组成第二行...
|
eb93656378a977bac3503804f3a8ad7123d41385 | fanwangwang/fww_study | /doc/py_example/femknowledge/matrixmutivec.py | 289 | 3.546875 | 4 | # 给定一个 $5×n5$ 的矩阵,$5×1$ 的向量,对矩阵与向量作乘积,以及对向量与数作乘积
import numpy as np
A = np.array([[4,-1,0,0,0],[-1,4,-1,0,0],[0,-1,4,-1,0],[0,0,-1,4,-1],[0,0,0,-1,4]])
b = [1,1,1,1,1]
x = A*b
y = A@b
y = y.reshape(5,1)
print(x)
print(y)
|
d97afa0117f3088d653e118423252078f9b1982c | gcarrara97/projeto_semantix | /projeto_semantix_6_balanco.py | 2,548 | 3.53125 | 4 | arquivo_parcial = open("bank.csv", "r")
arquivo_completo = open("bank-full.csv", "r")
#Questo 6
#BALANO
linhas = arquivo_completo.readlines()
fl = False
emprestimo_imobiliario = 0
balanco = []
for i in linhas:
linha = i.split(';')
if fl == True:
if linha[6] == "\"yes\"":
emprestimo_imobiliario += 1
balanco.append(int(linha[5]))
else:
fl = True
print("Nmero de clientes com emprstimo imobilirio: " + str(emprestimo_imobiliario))
print("MENOR BALANO " + str(min(balanco)))
print("MAIOR BALANO " + str(max(balanco)))
b0 = 0
b0_10000 = 0
b10000_20000 = 0
b20000_30000 = 0
b30000_40000 = 0
b40000_50000 = 0
b50000_60000 = 0
fl = False
for i in linhas:
linha = i.split(';')
if fl == True:
if linha[6] == "\"yes\"":
if int(linha[5]) < 0:
b0 += 1
if int(linha[5]) >= 0 and int(linha[5]) < 10000:
b0_10000 += 1
if int(linha[5]) >= 10000 and int(linha[5]) < 20000:
b10000_20000 += 1
if int(linha[5]) >= 20000 and int(linha[5]) < 30000:
b20000_30000 += 1
if int(linha[5]) >= 30000 and int(linha[5]) < 40000:
b30000_40000 += 1
if int(linha[5]) >= 40000 and int(linha[5]) < 50000:
b40000_50000 += 1
if int(linha[5]) >= 50000 and int(linha[5]) < 60000:
b50000_60000 += 1
else:
fl = True
print("Menor que 0 euros: freq. absoluta de " + str(b0) + " e freq. relativa de " + str(float(b0)/emprestimo_imobiliario))
print("Entre 0 e 10000 euros: freq. absoluta de " + str(b0_10000) + " e freq. relativa de " + str(float(b0_10000)/emprestimo_imobiliario))
print("Entre 10000 e 20000 euros: freq. absoluta de " + str(b10000_20000) + " e freq. relativa de " + str(float(b10000_20000)/emprestimo_imobiliario))
print("Entre 20000 e 30000 euros: freq. absoluta de " + str(b20000_30000) + " e freq. relativa de " + str(float(b20000_30000)/emprestimo_imobiliario))
print("Entre 30000 e 40000 euros: freq. absoluta de " + str(b30000_40000) + " e freq. relativa de " + str(float(b30000_40000)/emprestimo_imobiliario))
print("Entre 40000 e 50000 euros: freq. absoluta de " + str(b40000_50000) + " e freq. relativa de " + str(float(b40000_50000)/emprestimo_imobiliario))
print("Entre 50000 e 60000 euros: freq. absoluta de " + str(b50000_60000) + " e freq. relativa de " + str(float(b50000_60000)/emprestimo_imobiliario))
|
6a28d887ba8bf192a48254a460922cbadd0b0074 | jasonzhixian/PythonForOffer | /Python_exercise/5_print_linked_list_for_end_to_start/exercise_reverse.py | 664 | 3.90625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def printLinkedListFromHeadToTail(self, listNode):
if listNode is None:
return None
result = []
cur = listNode
while cur:
result.append(cur.val)
cur = cur.next
return result
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next= node2
node2.next = node3
node3.next = node4
solution = Solution()
test = ListNode(None)
print(solution.printLinkedListFromHeadToTail(node1))
print(solution.printLinkedListFromHeadToTail(test))
|
dfb0505e3afbc8e12cf9f22f0e65d14cce9cda17 | jasonzhixian/PythonForOffer | /Python_exercise/19_Mirror_of_binary_tree/exercise.py | 691 | 3.609375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#change the exist tree
def mirrorBinaryTree(self, root):
if root == None:
return None
root.left, root.right = root.right, root.left
self.mirrorBinaryTree(root.left)
self.mirrorBinaryTree(root.right)
return root
#create the new tree
def mirrorBinaryTree_2(self, root):
if root == None:
return None
newTree = TreeNode(root.val)
newTree.left = self.mirrorBinaryTree_2(root.left)
newTree.right = self.mirrorBinaryTree_2(root.right)
return newTree |
9fe23b1af531610a538a71a5a2e19986cb992506 | jasonzhixian/PythonForOffer | /exercise_for_tree.py | 4,999 | 3.625 | 4 | #6
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#reconstructbinarytree
def reConstructBinaryTree(self, preorder, inorder):
if not preorder and not inorder:
return None
root = TreeNode(preorder[0])
if set(preorder) != set(inorder):
return None
i = preorder.indes(inorder[0])
root.left = self.reConstructBinaryTree(preorder[1, i+1], inorder[:i])
root.right = self.reConstructBinaryTree(preorder[i+1], inorder[i+1:])
return root
def preorder(self, root):
if root is None:
return None
print(root.val, end = '')
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
if root is None:
return None
self.inorder(root.left)
print(root.val, end = '')
self.inorder(root.right)
def backorder(self, root):
if root is None:
return None
self.backorder(root.left)
self.backorder(root.right)
print(root.val, end = '')
#39
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#maximum depth of binary tree
def maxDepth(self, root):
if root is None:
return 0
else:
max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
#minimum depth of binary tree
def minDepth(self, root):
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
#19
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#change the exist tree
def mirrorBinaryTree(self, root):
if root is None:
return None
root.left, root.right = root.right, root.left
self.mirrorBinaryTree(root.left)
self.mirrorBinaryTree(root.right)
return root
#create the new tree
def mirrorBinaryTree(self, root):
if root is None:
return None
newtree = TreeNode(root.val)
newtree.left = self.mirrorBinaryTree(root.left)
newtree.right = self.mirrorBinaryTree(root.right)
return newtree
#pathSum
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
else:
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-roo.val)
#is symmetric_tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
self.isSymmetricRe(root.left, root.right)
def isSymmetricRe(self, left, right):
if left is None and right is None:
return True
if left is None or right is None or left.val != right.val:
return False
return self.isSymmetricRe(left.left, right.right) and self.isSymmetricRe(left.right, right.left)
#binary tree level order traversal / reverse
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrder(self, root): #def levelOrderBottom
if root is None:
return []
result, cur = [], [root]
while cur:
next_level, vals = [], []
for node in cur:
vals.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
cur = next_level
result.append(vals)
return result #return result[::-1]
#39_2 is balanced binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
#solution one
def getDepth(self, root):
if root is None:
return 0
else:
return max(self.getDepth(root.left), self.getDepth(root.right)) + 1
def isBalanced(self):
if root is None:
return True
if abs(self.getDepth(root.left) - self.getDepth(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
|
73db8a09cd5009c1c9cdca7ffdc92a3f7fc34fab | 12389285/meps | /code/constraints/distribution.py | 7,548 | 3.84375 | 4 | from itertools import permutations, repeat
import numpy
def distribution(schedule, courses):
"""
This function calculates the malus points regarding the spread of course
activities over the week.
This function takes as input arguments:
- the schedule
- list of courses
This function works as follows:
- makes lists with days on which lectures, tutorials and practica
are given
- calculates bonus and malus points regarding the best spread
combinations of tutorials, lectures and practica
"""
malus = 0
# make lists to see on what day the different activities are scheduled
for i in range(len(courses)):
name = courses[i].name
number_activities = courses[i].dif_total
day_lec_1 = None
day_lec_2 = None
day_tut = []
day_pr = []
total_days = []
total_lecs = []
double_lec = 0
for i in range(len(schedule)):
for j in range(len(schedule[i])):
for k in range(len(schedule[i][j])):
if schedule[i][j][k] != None:
course, sort = str(schedule[i][j][k]).split("_")
if course == name:
if 'lec' in sort:
if day_lec_1 == None:
day_lec_1 = i
# add to lecture and total list
total_lecs.append(i)
total_days.append(i)
else:
day_lec_2 = i
if day_lec_2 != day_lec_1:
total_lecs.append(i)
total_days.append(i)
else:
double_lec = 1
elif 'tut' in sort:
# add to tutorial days list
day_tut.append(i)
elif 'pr' in sort:
# add to practica days list
day_pr.append(i)
# in case there are both practica and tutorials
if day_pr and day_tut:
malus = malus + tut_and_prac(day_tut, day_pr, total_days, number_activities)
# in case there are only tutorials and no practica
elif day_tut and not day_pr:
malus = malus + only_tut(day_tut, total_days, total_lecs, double_lec, number_activities)
# in case there are only practica and no tutorials
elif day_pr and not day_tut:
malus = malus + only_prac(day_pr, total_days, total_lecs, double_lec, number_activities)
else:
if double_lec == 1:
malus = malus + 10
return malus
def tut_and_prac(tut, prac, total_days, number_activities):
"""
This function calculates bonus and malus points regarding the best spread
combinations of tutorials, lectures and practica.
"""
# set variables and lists
malus = 0
comb_doubles = []
best_comb = []
combinations = list(list(zip(r, p)) for (r, p) in zip(repeat(tut), permutations(prac)))
# calculate combination list without prac and tut on the same day
for i in range(len(combinations)):
double = 0
for j in range(len(combinations[i])):
num = str(combinations[i][j])
num1, num2 = num.split(',')
num1 = num1.replace('(', '')
if num1 in num2:
double = double + 1
comb_doubles.append(double)
best = numpy.min(comb_doubles)
best_index = [i for i,x in enumerate(comb_doubles) if x == best]
for i in range(len(best_index)):
ind = best_index[i]
best_comb.append(combinations[ind])
# for these combinations, calculate the malus points
tot = []
points_list = []
for i in range(len(best_comb)):
points_tot = 0
for j in range(len(best_comb[i])):
tot = []
tot.extend(total_days)
tot.extend(best_comb[i][j])
tot = list(set(tot))
points_m = spread_malus(number_activities, tot)
points_b = spread_bonus(number_activities, tot)
points_tot = points_tot + (points_m + points_b) / len(best_comb[i])
points_list.append(points_tot)
# choose the option with the smallest amount malus points, and calculate points
best_points = numpy.min(points_list)
best_points_index = numpy.argmin(points_list)
couples = best_comb[best_points_index]
malus = best_points
return malus
def only_tut(day_tut, total_days, total_lecs, double_lec, number_activities):
"""
This function calculates bonus and malus points regarding the best spread
combinations of tutorials and lectures.
"""
malus = 0
double = 0
# if the lectures are on te same day it costs points
if double_lec == 1:
malus = malus + 10
# count malus points
for i in range(len(day_tut)):
total_days.append(day_tut[i])
if day_tut[i] in total_lecs:
double = double + 1
double_frac = double / len(day_tut)
malus = malus + double_frac * 10
# count bonus points for perfectly spread activities
bonus = 0
for i in range(len(day_tut)):
all_days = []
all_days.extend(total_lecs)
all_days.append(day_tut[i])
bonus = bonus + (spread_bonus(number_activities, all_days) / len(day_tut))
malus = malus + bonus
return malus
def only_prac(day_pr, total_days, total_lecs, double_lec, number_activities):
"""
This function calculates bonus and malus points regarding the best spread
combinations of lectures and practica.
"""
malus = 0
double = 0
# if the lectures are on te same day it costs points
if double_lec == 1:
malus = malus + 10
day_pr = list(set(day_pr))
for i in range(len(day_pr)):
total_days.append(day_pr[i])
if day_pr[i] in total_lecs:
double = double + 1
double_frac = double / len(day_pr)
malus = malus + double_frac * 10
# count bonus points for perfectly spread activities
bonus = 0
for i in range(len(day_pr)):
all_days = []
all_days.extend(total_lecs)
all_days.append(day_pr[i])
bonus_this = (spread_bonus(number_activities, all_days) / len(day_pr))
bonus = bonus + bonus_this
malus = malus + bonus
return malus
def spread_malus(number_activities, diff_days):
"""
This function returns malus points if activities are not spread well
enough.
"""
malus = 0
if len(diff_days) == number_activities - 1:
malus = malus + 10
elif len(diff_days) == number_activities - 2:
malus = malus + 20
elif len(diff_days) == number_activities - 3:
malus = malus + 30
return malus
def spread_bonus(number_activities, diff_days):
"""
This function returns bonus points if activities are perfectly spread.
"""
malus = 0
if number_activities == 2:
if diff_days == [0, 3] or diff_days == [1, 4]:
malus = malus - 20
if number_activities == 3:
if diff_days == [0, 2, 4]:
malus = malus - 20
if number_activities == 4:
if diff_days == [0, 1, 3, 4]:
malus = malus - 20
return malus
|
e8ccaa13937f18d9f09a3484df5915e0506f1cc2 | 12389285/meps | /code/constraints/overlap_simulated.py | 1,275 | 4.0625 | 4 | def overlapping(activity, timelock, overlap_dict, roomlock):
"""
This function returns True if the is no overlap with courses given in the
overlap matrix. Otherwise, it returns False.
This function takes as input arguments:
- activity
- time lock and room lock
- overlap matrix
"""
# if it is None it is always true
if activity == None:
return True
else:
# check if two lectures are given in timelock
if '_lec' in activity:
for i in range(len(timelock)):
if i == roomlock:
continue
elif activity == timelock[i]:
return False
# check if no other overlap-course is given in the same time lock
activity = activity.split('_')
for i in range(len(timelock)):
activity_timelock = timelock[i]
if activity_timelock != None:
if i == roomlock:
continue
activity_timelock = timelock[i].split('_')
activity_timelock = activity_timelock[0]
if activity_timelock in overlap_dict[activity[0]]:
if activity_timelock != activity[0]:
return False
return True
|
ecc6ade6a296c0f1d2b4f6567eba9a4d13951e00 | michaelsong93/python-prac | /sep4-2.py | 598 | 3.75 | 4 | lst1 = [('a',1),('b',2),('c','hi')]
lst2 = ['x','a',6]
d = {k:v for k,v in lst1}
s = {x for x in lst2}
print(d)
print(s)
def f(n):
yield n
yield n+1
yield n*n
print([i for i in f(3)])
def merge(l,r):
llen = len(l)
rlen = len(r)
i = 0
j = 0
while i < llen or j < rlen:
if j == rlen or (i < llen and l[i] < r[j]):
yield l[i]
i += 1
else:
yield r[j]
j += 1
# g = merge([1,3,5],[2,4,6])
# while True:
# print(g.__next__())
# print(merge([1,3,5],[2,4,6]))
print([x for x in merge([1,2,5],[3,4,6])]) |
93f460a4b712f9b45b30382d5ffa6213db38d226 | lemacm/python | /loan.py | 2,819 | 4.03125 | 4 | name = input ("Name: ")
def takeincome(num):
if num < 500:
return 'payscale1'
elif num < 1000:
return 'payscale2'
else:
return 'payscale3'
def criteria1 ():
print('''Are you employed?)
- No
- Part time''')
employment = input ('Please choose one of the provided options: ')
if employment == 'No':
print ("Unfortunatelly we cannot lend you any money")
else:
print('''What will you use this money for?
- Debt
- Car
- Holiday''')
purpose = input ('Please choose one of the provided options: ')
criteria2(purpose)
def lencalc (money):
print('''How long do you want to borrow it for(in months)?
- 1
- 6
- 12''')
length = int(input(": "))
calculation = money*5/length
print("We have done our calculation and the good news is that you'll have to pay us back", money * 5,"over", length, "months.")
print("Your monthly rate will be £", calculation)
def criteria2 (strg):
amountborr = [100,200,300,400,500,600,700,800,900,1000]
income = int (input("What's your annual income?: "))
if takeincome(income)== 'payscale1':
if strg == 'Debt':
print ("you can borrow between £100 and £400.")
amount = int(input("How much would you like to borrow? (The amount has to be in hundreds): "))
if amount in amountborr[0:4]:
print ("Luky you, we can lend you", amount,"pounds straightaway.")
lencalc (amount)
else:
print("Sorry, it has to be between £100 and £400.")
else:
print ("you can borrow between £100 and £600.")
amount = int(input("How much would you like to borrow? "))
if amount in amountborr[0:6]:
print ("Luky you, we can lend you", amount,"pounds straightaway.")
lencalc (amount)
else:
print("Sorry, it has to be between £100 and £600.")
elif takeincome(income)== 'payscale2':
print ("you can borrow between £100 and £1000.")
amount = int(input("How much would you like to borrow? "))
if amount in amountborr[0:]:
print ("Luky you, we can lend you", amount,"pounds straightaway.")
lencalc (amount)
else:
print("Sorry, it has to be between £100 and £1000.")
else:
print(name,",you are making lots of money, you don't need a loan!")
def checkage():
age = int (input ("How old are you: "))
if age <=18:
print (name,",you are too young to get a loan!")
else:
criteria1()
checkage()
|
4c1e3608010a0b5c306c5fbd10bc00b07fc0e771 | sishu7/common-interview-questions | /ZeroDuplicates.py | 575 | 3.625 | 4 | #zeroes duplicates in a list, after first instance
def zero_duplicates(l):
dict1 = {}
for i in range(0, len(l)):
if l[i] in dict1: l[i] = 0
else: dict1[l[i]] = 1
return l
print zero_duplicates([1, 2, 2, 3, 4, 4, 5, 5, 6, 6])
#zeroes all duplicates in a list
def zero_duplicates2(l):
dict1 = {}
for i in range(0, len(l)):
if l[i] not in dict1: dict1[l[i]] = 1
else: dict1[l[i]] += 1
for j in range(0, len(l)):
if dict1[l[j]] > 1: l[j] = 0
return l
print zero_duplicates2([1, 2, 2, 3, 4, 4, 5, 5, 6, 6])
|
b73eef9b47783fca87f8bb1201a46bebd0cc1e3e | sishu7/common-interview-questions | /StringComparison.py | 388 | 3.84375 | 4 | #compares strings character by characters
def compare(str1, str2):
if len(str1) == len(str2):
for i in range(0, len(str1)):
if str1[i] != str2[i]:
return False
else:
return False
return True
print compare('abc', 'abc')
print compare('abd', 'abc')
print compare(' love you', 'I love you')
print compare('I love you', 'I love you')
|
6c3c5507ecf07b53bf40a1353ba04447ea80d882 | ErikWeisz5/chapter_work | /3/6.py | 149 | 3.765625 | 4 | d = int(input("your day"))
m = int(input("your month"))
y = int(input("your year"))
if d * m == y :
print("magic")
else :
print("not magic") |
84006abd27c93fcb1fd6fe813161f34ab0177e9f | ErikWeisz5/chapter_work | /4/3.py | 300 | 3.765625 | 4 | l = int(input("number of laps: "))
r = set()
a = 0
b = 0
while a < l:
seconds = int(input("Lap time: "))
r.add(seconds)
a += 1
r = list(r)
r.sort()
while b < l:
b += r[b]
average = b/l
print("fastest lap : ", r[0])
print("Slowest Lap : ", r[a-1])
print("average lap : ", average) |
1946e3e82bc870dc367c8d3b9b9c19536bb2aed4 | jruizvar/jogos-data | /aula/variable.py | 495 | 3.515625 | 4 | """
Variables in tensorflow
"""
import tensorflow as tf
"""
RANK 0
"""
a = tf.Variable(4, name='a')
b = tf.Variable(3, name='b')
c = tf.add(a, b, name='c')
print("Variables in TF\n")
print(a)
print(b)
print(c)
print()
with tf.Session() as sess:
sess.run(a.initializer)
sess.run(b.initializer)
a_val = a.eval()
b_val = b.eval()
c_val = c.eval()
print("The value of a:", a_val)
print("The value of b:", b_val)
print("The value of c:", c_val)
print()
|
5a748bacb223ad9de8620dd4ebcad3c457525ef8 | JuanSebastianOG/Analisis-Numerico | /Talleres/PrimerCorte/PrimerTaller/CuadraticaMejorada.py | 670 | 3.953125 | 4 | #Implementacion de una ecuación que mejora la ecuación cuadratica original
import math
def calculoOriginal( a, b, c ):
x0 = (-b - math.sqrt( b**2 - 4*a*c )) / (2*a)
x1 = (-b + math.sqrt( b**2 - 4*a*c )) / (2*a)
print("Los valores de las raices con la formula original son: Xo -> ", x0, " X1 -> ", x1)
def calculoMejorado( a, b, c ):
x0 = (2*c) / (-b - math.sqrt( b**2 - 4*a*c ))
x1 = (2*c) / (-b + math.sqrt( b**2 - 4*a*c ))
print("Los valores de las raices con la formula mejorada son: Xo -> ", x0, " X1 -> ", x1)
if __name__ == "__main__":
calculoOriginal( 3, 9 ** 12, -3 )
calculoMejorado( 3, 9 ** 12, -3 )
|
934bdc157134659f5fc834ea4bce96bd6df629a2 | JuanSebastianOG/Analisis-Numerico | /Talleres/PrimerCorte/PrimerTaller/Algoritmos/Metodo_Newton.py | 1,285 | 4.25 | 4 | #Implementación del método de Newton para encontrar las raices de una función dada
from matplotlib import pyplot
import numpy
import math
def f( x ):
return math.e ** x - math.pi * x
def fd( x ):
return math.e ** x - math.pi
def newton( a, b ):
x = (a + b) / 2
it = 0
tol = 10e-8
errorX = []
errorY = []
raiz = x - ( f(x) / fd(x) )
while abs( raiz - x ) > tol:
if it > 0:
errorX.append( abs( raiz - x ) )
it = it + 1
x = raiz
raiz = x - ( f(x) / fd(x) )
if it > 1:
errorY.append( abs( raiz - x ) )
print("La raiz que se encuentra en el intervalo ", a, ", ", b, " es aproximadamente: ", raiz )
print("El numero de iteraciones que se obtuvieron: ", it )
pol = numpy.polyfit(errorX, errorY, 2)
pol2 = numpy.poly1d( pol )
cX = numpy.linspace( errorX[0], errorX[len(errorX) - 1], 50 )
cY = pol2( cX )
pyplot.plot( cX, cY )
pyplot.xlabel("Errores X ")
pyplot.ylabel("Errores Y ")
pyplot.title("Metodo de Newton: \n Errores en X vs. Errores en Y")
pyplot.grid()
pyplot.show()
#------------------------MAIN------------------------------------------
if __name__ == "__main__":
newton( 0, 1 )
newton( 1, 2 )
|
72f12e63fbac4561a74211964ab031f5ffb29212 | derick-droid/pythonbasics | /files.py | 905 | 4.125 | 4 | # checking files in python
open("employee.txt", "r") # to read the existing file
open("employee.txt", "a") # to append information into a file
employee = open("employee.txt", "r")
# employee.close() # after opening a file we close the file
print(employee.readable()) # this is to check if the file is readable
print(employee.readline()) # this helps read the first line
print(employee.readline()) # this helps to read the second line after the first line
print(employee.readline()[0]) # accessing specific data from the array
# looping through a file in python
for employees in employee.readline():
print(employee)
# adding information into a file
employee = open("employee.txt", "a")
print(employee.write("\n derrick -- for ICT department"))
employee.close()
# re writing a new file or overwriting a file
employee = open("employee1.txt", "w")
employee.write("kelly -- new manager")
|
8cf687f5d815f6fc2b0940d55d30e46cd1c7355a | derick-droid/pythonbasics | /exponent functions.py | 184 | 3.765625 | 4 | def large_number(base_number, power_number):
result = 1
for index in range(power_number):
result = result * base_number
return result
print(large_number(3, 2))
|
16086860e6bf740354f6cdb0537fbbe3f39e85ae | derick-droid/pythonbasics | /nest2dic.py | 404 | 4.09375 | 4 | # creating nested dictionary with for loop
aliens = []
for alien_number in range (30):
new_alien = {
"color" : "green",
"point" : 7,
"speed" : "high"
}
aliens.append(new_alien)
print(aliens)
for alien in aliens[:5]:
if alien["color"] == "green":
alien["color"] == "red"
alien["point"] == 8
alien["speed"] == "very high"
print(alien) |
ea96c07f9845aca38a5011f1009a7dc4b8de30e9 | derick-droid/pythonbasics | /dictionary.py | 686 | 3.53125 | 4 | # returning dictionary in functionn
def user_dictionary (first_name, last_name):
full = {
"first_name" : first_name,
"last_name" : last_name
}
return full
musician = user_dictionary("ford", "dancan")
print(musician)
# using optinal values in dictionary
def dev_person(occupation, age, home_town = ""):
if home_town:
person = {
"occupation" : occupation,
"age" : age,
"home_town" : home_town
}
return person
else:
person = {
"occupation" : occupation,
"age" : age
}
return person
user = dev_person("software developer", "23", "Migori")
print(user)
|
95a9f725607b5acc0f023b0a0af2551bec253afd | derick-droid/pythonbasics | /dictexer.py | 677 | 4.90625 | 5 | # 6-5. Rivers: Make a dictionary containing three major rivers and the country
# each river runs through. One key-value pair might be 'nile': 'egypt'.
# • Use a loop to print a sentence about each river, such as The Nile runs
# through Egypt.
# • Use a loop to print the name of each river included in the dictionary.
# • Use a loop to print the name of each country included in the dictionary.
rivers = {
"Nile": "Egypt",
"Amazon": "America",
"Tana": "Kenya"
}
for river, country in rivers.items():
print(river + " runs through " + country)
print()
for river in rivers.keys():
print(river)
print()
for country in rivers.values():
print(country) |
dcf2b3140557d00145cdcbc2cddddedc08e6095d | derick-droid/pythonbasics | /listfunctions.py | 248 | 3.828125 | 4 | lucky_numbers = [1, 2, 3, 4, 5, 6, 7]
friends = ["derrick", "jim", "jim", "trump", "majani" ]
friends.extend(lucky_numbers) # to add another list on another list
print(friends)
print(friends.count("jim")) # to count repetitive objects in a list
|
6da039c504277c5a23ca5a744faa1f2341c58105 | derick-droid/pythonbasics | /persona.py | 446 | 3.78125 | 4 | class Robots:
def __init__(self, name, color, weight):
self.name = name
self.color = color
self.weight = weight
def introduce_yourself(self):
print("my name is " + self.name )
print("I am " + self.color )
print("I weigh " + self.weight)
r1 = Robots("Tom", "blue", "34kg")
r2 = Robots("Derrick", "yellow", "50kgs")
r1.introduce_yourself()
print(" ")
r2.introduce_yourself() |
448b01b0daa1f1cb13ac286d3f4c600318cf8a30 | derick-droid/pythonbasics | /module.py | 262 | 3.890625 | 4 | # from largest_number import largest_number
# biggest_number = largest_number(numbers)
# print(biggest_number)
from largest_number import find_biggest_number
numbers = [2, 3, 73, 83, 27, 7, ]
biggest_number = find_biggest_number(numbers)
print(biggest_number)
|
935e0579d7cbb2da005c6c6b1ab7f548a6694a86 | derick-droid/pythonbasics | /slicelst.py | 2,312 | 4.875 | 5 | # 4-10. Slices: Using one of the programs you wrote in this chapter, add several
# lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:. Then use a slice to
# print the first three items from that program’s list.
# • Print the message, Three items from the middle of the list are:. Use a slice
# to print three items from the middle of the list.
# • Print the message, The last three items in the list are:. Use a slice to print
# the last three items in the list.
numbers = [1, 3, 2, 4, 5, 6, 7, 8, 9]
slice1 = numbers[:3]
slice2 = numbers[4:]
slice3 = numbers[-3:]
print(f"The first three items in the list are:{slice1}")
print(f"The items from the middle of the list are:{slice2}")
print(f"The last three items in the list are:{slice3}")
print()
# 4-11. My Pizzas, Your Pizzas: Start with your program from Exercise 4-1
# (page 60). Make a copy of the list of pizzas, and call it friend_pizzas .
# Then, do the following:
# • Add a new pizza to the original list.
# • Add a different pizza to the list friend_pizzas .
# • Prove that you have two separate lists. Print the message, My favorite
# pizzas are:, and then use a for loop to print the first list. Print the message,
# My friend’s favorite pizzas are:, and then use a for loop to print the sec-
# ond list. Make sure each new pizza is stored in the appropriate list.
print()
pizzas = ["chicago pizza", "new york_style pizza", "greek pizza", "neapolitans pizza"]
friends_pizza = pizzas[:]
pizzas.append("sicilian pizza")
friends_pizza.append("Detroit pizza")
print(f"my favourite pizzas are:{pizzas}")
print()
print(f"my friend favourite pizzas are:{friends_pizza}")
print()
print("my favourite pizzas are: ")
for pizza in pizzas:
print(pizza)
print()
print("my favourite pizzas are: ")
for items in friends_pizza:
print(items)
print()
#
# 4-12. More Loops: All versions of foods.py in this section have avoided using
# for loops when printing to save space. Choose a version of foods.py, and
# write two for loops to print each list of foods.
food_stuff = ["cake", "rice", "meat", "ice cream", "banana"]
food = ["goat meat", "pilau", "egg stew", "fried", "meat stew"]
for foodz in food_stuff:
print(foodz)
print()
for itemz in food:
print(itemz) |
5a827e2d5036414682f468fac5915502a784f486 | derick-droid/pythonbasics | /exerdic.py | 2,972 | 4.5 | 4 | # 6-8. Pets: Make several dictionaries, where the name of each dictionary is the
# name of a pet. In each dictionary, include the kind of animal and the owner’s
# name. Store these dictionaries in a list called pets . Next, loop through your list
# and as you do print everything you know about each print it
rex = {
"name" : "rex",
"kind": "dog",
"owner's name" : "joe"
}
pop = {
"name" :"pop",
"kind" : "pig",
"owner's name": "vincent"
}
dough = {
"name": "dough",
"kind" : "cat",
"owner's name" : "pamna"
}
pets = [rex, pop, dough ]
for item in pets:
print(item)
print()
# 6-9. Favorite Places: Make a dictionary called favorite_places . Think of three
# names to use as keys in the dictionary, and store one to three favorite places
# for each person. To make this exercise a bit more interesting, ask some friends
# to name a few of their favorite places. Loop through the dictionary, and print
# each person’s name and their favorite places.
favorite_places = {
"derrick": {
"nairobi", "mombasa", "kisumu"
},
"dennis":{
"denmark", "thika", "roman"
},
"john": {
"zambia", "kajiado", "suna"
}
}
for name, places in favorite_places.items(): # looping through the dictionary and printing only the name variable
print(f"{name} 's favorite places are :")
for place in places: # looping through the places variable to come up with each value in the variable
print(f"-{place}")
print()
# 6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so
# each person can have more than one favorite number. Then print each person’s
# name along with their favorite numbers.
favorite_number = {
"derrick" : [1, 2, 3],
"don" : [3, 5, 7],
"jazzy" : [7, 8, 9]
}
for name, fav_number in favorite_number.items():
print(f"{name} favorite numbers are: ")
for number in fav_number:
print(f"-{number}")
# 6-11. Cities: Make a dictionary called cities . Use the names of three cities as
# keys in your dictionary. Create a dictionary of information about each city and
# include the country that the city is in, its approximate population, and one fact
# about that city. The keys for each city’s dictionary should be something like
# country , population , and fact . Print the name of each city and all of the infor-
# mation you have stored about it.
cities = {
"Nairobi" : {
"population" : "1400000",
"country" : "kenya",
"facts" : "largest city in East Africa"
},
"Dar-es-salaam" : {
"population" : "5000000",
"country" : "tanzania",
"facts" : "largest city in Tanzania"
},
"Kampala" : {
"population" : "1000000",
"country" : "Uganda",
"facts" : "The largest city in Uganda"
}
}
for city, information in cities.items():
print(f"{city}:")
for fact,facts in information.items():
print(f"-{fact}: {facts}")
|
d65f32a065cc87e5de526a718aeea6d601e1ac06 | derick-droid/pythonbasics | /iflsttry.py | 2,930 | 4.5 | 4 | # 5-8. Hello Admin: Make a list of five or more usernames, including the name
# 'admin' . Imagine you are writing code that will print a greeting to each user
# after they log in to a website. Loop through the list, and print a greeting to
# each user:
# • If the username is 'admin' , print a special greeting, such as Hello admin,
# would you like to see a status report?
# • Otherwise, print a generic greeting, such as Hello Eric, thank you for log-
# ging in again.
usernames = ["derick-admin", "Erick", "charles", "yusuf"]
for name in usernames:
if name == "derick-admin":
print(f"Hello admin , would you like to see status report")
else:
print(f"Hello {name} , thank you for logging in again")
#
# 5-9. No Users: Add an if test to hello_admin.py to make sure the list of users is
# not empty.
# • If the list is empty, print the message We need to find some users!
# • Remove all of the usernames from your list, and make sure the correct
# message is printed.
users = ["deno", "geogre", "mulla", "naomi"]
users.clear()
if users:
for item in users:
print(f"hello {item}")
else:
print("we need at least one user")
print()
#
# 5-10. Checking Usernames: Do the following to create a program that simulates
# how websites ensure that everyone has a unique username.
# • Make a list of five or more usernames called current_users .
# • Make another list of five usernames called new_users . Make sure one or
# two of the new usernames are also in the current_users list.
# • Loop through the new_users list to see if each new username has already
# been used. If it has, print a message that the person will need to enter a
# new username. If a username has not been used, print a message saying
# that the username is available.
# •
# Make sure your comparison is case insensitive. If 'John' has been used,
# 'JOHN' should not be accepted.
web_users = ["derrick", "moses", "Raila", "john", "ojwang", "enock"]
new_users = ["derrick", "moses", "babu", "vicky", "dave", "denver"]
for user_name in new_users:
if user_name in web_users:
print("please enter a new user name ")
else:
print("the name already registered ")
print()
# 5-11. Ordinal Numbers: Ordinal numbers indicate their position in a list, such
# as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.
# • Store the numbers 1 through 9 in a list.
# • Loop through the list.
# • Use an if - elif - else chain inside the loop to print the proper ordinal end-
# ing for each number. Your output should read "1st 2nd 3rd 4th 5th 6th
# 7th 8th 9th" , and each result should be on a separate line
ordinary_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in ordinary_numbers:
if number == 1:
print(f'{number}st')
elif number == 2:
print(f"{number}nd")
elif number == 3:
print(f"{number}rd")
else:
print(f"{number}th")
|
80bb7af9cb2b49a297419ccdd8d6ae2d486f244a | leticiasayuri/introducao-pandas | /introducao/dataframe.py | 1,541 | 3.75 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Aluno': ["Wilfred", "Abbie", "Harry", "Julia", "Carrie"],
'Faltas': [3, 4, 2, 1, 4],
'Prova': [2, 7, 5, 10, 6],
'Seminário': [8.5, 7.5, 9.0, 7.5, 8.0]})
print("DataFrame\n", df, "\n")
print("Tipos no DataFrame\n", df.dtypes, "\n")
print("Colunas\n", df.columns, "\n")
print("Valores da coluna Seminário\n", df["Seminário"], "\n")
print("Informações matemáticas\n", df.describe(), "\n")
# Ordenação de DataFrame
print("Ordenação pela coluna Seminário\n",
df.sort_values(by="Seminário"), "\n")
# Seleção de valores pelo index
print("Selação de valores por índice (índice 3)\n", df.loc[3], "\n")
# Seleção de acordo com critérios condicionais
# Boolean Indexing
# Seleção das linhas em que o valor da coluna Seminário seja acima de 8.0
print("Seleção por critérios condicionais\nSeleção das linhas em que o valor da coluna Seminário seja acima de 8.0\n",
df[df["Seminário"] > 8.0], "\n")
# Condições de múltiplas colunas (deve-se usar operadores bitwise)
# Seleção das linhas em que o valor da coluna Seminário seja acima de 8.0
# e o valor da coluna Prova não seja menor que 3
print("Seleção por critérios condicionais de múltiplas colunas\nSeleção das linhas em que o valor da coluna Seminário seja acima de 8.0 e o valor da coluna Prova não seja menor que 3\n",
df[(df["Seminário"] > 8.0) & (df["Prova"] > 3)], "\n")
|
dec5f53cc6965129b4eeea95ac949cd8fa2fa3ba | 781-Algorithm/JeonPanGeun | /Algo_python/[BOJ] 10773.py | 1,287 | 3.75 | 4 |
# 백준 10773 제로
# 첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000)
#
# 이후 K개의 줄에 정수가 1개씩 주어진다.
# 정수는 0에서 1,000,000 사이의 값을 가지며,
# 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경우 해당 수를 쓴다.
#
# 정수가 "0"일 경우에 지울 수 있는 수가 있음을 보장할 수 있다.
class Stack:
def __init__(self):
self.top = []
self.cnt = 0
def push(self, item):
self.top.append(item)
self.cnt += 1
def pop(self):
if not self.isEmpty():
self.cnt -= 1
return self.top.pop(-1)
else:
print("Stack underflow")
exit()
def peek(self):
if not self.isEmpty():
return self.top[-1]
else:
print("underflow")
exit()
def isEmpty(self):
return self.cnt == 0
# return len(self.top) == 0
def size(self):
return self.cnt
n = int(input())
stack = []
# stack2 = Stack()
for _ in range(n):
money = int(input())
if money != 0:
stack.append(money)
# stack2.push(money)
elif money == 0:
stack.pop(-1)
# stack2.pop()
print(sum(stack))
|
0ed70af907f37229379d7b38b7aaae938a7fc31a | adamkozuch/scratches | /scratch_4.py | 584 | 4.15625 | 4 | def get_longest_sequence(arr):
if len(arr) < 3:
return len(arr)
first = 0
second = None
length = 0
for i in range(1, len(arr)):
if arr[first] == arr[i] or (second and arr[second]== arr[i]):
continue
if not second:
second = i
continue
if i - first > length:
length = i - first
first = second
second = i
if len(arr) - first > length:
length = len(arr) - first
return length
print(get_longest_sequence([1]))
print(get_longest_sequence([5,1,2,1,2,5]))
|
286fe8a0f431330f9fc43b430646ff942254a602 | jiz148/blueprint_editor | /model/operation/implement/multiply.py | 732 | 3.828125 | 4 | """
Operation: Multiply
"""
def generate_code(json_dict, lang='python'):
result = ''
multiply_1, multiply_2, output = parse_json(json_dict)
if lang == 'python':
result = "{} = {} * {}".format(output, multiply_1, multiply_2)
return result
def parse_json(json_dict):
"""
@param json_dict: should have keys: multiply_1, multiply_2, output
@return: strings of multiply_1, multiply_2, output
"""
try:
return str(json_dict['multiply_1']), str(json_dict['multiply_2']), str(json_dict['output'])
except Exception:
raise KeyError('Error while paring: Multiply')
if __name__ == '__main__':
print(generate_code({'multiply_1': 'a', 'multiply_2': 'b', 'output': 'asd'}))
|
1bbb879b68e07c8c9b20612ef956ed3fdfd4da51 | FatherZosima/CLV-Wishing-Well | /sim.py | 5,108 | 3.546875 | 4 | import random
import matplotlib.pyplot as plt
import numpy as np
import enum
class GambleOutcomes(enum.Enum):
Won = 1
Lost = 2
NoPlay = 3
class Player:
def __init__(self, startingHoldings, playerID):
self.currentHoldings = startingHoldings
self.holdingHistory = [startingHoldings]
self.gameHistory = [[] for f in range(numRounds)]
self.gamesPlayed = 0
self.playerID = playerID
def gamble(self):
gambleStatus = GambleOutcomes.NoPlay
global currentPot
if(self.wouldGamble()):#check if this a gamble the player might make
moneyToGamble = self.gambleAmount()
#now to actually test if they won
likelihood = 2.0/np.pi * np.arctan(0.1*moneyToGamble/currentPot)#2.0/np.pi * np.arctan(0.1*moneyToGamble/currentPot)
if(likelihood < minimumProbability): likelihood = minimumProbability
# likelihood = np.round(likelihood,3)
# print("calculating likelihood for player",self.playerID,"-",likelihood)
winningNum = random.uniform(0,1.0)
if(winningNum <likelihood):
gambleStatus = GambleOutcomes.Won
currentPot += moneyToGamble
self.currentHoldings += currentPot*(1-bankSkim)
currentPot *= bankSkim
else:
gambleStatus = GambleOutcomes.Lost
self.currentHoldings -= moneyToGamble
currentPot += moneyToGamble
self.gamesPlayed +=1
self.gameHistory[currRound].append(gambleStatus)
return gambleStatus
#would the player gamble
def wouldGamble(self):
return (self.currentHoldings > 0.1) #gamble as long as they have at least $0.1
#how much would the player gamble
def gambleAmount(self):
rand = random.uniform(0,0.5) #bet betwen 0-50% of earnings
return min(rand*self.currentHoldings,10000) #never bet more than 1000 at a time
#add currentHoldings to history of holdings (occurs at end of rounds)
def updateHistory(self):
self.holdingHistory.append(self.currentHoldings)
def printHistory(self):
wins = 0
losses = 0
noplays =0
for game in self.gameHistory:
for attempt in game:
if attempt == GambleOutcomes.Won: wins+=1
elif attempt == GambleOutcomes.Lost: losses +=1
elif attempt == GambleOutcomes.NoPlay: noplays+=1
hist = str(wins)+"/"+str(losses)+"/"+str(noplays)+"/"+str(self.gamesPlayed)
print("Player",self.playerID,"Final Balance:",np.round(self.currentHoldings,2),"Wins/Losses/NoPlays/TotalPlays",hist)
bankHoldings = 0
bankHoldingHistory = [bankHoldings]
bankSkim = 0.05 #bank skims 5% to build big pot
bigPayoutFrequency = 100 #big pot happens every 100 times
numRounds = 500
currRound = 0
currentPot = 5 #start with a small pot first round
numPlayers = 500
defaultStartingMoney = 500 #amount each player starts with
minimumProbability = 0.005 #at least 1/100 chance for any player
#populate list of players
players = []
for i in range(numPlayers):
p = Player(defaultStartingMoney, i)
players.append(p)
for i in range(numRounds):
if(i%bigPayoutFrequency==0 and i!=0):
currentPot+= bankHoldings
bankHoldings = 0
print("**************************ROUND",i,"**************************")
#players spend money until someone wins or round ends
roundWon = False
attempts = 0
while(roundWon==False):
#pick random palyer
randPlayer = np.random.randint(numPlayers)
#print("P",randPlayer," ($",players[randPlayer].currentHoldings,") attempting gamble POT:",currentPot)
gambleStatus = players[randPlayer].gamble()
#print("outcome:",gambleStatus)
if(gambleStatus!=GambleOutcomes.NoPlay): attempts+=1
#if(gambleStatus==GambleOutcomes.NoPlay):
#print("P",randPlayer,"did not play this round,",i)
if(gambleStatus==GambleOutcomes.Won): #if player won
print("P",randPlayer, "won round",i,"after",attempts,"attempts")
bankHoldings += currentPot
currentPot = 5 #start next round with $5
roundWon = True
break
for p in players:
p.updateHistory()
bankHoldingHistory.append(bankHoldings)
currRound+=1
for p in players:
p.printHistory()
rounds = np.arange(currRound+1)
plt.figure()
for p in players:
plt.plot(rounds, p.holdingHistory)
plt.plot(rounds, bankHoldingHistory, label='Bank Holdings')
plt.xlabel("Round number")
plt.ylabel("Current $ owned")
title = "Holdings over rounds for "+str(numPlayers)+" players"
plt.title(title)
plt.legend()
finalHoldings = []
for p in players:
finalHoldings.append(p.currentHoldings)
plt.figure()
logbins = np.geomspace(min(finalHoldings), max(finalHoldings), 10)#split into 20 bins
plt.hist(finalHoldings, bins=logbins)
plt.xscale('log')
plt.ylabel("number of players owning amount")
plt.xlabel("final $ owned")
plt.title("Final holdings")
plt.show()
|
4c9029512a3446a50058a0d7099b71cfb3ad2574 | kKunov/Haskel_exam | /03-NameMatching.py | 1,786 | 3.90625 | 4 | def get_known_m_f():
known_m_f = [0, 0]
known_m_f[0] = input("Males names: ")
known_m_f[1] = input("females names: ")
known_m_f[0] = int(known_m_f[0]) # Tuk gi preobrazuvam za da moga
known_m_f[1] = int(known_m_f[1]) # sled tova da gi polzvam bez da go pravq
return known_m_f
def helper_get_names():
name = input("Input Name or 'no' for no more names: ")
is_ends_with_correct = (
name == 'no' or
name.endswith('ss') or
name.endswith('tta')
)
while is_ends_with_correct is False:
name = input("Its not valid name, try again:")
is_ends_with_correct = (
name == 'no' or
name.endswith('ss') or
name.endswith('tta')
)
return name
def get_names():
names = []
names.append(helper_get_names())
while names[len(names) - 1] != 'no':
names.append(helper_get_names())
names.pop() # tuk pop-vam posledniq element za da e po-chist
# masiva zashtoto realno posledniq element e "no"
return names
def name_maching(known_m_f, names):
num_males = 0
num_females = 0
for name in names:
if name.endswith('ss'):
num_males += 1
elif name.endswith('tta'):
num_females += 1
unknown_males = num_males - known_m_f[0]
unknown_females = num_females - known_m_f[1]
male_percentage = 1 / unknown_males
female_percentage = 1 / unknown_females
print("%s %s" % (male_percentage, female_percentage,))
percentage = 1 * male_percentage * female_percentage
percentage *= 100
print("%s percent" % (percentage,))
def main():
known_m_f = get_known_m_f()
names = get_names()
name_maching(known_m_f, names)
if __name__ == '__main__':
main()
|
e06f5970d225977b18877e7c40cbc04cc748aa09 | cvtorrisi93/cp1404practicals | /prac_04/list_exercises.py | 1,181 | 3.9375 | 4 | """
CP1404/CP5632 Practical - Christian Torrisi
List exercises
"""
USERNAMES = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn',
'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob']
def main():
numbers = get_numbers()
print_number_outputs(numbers)
username = input("Username: ")
check_username_access(username)
def check_username_access(username):
"""Check if user input matches any element in USERNAMES list"""
if username in USERNAMES:
print("Access granted")
else:
print("Access denied")
def print_number_outputs(lst):
print("The first number is {}".format(lst[1]))
print("The last number is {}".format(lst[-1]))
print("The smallest number is {}".format(min(lst)))
print("The largest number is {}".format(max(lst)))
print("The average of numbers is {}".format(sum(lst) / len(lst)))
def get_numbers(x=5):
"""Gets numbers based on above parameter from the user"""
numbers = []
for i in range(x):
number = int(input("Number: "))
numbers.append(number)
return numbers
main()
|
c5812e210bf7b92a7f46b90edab07feef8cc9fa1 | cvtorrisi93/cp1404practicals | /prac_03/scores.py | 1,118 | 4.0625 | 4 | """
CP1404/CP5632 - Practical
Scores program to determine what the score is based on value
"""
import random
MIN_SCORE = 0
MAX_SCORE = 100
def main():
output_file = open("results.txt", 'w')
number_of_scores = get_valid_integer("Enter a number of scores to generate: ")
for i in range(number_of_scores):
score = get_random_score()
result = determine_score(score)
print("{} is {}".format(score, result), file=output_file)
def get_random_score():
"""Produces a random int between the minimum and maximum score"""
score = random.randint(MIN_SCORE, MAX_SCORE)
return score
def get_valid_integer(prompt):
"""Get valid integer from user"""
valid_input = False
while not valid_input:
try:
number = int(input(prompt))
valid_input = True
except ValueError:
print("Error: not a valid integer")
return number
def determine_score(score):
"""Computes the score"""
if score >= 90:
return "Excellent"
elif score >= 50:
return "Passable"
else:
return "Bad"
main()
|
228c27b3406c45f10f3df2588de29e1d4ad5bfcb | AjayHao/helloPy | /demos/basic/list.py | 684 | 4.21875 | 4 | #!/usr/bin/python3
# 元祖
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7, 8]
# 随机读取
print ("list1[0]: ", list1[0])
print ("list1[-2]: ", list1[-2])
print ("list2[1:3]: ", list2[1:3])
print ("list2[2:]: ", list2[2:])
# 更新
list1[2] = '123'
print ("[update] list1: ", list1)
# 删除
del list1[2]
print ("[del] list1: ", list1)
# 操作符
print ("[len()] list1: ", len(list1))
print ("list1 + list2: ", list1 + list2)
print ("list1 * 2: ", list1 * 2)
print ("2000 in list1: ", 2000 in list1)
for x in list1: print(x, end=" ")
print()
print(1 not in list2)
# 列表数组转换
tuple = tuple(list2)
print(tuple) |
a97267baf084e7e54bc75706b82fe02fcbe7f519 | AjayHao/helloPy | /demos/designpatterns/creational/singleton_pattern.py | 301 | 3.59375 | 4 | class Singleton:
def __init__(self):
pass
def __new__(cls):
if not hasattr(Singleton, "__instance"):
Singleton.__instance = super(Singleton, cls).__new__(cls)
return Singleton.__instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1, obj2) |
3551929bd1814c20eca69cbb80290d2ff8de8372 | chaksamu/python | /venv/binarysearch.py | 442 | 3.609375 | 4 | pos=-1
def search(list,s):
l=0
u=len(list)-1
print(l,u)
while l<=u:
mid=(l+u) // 2
print(mid)
if list[mid]==s:
globals()['pos']=mid
return True
else:
if list[mid] < s:
l=mid+1
else:
u=mid-1
return False
list=[1,2,3,4,5,6,7,8,9,10,11]
s=11
if search(list,s):
print("Found",pos)
else:
print("NotFound") |
7a5473750801417f14ab6605e911b5d5765d04b7 | chaksamu/python | /venv/multithreads.py | 486 | 3.90625 | 4 | from time import sleep
from threading import *
class Hello(Thread):
def run(self): #run is default method
for i in range(5):
print("Hello")
sleep(1)
t1=Hello()
#t1.run()
t1.start()
sleep(0.5)
class Hi(Thread):
def run(self):
for i in range(5):
print("Hi")
sleep(1)
t2=Hi()
#t2.run()
t2.start()
t1.join() #Join will tell to main thread wait till completion of t1 and t2 thread.
t2.join()
print("By1") |
477250d187e782933186cb9bf8b3b4e6a9ece45c | chaksamu/python | /venv/calendar.py | 595 | 3.90625 | 4 | import calendar
for month in calendar.month_name:
print(month)
for month in calendar.day_name:
print(month)
for month in calendar.day_name:
print(month)
c=calendar.TextCalendar(calendar.SUNDAY)
str=c.formatmonth(2025,12)
print(str)
c = calendar.TextCalendar(calendar.TUESDAY)
str = c.formatmonth(2025, 2)
print(str)
c = calendar.HTMLCalendar(calendar.TUESDAY)
str = c.formatmonth(2025, 2)
print(str)
c = calendar.TextCalendar(calendar.TUESDAY)
for i in c.itermonthdays(2025,4):
print(i)
for month in range (1,13):
mycal=calendar.monthcalendar(2025,month)
print(mycal) |
b8ad231bf1e687ee05105ea6440ed20c9f263f6f | chaksamu/python | /venv/classinsideclass.py | 711 | 3.8125 | 4 | class Student:
def __init__(self,name,rollno):
self.N = name
self.R = rollno
self.L = self.Laptop()
def show(self):
print(self.N,self.R)
self.L.show()
class Laptop:
def __init__(self):
self.brand = 'hp'
self.cpu = 'i8'
self.ram = 20
#print(self.brand)
#print(self.cpu)
def show(self):
print(self.brand, self.cpu, self.ram)
s1=Student('chakri',1)
s2=Student('chandu',2)
print(s1.N,s1.R)
print(s2.N,s2.R)
s1.show()
s2.show()
#one way
s1.L.brand
s2.L.cpu
#other way
l1=s1.L
l2=s2.L
print(l1.cpu)
print(l2.ram)
print(id(l1))
print(id(l2))
lap1 = Student.Laptop()
|
35d4105326e91ac51680a7a0d7e50d17a87c79d9 | chaksamu/python | /venv/loops.py | 594 | 3.921875 | 4 | #While
def main():
x=0
while (x<=5):
print(x)
x=x+1
#print(x)
main()
#For
def main():
x=0
for x in range(2,7):
print("The ",x)
main()
def main():
Months={"Jan", "Feb", "Mar"}
for i in Months:
print(i)
main()
#break
def main():
y={1,2,3,4,5,6,7,8,9,10}
for x in y:
if(x==5):
#break
continue
print(x)
else:
print(x)
main()
def main():
Months={"Jan", "Feb", "Mar", "Apr", "May"}
for i, m in enumerate(Months):
print(i,m)
# print(z)
main()
|
227ace258237b03dd4bb000ad3b4abec216c656b | chaksamu/python | /venv/bubblesort.py | 305 | 3.828125 | 4 | def sort(nums):
print(nums)
for i in range(len(nums)-1,0,-1):
for j in range(i):
if nums[j]>nums[j+1]:
t=nums[j]
nums[j]=nums[j+1]
nums[j+1]=t
print(nums)
#print(nums)
nums=[6,5,4,3,2,1]
sort(nums)
#print(nums)
|
a547e08af1445d7aa9f2ff0d95fc66d9f2a8c9db | chaksamu/python | /venv/steps/liststeps3.py | 271 | 3.609375 | 4 | name=str(input("Enter the Filename: "))
f=open(name,'r')
#ff=f.read()
#print(ff)
#gg=(ff.split())
#print(gg)
for line in f:
if not line.startswith('From'):
continue
tt=line.split()
print(tt[1])
yy=tt[1]
zz=yy.split('@')
print(zz)
#4:13:00
|
e99b2ad952745f289c6e8e19ac756e975092606c | Akshay1997a/Python-Datastructure | /LinkedList.py | 1,841 | 4 | 4 | from os import system
def cls():
system('clear')
class Node:
def __init__(self, val):
self.data = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def addNode(self, list):
for i in list:
if self.head == None:
self.head = Node(i)
else:
temp = self.head
while(temp.next):
temp = temp.next
temp.next = Node(i)
def deleteNode(self, node, val):
if node == None:
print('Value not found')
return False
if self.head.data == val:
self.head = self.head.next
else:
if node.data == val:
return node.next
else:
temp = self.deleteNode(node.next, val)
if temp != False:
node.next = temp
return False
return False
def printNode(self, node):
if node != None:
print(str(node.data), end=' ')
self.printNode(node.next)
cls()
ll = LinkedList()
while(True):
print()
print('...................Linked List........................')
print('1 - Add list')
print('2 - Delete Node')
print('3 - Print List')
print('4 - Clear console')
print('5 - exit')
x = int(input('Enter your feedback :: '))
if (x == 1):
ll.addNode([int(x) for x in input('Enter List :: ').split(' ')])
print('current list :: ', end='')
ll.printNode(ll.head)
elif (x == 2):
ll.deleteNode(ll.head, int(input('Enter value: : ')))
print('current list :: ', end='')
ll.printNode(ll.head)
elif (x == 3):
ll.printNode(ll.head)
elif (x == 4):
cls()
else:
break
|
faf4ef2dab7840dfe0c778377e4998fa951ab988 | quynhhgoogoo/Artificial-Intelligence | /lectures/n-grams/ngrams.py | 1,105 | 3.625 | 4 | from collections import Counter
import math
import nltk
import os
import sys
nltk.download('punkt')
def main():
'''Calculate top term frequencies for a corpus of documents'''
if len(sys.argv) != 3:
sys.exit("Usage: python ngrams.py n corpus")
print("Loading data...")
# Loading input
n = int(sys.argv[1])
corpus = load_data(sys.argv[2])
# Compute n-grams
ngrams = Counter(nltk.ngrams(corpus, n))
# Print most common n-grams
for ngram, freq in ngrams.most_common(10):
print(f"{freq}: {ngram}")
def load_data(directory):
contents = []
# Read all files and extract words
for filename in os.listdir(directory):
with open(os.path.join(directory, filename)) as f:
# Convert all the words to lower case
# For all the words which are characters
contents.extend([
word.lower() for word in
nltk.word_tokenize(f.read())
if any (c.isalpha() for c in word)
])
return contents
if __name__ == "__main__":
main() |
1d2d81b28514c9d02774bab739dff207a7e619f0 | nixeagle/euler | /2/flare183.py | 265 | 3.53125 | 4 | def fib():
x,y = 0,1
while True:
yield x
x,y = y, x+y
def even(seq):
for number in seq:
if not number % 2:
yield number
def problem(seq):
for number in seq:
if number > 4000000:
break
yield number
print sum(even(problem(fib()))) |
4646413619e71320a217116999fa2ba6fc4e7992 | ZanderBE/Fill-in-the-Blank-Quiz | /Final-Version-Fill-In-The-Blank-Quiz.py | 7,241 | 3.71875 | 4 | guessCounter = 5
guessIndex = 0
outOfLives = 0
blankList = ["BLANK1", "BLANK2", "BLANK3", "BLANK4"]
promptList = ['What do you think fills "BLANK1"? ',
'What do you think fills "BLANK2"? ',
'What do you think fills "BLANK3"? ',
'What do you think fills "BLANK4"? ']
easyMode ='''
[EASY MODE]The current problem reads: Twenty BLANK1 from now you will be more BLANK2 by the things that you BLANK3 do than by the ones you BLANK4 do.
'''
easyList = ["years", "dissapointed", "didn't", "did"]
mediumMode ='''
[MED. MODE]The current problem reads: I'm a BLANK1 today because I had a BLANK2 who BLANK3 in me and I didn't have the BLANK4 to let him down.
'''
mediumList = ["success", "friend", "believed", "heart"]
hardMode = '''
[HARD MODE]The current problem reads: It is BLANK1 to escape the BLANK2 that people commonly use false standards of measurement - that they seek power, success and BLANK3 for themselves and admire them in others, and that they underestimate what is of true BLANK4 in life.
'''
hardList = ["impossible", "impression", "wealth", "value"]
def show_intro():
"""This function will show the user tips on how to get started with the quiz and select difficulty"""
print("""
Welcome to my Quiz! Please select your difficulty from below:
Easy Peezy Lemon Squeezy - Type: Easy
You Can Probably Handle This... Maybe - Type: Medium
Almost Impossible - Type: Hard
**You will get 5 guesses per blank regardless of difficulty
""")
def difficulty_selector():
"""
This function will prompt the user to select a difficulty out of the available choices.
Input:
The user selects between "easy", "medium" or "hard."
Behavior:
Once user has selected the difficulty it will assign the difficulty and answers based
on that choice.
Return:
This function will return the difficulty and answer variables for question_prompter().
"""
answer_choices = ["easy","medium", "hard"]
new_answer = raw_input("Please feel free to type your answer here: ").lower()
while new_answer not in answer_choices:
print("That's not a valid answer! Please select from Easy, Medium or Hard.")
new_answer = raw_input("Please feel free to type your answer here: ").lower()
if new_answer == "easy":
difficulty = easyMode
answers = easyList
elif new_answer == "medium":
difficulty = mediumMode
answers = mediumList
elif new_answer == "hard":
difficulty = hardMode
answers = hardList
return question_prompter(difficulty, answers, guessIndex)
def question_prompter(difficulty, answers, guessIndex):
"""
This function will prompt the user to guess for the current BLANK.
Input:
The user will input their guess for the corresponding BLANK.
Behavior:
This will ask the user for a guess based on the guessIndex to correspond with correct prompt
Return:
This function will return the new_answer through the answer_checker to check users response.
"""
global guessCounter
print(difficulty)
while guessCounter > outOfLives:
new_answer = raw_input(promptList[guessIndex]).lower()
return answer_checker(new_answer, answers, difficulty)
def answer_checker(new_answer, answers, difficulty):
"""
This function will check the users response against the correct answers.
Input:
This will receive the users newest response as well as the current answer list and difficulty.
Behavior:
Loop through each correct answer and check if the newest response matches the current answer.
If there is a match, move the guessIndex to the next prompt
check game_status in case game is over
reset the guess counter
If there is no match, remove a guess
check game_status in case game is over
alert user of incorrect response and remaining guesses, if any.
Return:
This function will return the question_prompter with either the same guessIndex (response was wrong) or new guessIndex (response was correct).
"""
global guessIndex
global guessCounter
for answer in answers:
if new_answer in answers:
difficulty = answer_filler(answers, difficulty)
print("That's correct!!\n")
guessIndex += 1
if guessIndex == len(answers):
return end_game(1, difficulty)
guessCounter = 5
return question_prompter(difficulty, answers, guessIndex)
else:
guessCounter -= 1
if guessCounter == outOfLives:
end_game(0, difficulty)
else:
print("Uh oh, that's incorrect! You currently have {} guesses left!\n").format(guessCounter)
return question_prompter(difficulty, answers, guessIndex)
def answer_filler(answers, difficulty):
"""
This function will add the correct answer to the problem if the user guesses correctly.
Input:
This will receive the correct answer and current difficulty problem.
Behavior:
Take difficulty and break it into a list of strings
Loop through each word in difficulty
If the word matches the current BLANK, replace it with current word from correct answer list and add to new_difficulty
remaining words can be added to new_difficulty with no change
combine new list into one string
Return:
This function will return the updated difficulty the fills correctly answered blanks
"""
global guessIndex
new_difficulty = []
difficulty = difficulty.split()
for word in difficulty:
if word == blankList[guessIndex]:
word = answers[guessIndex]
new_difficulty.append(word)
else:
new_difficulty.append(word)
new_difficulty = " ".join(new_difficulty)
return new_difficulty
def end_game(game_status, difficulty):
"""
This function will check if the game win or lose conditions have been met and end game accordingly.
Input:
This will receive the current game_status and current difficulty.
Behavior:
If answer_checker() sees that guessCounter equals outOfLives it will send a game status of 0 is sent to this function.
A game_status of 0 will end the game and print the corresponding message.
If answer_checker sees that guessIndex equals the length of the answer list a game status of 1 is sent to this function.
a game_status of 1 will end the game and print the finished problem with corresponding message
Return:
This function will end the game.
"""
if game_status == 0:
print("""
**Game Over!**
Uh oh! Looks like the last guess was incorrect and you're out of guesses now.
Better luck next time!""")
else:
print('''
Completed Quiz:
{}
You won!!! Nice Job completing that quiz!!!''').format(difficulty[38:])
def play_game():
"""This game will begin the game by showing the intro function and running the difficulty selector function."""
show_intro()
difficulty_selector()
play_game()
|
0d113719859b6ff06717d69e0bd4aee5150985ee | wrf22805656/Web-Crawler | /Scraping data - example one | 555 | 3.640625 | 4 | #! /user/bin/env python
import re
import urllib2
def download(url):
print ('downloading:' "\n", url)
try:
html = urllib2.urlopen(url).read()
except urllib2.URLError as e:
print 'Downloading error:', e.reason
html = None
return html
url = 'http://example.webscraping.com/view/United-Kingdom-239'
html = download(url)
# results = re.findall('<td class="w2p_fw">(.*?)</td>',html)
# print results
result2 = re.findall('<td class="w2p_fw">(.*?)</td>',html)[1]
print result2
|
aeed9a1fecdf64c15fed3310d68fc54cfb839475 | trallorc/Steev | /Moshe Sharat/hexmap/Render.py | 7,712 | 3.640625 | 4 | from abc import ABCMeta, abstractmethod
import pygame
import math
from Map import Grid
SQRT3 = math.sqrt(3)
class Render(pygame.Surface):
__metaclass__ = ABCMeta
def __init__(self, map, radius=16, *args, **keywords):
self.map = map
self.radius = radius
# Colors for the map
self.GRID_COLOR = pygame.Color(50, 50, 50)
super(Render, self).__init__((self.width, self.height), *args, **keywords)
self.cell = [(.5 * self.radius, 0),
(1.5 * self.radius, 0),
(2 * self.radius, SQRT3 / 2 * self.radius),
(1.5 * self.radius, SQRT3 * self.radius),
(.5 * self.radius, SQRT3 * self.radius),
(0, SQRT3 / 2 * self.radius)
]
@property
def width(self):
return math.ceil(self.map.cols / 2.0) * 2 * self.radius + \
math.floor(self.map.cols / 2.0) * self.radius + 1
@property
def height(self):
return (self.map.rows + .5) * self.radius * SQRT3 + 1
def get_surface(self, ( row, col )):
"""
Returns a subsurface corresponding to the surface, hopefully with trim_cell wrapped around the blit method.
"""
width = 2 * self.radius
height = self.radius * SQRT3
top = (row - math.ceil(col / 2.0)) * height + (height / 2 if col % 2 == 1 else 0)
left = 1.5 * self.radius * col
return self.subsurface(pygame.Rect(left, top, width, height))
# Draw methods
@abstractmethod
def draw(self):
"""
An abstract base method for various render objects to call to paint
themselves. If called via super, it fills the screen with the colorkey,
if the colorkey is not set, it sets the colorkey to magenta (#FF00FF)
and fills this surface.
"""
color = self.get_colorkey()
if not color:
magenta = pygame.Color(255, 0, 255)
self.set_colorkey(magenta)
color = magenta
self.fill(color)
# Identify cell
def get_cell(self, ( x, y )):
"""
Identify the cell clicked in terms of row and column
"""
# Identify the square grid the click is in.
row = math.floor(y / (SQRT3 * self.radius))
col = math.floor(x / (1.5 * self.radius))
# Determine if cell outside cell centered in this grid.
x = x - col * 1.5 * self.radius
y = y - row * SQRT3 * self.radius
# Transform row to match our hex coordinates, approximately
row = row + math.floor((col + 1) / 2.0)
# Correct row and col for boundaries of a hex grid
if col % 2 == 0:
if y < SQRT3 * self.radius / 2 and x < .5 * self.radius and \
y < SQRT3 * self.radius / 2 - x:
row, col = row - 1, col - 1
elif y > SQRT3 * self.radius / 2 and x < .5 * self.radius and \
y > SQRT3 * self.radius / 2 + x:
row, col = row, col - 1
else:
if x < .5 * self.radius and abs(y - SQRT3 * self.radius / 2) < SQRT3 * self.radius / 2 - x:
row, col = row - 1, col - 1
elif y < SQRT3 * self.radius / 2:
row, col = row - 1, col
return (row, col) if self.map.valid_cell((row, col)) else None
def fit_window(self, window):
top = max(window.get_height() - self.height, 0)
left = max(window.get_width() - map.width, 0)
return (top, left)
class RenderUnits(Render):
"""
A premade render object that will automatically draw the Units from the map
"""
def __init__(self, map, *args, **keywords):
super(RenderUnits, self).__init__(map, *args, **keywords)
if not hasattr(self.map, 'units'):
self.map.units = Grid()
def draw(self):
"""
Calls unit.paint for all units on self.map
"""
super(RenderUnits, self).draw()
units = self.map.units
for position, unit in units.items():
surface = self.get_surface(position)
unit.paint(surface)
class RenderGrid(Render):
def draw(self):
"""
Draws a hex grid, based on the map object, onto this Surface
"""
super(RenderGrid, self).draw()
# A point list describing a single cell, based on the radius of each hex
for col in range(self.map.cols):
# Alternate the offset of the cells based on column
offset = self.radius * SQRT3 / 2 if col % 2 else 0
for row in range(self.map.rows):
# Calculate the offset of the cell
top = offset + SQRT3 * row * self.radius
left = 1.5 * col * self.radius
# Create a point list containing the offset cell
points = [(x + left, y + top) for (x, y) in self.cell]
# Draw the polygon onto the surface
pygame.draw.polygon(self, self.GRID_COLOR, points, 1)
class RenderFog(Render):
OBSCURED = pygame.Color(00, 00, 00, 255)
SEEN = pygame.Color(00, 00, 00, 100)
VISIBLE = pygame.Color(00, 00, 00, 0)
def __init__(self, map, *args, **keywords):
super(RenderFog, self).__init__(map, *args, flags=pygame.SRCALPHA, **keywords)
if not hasattr(self.map, 'fog'):
self.map.fog = Grid(default=self.OBSCURED)
def draw(self):
# Some constants for the math
height = self.radius * SQRT3
width = 1.5 * self.radius
offset = height / 2
for cell in self.map.cells():
row, col = cell
surface = self.get_cell(cell)
# Calculate the position of the cell
top = row * height - offset * col
left = width * col
# Determine the points that corresponds with
points = [(x + left, y + top) for (x, y) in self.cell]
# Draw the polygon onto the surface
pygame.draw.polygon(self, self.map.fog[cell], points, 0)
def trim_cell(surface):
pass
if __name__ == '__main__':
from Map import Map, MapUnit
import sys
class Unit(MapUnit):
color = pygame.Color(200, 200, 200)
def paint(self, surface):
radius = surface.get_width() / 2
pygame.draw.circle(surface, self.color, (radius, int(SQRT3 / 2 * radius)), int(radius - radius * .3))
m = Map((5, 5))
grid = RenderGrid(m, radius=32)
units = RenderUnits(m, radius=32)
fog = RenderFog(m, radius=32)
m.units[(0, 0)] = Unit(m)
m.units[(3, 2)] = Unit(m)
m.units[(5, 3)] = Unit(m)
m.units[(5, 4)] = Unit(m)
for cell in m.spread((3, 2), radius=2):
m.fog[cell] = fog.SEEN
for cell in m.spread((3, 2)):
m.fog[cell] = fog.VISIBLE
print(m.ascii())
try:
pygame.init()
fpsClock = pygame.time.Clock()
window = pygame.display.set_mode((640, 480), 1)
from pygame.locals import QUIT, MOUSEBUTTONDOWN
# Leave it running until exit
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
print(units.get_cell(event.pos))
window.fill(pygame.Color('white'))
grid.draw()
units.draw()
fog.draw()
window.blit(grid, (0, 0))
window.blit(units, (0, 0))
window.blit(fog, (0, 0))
pygame.display.update()
fpsClock.tick(10)
finally:
pygame.quit()
|
7c3a1cf25c041f0212a7764e4aad57abecf7f9bf | kanglicheng/GoogleCodeJam | /2019/Qualification/B/b.py | 263 | 3.59375 | 4 | def solve():
N = int(input())
S = input()
ans = ""
for c in S:
ans += "E" if c == "S" else "S"
return ans
if __name__ == "__main__":
T = int(input())
for t in range(1, T + 1):
print("Case #{}: {}".format(t, solve()))
|
7dbb6ceb733fa90b5f1cc5ab5521cffaf24d7c0f | ryanmcfarland/file-tk-downloader | /classes/reqdl.py | 937 | 3.5625 | 4 | import requests
import os
import sys
import urllib3
class RequestFile:
def __init__(self, dir="", filename="", url=""):
self.dir = dir
self.filename = filename
self.url = url
## --> check if the directory exists
def check_dir_exists(self):
if not os.path.exists(self.filepath):
os.makedirs(self.filepath)
## --> create full filename
def generate_filename(self):
return self.dir + "/" + self.filename
## --> return the full filepath of the file
def return_filepath(self):
self.filepath = self.generate_filename()
return self.filepath
def download_file(self):
r = requests.get(self.url, stream = True)
with open(self.filepath, "wb") as fileDownload:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
fileDownload.write(chunk)
return "Success" |
a66405eeea9904f8c4967a7789bc6a4841713f24 | anumulaphani/nodejs-application | /sales enhancement.py | 255 | 3.796875 | 4 | sales = float(input("Enter sales: $"))
while sales <= 0:
print("Invalid option")
sales = float(input("Enter sales: $"))
if sales < 1000:
bonus = sales * 0.1
print(bonus)
else:
bonus = sales * 0.15
print(bonus)
print("good bye") |
fcf2d76ad0f3015988ae7b445870405ac0e2e668 | anumulaphani/nodejs-application | /practicals 2/practicals_3/value_error.py | 436 | 4.0625 | 4 | def get_num(lower, upper):
while (True):
try:
user_input = int(input("Enter a number ({}-{}):".format(lower, upper)))
if user_input < lower:
print("Number too low.")
elif user_input > upper:
print("please enter a valid number")
else:
return user_input
except ValueError:
print("Please enter a valid number") |
977529bdb4da2c8b6a0a7d5749b57dca59ece90c | Wormandrade/Trabajo01 | /eje02.py | 358 | 4.03125 | 4 | #Calcular el perímetro y área de un círculo dado su radio.
print("========================")
print("\tEJERCICIO 02")
print("========================")
print("Cálculo de périmetro y área de un círculo\n")
radio = float(input("Ingrese el radio: \n"))
pi=3.1416
print("El perímetro es: ",round(radio*pi,2))
print("El área es: ",round(radio*radio*pi,2)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.