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 |
|---|---|---|---|---|---|---|
fc4f16786713f1bcc5710e70591ee3093b10e2ec | djohnson67/sPython3rd | /math/io/strip_newline.py | 512 | 3.875 | 4 | #reads file oneline at a time and strips \n from it
def main():
infile = open('philosophers.txt','r')
#read 3 lines
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
#striup \n from each line
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')
#close it
infile.close()
#print the data from mem
print(line1)
print(line2)
print(line3)
#call the main function
main() |
e0c4c2ea0fd3efd52e138b92ec59d3e98c668ad9 | djohnson67/sPython3rd | /math/io/read_sales.py | 457 | 3.6875 | 4 | #reads values from sales.txt
def main():
#opemn sales
sales_file = open('sales.txt','r')
#read first line then test for empty string ''
line = sales_file.readline()
#continue until empty string
while line != '':
#convert to float
amount = float(line)
#print line
print(format(amount, '.2f'))
line = sales_file.readline()
#close file
sales_file.close()
main() |
8958ab69502d9caf3f359c6e61d08bb2e032404c | djohnson67/sPython3rd | /Classes/account_test.py | 819 | 4 | 4 | import bankaccount
def main():
#get starting balan
start_balance = float(input('Enter starting balance: '))
#create account
savings = bankaccount.BankAccount(start_balance)
#deposit check
pay = float(input('How much were you paid this week? '))
print('I will deposit this into your account')
savings.deposit(pay)
#display balance
print('Your account balance is $', format(savings.get_balance(), ',.2f'), sep='')
#withdraw some cash
cash = float(input('How much would you like to withdraw? '))
print('I will withdraw that from your account')
savings.withdraw(cash)
#display balance
print('Your account balance is $', format(savings.get_balance(), ',.2f'), sep='')
#test print function
print(savings)
main()
|
3c666ec9ea6dc2435257a4ac90ea0a117e8f70a9 | djohnson67/sPython3rd | /loan_qual2.py | 443 | 4.0625 | 4 | #determine if bank customer qualifies for loan
min_salary = 30000.0
min_years = 2
#get customers annual salary
salary = float(input('Enter annual salary: '))
#get number of yars on job
years_on_job = int(input('Enter number of years employed: '))
#determine if customer qualifes
if salary >= min_salary and years_on_job >= min_years:
print('you qualify for the loan')
else:
print('You do not qualify for the loan') |
6194f3cadc0f1cccb768aa17d523b8e8448cc9c8 | berkercaner/pythonTraining | /Chap12/copy-text.py | 710 | 3.78125 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
def main():
infile = open('lines.txt', 'rt') #it's default rt but better to specify
outfile = open('lines-copy.txt', 'wt')
for line in infile:
print(line.rstrip(), file=outfile)
#outfile.writelines(line) ==> it'll work the same way but print function dealing line endings by default.
#so print is more useful
print('.', end='', flush=True) #for make a little progress bar #flush is flushes the output buffer
#end='' is for printing in same line, not to the next line
outfile.close()
infile.close()
print('\ndone.')
if __name__ == '__main__': main()
|
0c9567b722911116f27ed17fbc1129e8d900342f | berkercaner/pythonTraining | /Chap08/dict.py | 1,565 | 4.25 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# it's like hash map in C
# each pair seperated by ',' and left of the pair is 'key'
# right of the pair is 'value'
def main():
#one way of creating dictionary
animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': 'grrr',
'giraffe': 'I am a giraffe!', 'dragon': 'rawr' }
#other way of creating dictionary and it's more readable
animals_2 = dict(kitten = 'meow', puppy = 'ruff!', lion = 'grrr',
giraffe = 'I am a giraffe!', dragon = 'rawr')
print_dict(animals)
print()
print_dict(animals_2)
#changing a key's value
print()
animals_2['lion'] = "i am a lion"
print_dict(animals_2),
#adding an elemet
print()
animals_2['monkey'] = "lol!"
print_dict(animals_2)
#using dict methods
print()
for k in animals_2.keys(): # in sequence of keys
print(k)
print()
for v in animals_2.values(): #in sequence of values
print(v)
print()
for z,y in animals_2.items(): #in sequene of items
print("{} says {}".format(z,y))
print()
print('lion' in animals_2) #returns true or false
print('found!' if 'lion' in animals_2 else 'nope!') #basic conditional expression with print
print()
#getting value from the key if key is not exists returns none
print(animals_2.get('lion'))
print(animals_2.get('levy'))
def print_dict(o):
for x in o: print('{}: {}'.format(x,o[x]))
if __name__ == '__main__': main()
|
c25f095d3e297cd7467d0beed372077007d86ab6 | berkercaner/pythonTraining | /Chap02/while.py | 384 | 3.671875 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
words = ['one', 'two', 'three', 'four', 'five']
n = 0
while(n < 5):
print(words[n])
n += 1
while 1:
try:
val = int(input("Enter pass: "))
if val == 321332:
print('successful')
break
print("try again")
except:
print("not a valid number") |
999462110e3248e304b4974f9d966ba5b0ff42bc | yuumi001/miniCTF2021_deploy | /crypto/history/source/chall.py | 3,546 | 3.703125 | 4 | from Crypto.Util.number import getRandomInteger
from string import *
import time
def stage1(): #caesar box
print('\n\n\n***\nFirst Stage: Written test')
intro = '\nGiven a ciphertext encrypted using the Roman method of cryptography...\n\n\n'
print(intro)
time.sleep(3)
# challenge
print('My ciphertext:\n')
m = 'Developed around 100 BC, not until 9th-century, Caesar cipher was cracked with the discovery of frequency analysis.'
key = getRandomInteger(2) % 13 + 7 # range 7 - 26
# encrypt
upper = ascii_uppercase
lower = ascii_lowercase
c = ''
for ch in m:
if ch in upper:
c += upper[(upper.index(ch) + key) % 26]
elif ch in lower:
c += lower[(lower.index(ch) + key) % 26]
else:
c += ch
print(c)
buf = input('\n\n\nWhat is the messages?\n\n')
time.sleep(1)
# if pass
if buf == m:
print(
'\n\n\nYou are qualified to the Second Stage!'
)
else:
print('\n\n\nFailed! You are disqualified!')
exit(-1)
def stage2():
print('\n\n\n***\nSecond Stage: Forest of Death')
intro = '\nYou have to bring your team\'s Scroll to the Building whose position is encrypted by an ancient Greek technique...\n\n\n'
print(intro)
time.sleep(3)
# challenge
print('My ciphertext:\n')
m = 'Located_at_port_2026_encrypted_by_Scytale'
# encrypt
chrs = getRandomInteger(1) + 3 #max chars per lap in range 3 - 7
c = ''
rounds = (len(m) + chrs - 1) // chrs
pad = rounds * chrs - len(m) #padding
for ch in range(pad):
m += ' '
for lap in range(rounds):
for ch in range(chrs):
c += m[ch * rounds + lap]
print(c)
buf = input('\n\n\nWhat is the messages?\n\n')
time.sleep(1)
# if pass
m = m.replace(' ', '')
if buf == m:
print(
'\n\n\nYou are qualified to the Final Stage!'
)
else:
print('\n\n\nFailed! You are disqualified!')
exit(-1)
def stage3():
print('\n\n\n***\nFinal Stage: Team Fight')
intro = '\nThe key of teamwork in a fight is to communicate secretly.\nThis was created at the end of the First World War in German.\n\n\n'
print(intro)
time.sleep(3)
# challenge
m = 'enigmaisformilitarycommunication'
# encrypt
print('Your team using this machine:\n')
print('_________________________________________________________________\n')
print('Machine: Enigma M3, reflector UKW B')
print('Rotor - Position - Ring: III - 9 - 3, II - 19 - 20, VI - 16 - 6 ')
print('Plugboard: dq cr bi ej kw mt os px uz gh')
print('_________________________________________________________________')
print('\n\n\nMy ciphertext:')
c = 'renoy begxr bczov ukkrg uasgc pkyjw sb'
print(c)
buf = input('\n\n\nWhat is the messages? (remove spaces)\n\n')
time.sleep(1)
# if pass
if buf == m:
print('\n\n\nPTITkagure proud of you as a new Chuunin!')
else:
print(
'\n\n\nYou are not gonna pass the Chuunin exam like this. Give up!'
)
exit(-1)
def main():
intro = 'Cryptography is the science of secrets.\nA proper Chuunin knows how important crypto is!'
print(intro)
time.sleep(2)
stage1()
time.sleep(3)
stage2()
time.sleep(3)
stage3()
time.sleep(0.5)
print(
'New S-rank Hiden Jutsu to you from ISP Ichizoku: ISPCLUB{s3cr3t_pr0t3ct0r}'
)
if __name__ == '__main__':
main()
|
ae6767f12a250449a4c1998b2c69058b9e90c5cd | Viniciusvaz77/Python-tests | /exs/fizzbuzz.py | 114 | 3.890625 | 4 | nmr= int(input("insira o número: "))
if nmr%5==0 and nmr%3==0:
print("FizzBuzz")
else:
print(nmr)
|
95cfff552392d91d7efa26b15beb7ce376547bad | hadesfranklyn/ProvaAb2EstruturaDeDadosPython | /Prova/q2.py | 1,002 | 3.703125 | 4 | class Pilha:
topo = None
tamanho = None
itens = None
def __init__(self,tamanho):
self.tamanho = tamanho
self.topo = 0
self.itens = [None] * tamanho
def estaVazia(self):
return True if self.topo == 0 else False
def estaCheia(self):
return True if self.topo == self.tamanho else False
def empilhar(self,item):
if not self.estaCheia():
self.itens[self.topo] = item
self.topo +=1
else:
print("esta cheia")
def desempilhar(self):
if not self.estaVazia():
self.topo -=1
return self.itens[self.topo]
else:
print("esta Vazia")
def contemItem(self,item):
for i in reversed(self.itens[self.topo]):
if item == i:
return True
return False
def imprimir(self):
[print(item)for item in reversed(self.itens[:self.topo])]
print("----")
|
49c2a767536d4af386dd3a35e8f0f59163659d93 | jocke45/adventofcode2020 | /day1/expense_report.py | 1,340 | 3.96875 | 4 | def expense_report(report, debug=False):
"""
Return the product of two integers that together add to 2020
Execution time: 0,02s
"""
report.sort(reverse=True)
for x in report:
for y in range(len(report) - 1, 0, -1):
# Iterate backwards. Since the list is sorted we might
# be able to cut a lot of list entries this way
if x + report[y] == 2020:
return x * report[y]
elif x + report[y] > 2020:
break # The sum will be to big for the rest of the list
def triple_expense_report(report, debug=False):
"""
Return the product of three integers that together add to 2020
Execution time: 0,04s
Execution time w/o "backwards break" trick: 0,52s
"""
report.sort(reverse=True)
for x in range(0, len(report), 1):
for y in range(x + 1, len(report), 1):
for z in range(len(report) - 1, 0, -1):
# Iterate backwards. Since the list is sorted we might
# be able to cut a lot of list entries this way
if report[x] + report[y] + report[z] == 2020:
return report[x] * report[y] * report[z]
elif report[x] + report[y] + report[z] > 2020:
break # The sum will be to big for the rest of the list
|
0b714eba32a384c37a3775bc0f208ee2289f6b70 | jocke45/adventofcode2020 | /day5/seat_finder.py | 1,600 | 3.84375 | 4 | def row_finder(boarding_pass, row_list):
"""
Find the correct row by recursing through a boarding pass' string
use the top half of the rows for F and bottom half for B
"""
if len(row_list) == 1:
row = row_list[0]
elif boarding_pass[0] == 'F':
row = row_finder(boarding_pass[1:], row_list[:len(row_list)//2])
elif boarding_pass[0] == 'B':
row = row_finder(boarding_pass[1:], row_list[len(row_list)//2:])
return row
def column_finder(boarding_pass, col_list):
"""
Find the correct column by recursing through a boarding pass' string
use the right half of the columns for R and left half for L
"""
if len(col_list) == 1:
col = col_list[0]
elif boarding_pass[0] == 'L':
col = column_finder(boarding_pass[1:], col_list[:len(col_list)//2])
elif boarding_pass[0] == 'R':
col = column_finder(boarding_pass[1:], col_list[len(col_list)//2:])
return col
def seat_finder(boarding_passes):
"""
Find what all the seat IDs given all the boarding pass data
"""
row_list = [*range(0, 128)]
col_list = [*range(0, 8)]
seats = []
for boarding_pass in boarding_passes:
row = row_finder(boarding_pass, row_list)
column = column_finder(boarding_pass[-3:], col_list)
seats.append(row * 8 + column)
return seats
def get_my_seat(plane_seats):
"""
Get what seat ID that is not taken by comparing the taken IDs to a range
"""
start = plane_seats[0]
end = plane_seats[-1]
return set(range(start, end + 1)).difference(plane_seats)
|
1931d2374059df352e19884dd37abcfcdeecb453 | quanglam2807/cs-160 | /chapter-3-problem-1.py | 246 | 3.828125 | 4 | # Quang Lam
def intpow(x, n):
if n == 0:
return 1
else:
return x * intpow(x, n - 1)
def main():
x = int(input("Enter x: "))
n = int(input("Enter n: "))
print(intpow(x, n))
if __name__ == "__main__":
main() |
c3e84cb63894cf3833da1350ea5bde5036dcac14 | quanglam2807/cs-160 | /binary-search.py | 2,121 | 3.9375 | 4 | # Quang Lam
class OrderedList(list):
def __init__(self,contents=[]):
super().__init__(contents)
self.sorted = False
def __iter__(self):
if not self.sorted:
self.sort()
self.sorted = True
return super().__iter__()
def binarySearch(self, l, r, item):
if r >= l:
mid = int(l + (r - l) / 2)
if self.__getitem__(mid) == item:
return True
if item > self.__getitem__(mid):
return self.binarySearch(mid + 1, r, item)
if item < self.__getitem__(mid):
return self.binarySearch(l, mid - 1, item)
else:
return False
def __contains__(self,item):
if not self.sorted:
self.sort()
self.sorted = True
# replace this line with your call to your binary search function.
return self.binarySearch(0, super().__len__() - 1, item)
def append(self,item):
super().append(item)
self.sorted = False
def main():
lst = OrderedList()
print("Binary Search Program")
print("---------------------")
print("Make a choice...")
print("1. Insert into tree.")
# print("2. Delete from tree.")
print("2. Lookup value.")
choice = 0
while True:
if choice < 1:
try:
choice = int(input("Choice? "))
if choice < 1 or choice > 3:
break
except ValueError:
break
else:
if choice == 1:
try:
num = int(input("Insert? "))
lst.append(num)
except ValueError:
choice = 0
if choice == 2:
try:
num =int(input("Value? "))
if num in lst:
print("Yes,", num, "is in the tree.")
else:
print("No,", num, "is in the tree.")
except ValueError:
choice = 0
if __name__ == "__main__":
main() |
51cddfd4c599409a8da840342b8228b4d95eda8c | kacchan822/nlp100py2015 | /chapter1/section02.py | 463 | 3.5 | 4 | """
言語処理100本ノック 2015
http://www.cl.ecei.tohoku.ac.jp/nlp100/#ch1
第1章: 準備運動
02. 「パトカー」+「タクシー」=「パタトクカシーー」
「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.
"""
strings1 = 'パトカー'
strings2 = 'タクシー'
result_strings = ''.join([i+j for i,j in zip(strings1, strings2)])
print(result_strings) |
9a95a30df19a4e44d832394e8ad0f9cba941fe67 | jakedshaw/tictactoe | /player.py | 212 | 3.53125 | 4 | class Player:
"""Player Class"""
def __init__(self, name, tile, score):
"""initializes player class"""
self.name = name
self.tile = tile
self.score = score
def __str__(self):
return f'{self.name}'
|
8255173f44c84c0e835153098f8bcaa4293ca099 | iBug/pyGadgets | /object.py | 370 | 3.78125 | 4 | class Object:
"""
A simple Object class similar to JavaScript's "Object"
"""
def __init__(self):
self.__dict__['_Object__data'] = dict()
def __getattr__(self, attr):
try:
return self.__data[attr]
except KeyError:
return None
def __setattr__(self, attr, value):
self.__data[attr] = value
|
973eb1247bc6f2172c1606219a8aff516fb41567 | earthobservations/wetterdienst | /wetterdienst/util/geo.py | 3,138 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2021, earthobservations developers.
# Distributed under the MIT License. See LICENSE for more info.
from typing import Tuple, Union
import numpy as np
import polars as pl
from sklearn.neighbors import BallTree
class Coordinates:
"""Class for storing and retrieving coordinates"""
def __init__(self, latitudes: np.array, longitudes: np.array):
"""
Args:
latitudes: latitudes in degree
longitudes: longitudes in degree
"""
self.latitudes = latitudes
self.longitudes = longitudes
def get_coordinates(self) -> np.array:
"""
Returns: coordinates in degree where the first column is the latitudes
and the second column the longitudes
"""
return np.array([self.latitudes, self.longitudes]).T
def get_coordinates_in_radians(self):
"""
Returns: coordinates in radians where the first column is the latitudes
and the second column the longitudes
"""
return np.radians(self.get_coordinates())
def __eq__(self, other):
return np.array_equal(self.latitudes, other.latitudes) and np.array_equal(self.longitudes, other.longitudes)
def derive_nearest_neighbours(
latitudes: np.array,
longitudes: np.array,
coordinates: Coordinates,
number_nearby: int = 1,
) -> Tuple[Union[float, np.ndarray], np.ndarray]:
"""
A function that uses a k-d tree algorithm to obtain the nearest
neighbours to coordinate pairs
Args:
latitudes (np.array): latitude values of stations_result being compared to
the coordinates
longitudes (np.array): longitude values of stations_result being compared to
the coordinates
coordinates (Coordinates): the coordinates for which the nearest neighbour
is searched
number_nearby: Number of stations_result that should be nearby
Returns:
Tuple of distances and ranks of nearest to most distant stations_result
"""
points = np.c_[np.radians(latitudes), np.radians(longitudes)]
distance_tree = BallTree(points, metric="haversine")
return distance_tree.query(coordinates.get_coordinates_in_radians().reshape(-1, 2), k=number_nearby)
def convert_dm_to_dd(dm: pl.Series) -> pl.Series:
"""
Convert degree minutes (floats) to decimal degree
:param dm:
:return:
"""
degrees = dm.cast(int)
minutes = dm - degrees
decimals = (minutes / 60 * 100).round(2)
return degrees + decimals
def convert_dms_string_to_dd(dms: pl.Series) -> pl.Series:
"""
Convert degree minutes seconds (string) to decimal degree
e.g. 49 18 21
:param dms:
:return:
"""
dms = dms.str.split(" ").to_frame("dms")
dms = dms.select(
pl.col("dms").arr.get(0).cast(pl.Float64).alias("degrees"),
pl.col("dms").arr.get(1).cast(pl.Float64).alias("minutes"),
pl.col("dms").arr.get(2).cast(pl.Float64).alias("seconds"),
)
return dms.get_column("degrees").rename("") + dms.get_column("minutes") / 60 + dms.get_column("seconds") / 3600
|
88857ccbf8401936285a9aee2a842420dfdabc09 | nickzhq/leetcode-algorithm | /980. Unique Paths III.py | 1,485 | 3.5625 | 4 | # 980. Unique Paths III
# https://leetcode.com/problems/unique-paths-iii/
class Solution(object):
def uniquePathsIII(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
row, col = len(grid), len(grid[0])
# 迭代器,用来返回当前位置的上下左右四个方向且可访问的位置
def neighbors(r, c):
for try_r, try_c in ((r+1, c), (r-1,c), (r, c+1), (r,c-1)):
if 0 <= try_r < row and 0 <= try_c < col and grid[try_r][try_c] % 2 == 0:
yield try_r, try_c
# 遍历grid,设置TODO是多少个零,同是寻找起点和终点
todo = 0
self.sr, self.sc, self.er, self.ec = 0,0,0,0
for r, _ in enumerate(grid):
for c, val in enumerate(grid[r]):
if val != -1: todo += 1
if val == 1: self.sr, self.sc = r, c
if val == 2: self.er, self.ec = r, c
self.res = 0
def dfs(r, c, todo):
todo -= 1
if todo < 0: return
if r == self.er and c == self.ec:
if todo == 0:
self.res += 1
return
grid[r][c] = -1
for try_r, try_c in neighbors(r, c):
dfs(try_r, try_c, todo)
grid[r][c] = 0
dfs(self.sr, self.sc, todo)
return self.res
|
f7ccd4b998572138d10fc5ac96fb12310341026f | nickzhq/leetcode-algorithm | /1314. Matrix Block Sum.py | 1,918 | 3.546875 | 4 | # 1314. Matrix Block Sum
# https://leetcode.com/problems/matrix-block-sum/
# https://leetcode.com/problems/matrix-block-sum/discuss/499970/Problem-explanation-in-Python-Step-by-Step-O(m*n)-98-speed-and-100-memory
class Solution(object):
def matrixBlockSum(self, mat, K):
"""
:type mat: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
rowSum = [[0 for _ in range(len(mat[i]))] for i in range(len(mat))]
res = [[0 for _ in range(len(mat[i]))] for i in range(len(mat))]
# Compute the sum of every group in the row with a DP
# complexity: O(m*n)
for i in range(len(mat)):
for j in range(len(mat[i])):
if j > 0: # 根据公式rowSum[i][j] = rowSum[i][j-1]-a+b 只能处理当前行第二个开始的元素
a = mat[i][j-K-1] if j-K-1 >= 0 else 0 # or 0
b = mat[i][j+K] if j+K < len(mat[i]) else 0 # or 0
rowSum[i][j] = rowSum[i][j-1]-a+b
else: # 处理当前行的第一个元素
for k in range(0, min(j+K+1, len(mat[i]))):
rowSum[i][j] += mat[i][k]
# Uses the computed sum of rows to compute the sum
# of the squares with the same DP but now for columns
# complexity: O(m*n)
for i in range(len(rowSum)):
for j in range(len(rowSum[i])):
if i > 0: # 处理当前列第二个元素
a = rowSum[i-K-1][j] if i-K-1 >= 0 else 0 # or 0
b = rowSum[i+K][j] if i+K < len(rowSum) else 0 # or 0
res[i][j] = res[i-1][j]-a+b
else: # 处理当前列的第一个元素
for k in range(0, min(i+K+1, len(rowSum))):
res[i][j] += rowSum[k][j]
# total complexity: O(m*n)
return res |
e203cabf7112e41dfaeef4ef7b775c575586f740 | nickzhq/leetcode-algorithm | /122. Best Time to Buy and Sell Stock II.py | 447 | 3.546875 | 4 | # 122. Best Time to Buy and Sell Stock II
#https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for idx in xrange( 1, len(prices) ):
if prices[idx] > prices[idx - 1]:
profit += prices[idx] - prices[idx - 1]
return profit |
0f63758468e28096b1ae65115a23577b611a119b | bssrdf/ands | /ands/algorithms/sorting/integer/radix_sort.py | 9,369 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 05/03/2022
Updated: 07/03/2022
# Description
## Short Description
Radix sort is a non-comparison sorting algorithm that uses the stable
counting sort as a subroutine. The stability of counting sort is essential for
radix sort to work properly.
## Long Description
Radix-sort assumes that the given list contains integers, each of which has
a w-bit binary representation (for example, w = 32). It sorts the list by
calling w / d times the counting sort algorithm. In the first iteration, it
sorts (with counting sort) the list of integers according to the least
significant d bits of each integer. In the next iteration, it sorts according
to the next least significant d bits. This continues until the last iteration,
where the integers are sorted according to the most significant d bits.
If w / d is not an integer, we can increase w to d⌈w/d⌉, where ⌈⌉ is the
ceiling operation.
## Example
In reality, radix sort can also be applied to non-binary representations.
For example, consider 3-digit decimal numbers: for example, 356, which has 3
digits, each of which can range from 0 to 9. Now, here's an example of how
radix sort would work on a list of 3-digit decimal numbers (this example is
taken from Figure 8.3 of CLRS book, p. 198). Here's the initial list.
list.
329
457
657
839
436
720
355
We now sort these numbers according to the least significant digit, but we
maintain the same order of the numbers (as the original list above) for the
same digit. In other words, the algorithm that we use to sort these numbers
according to least significant digit is stable.
720
355
436
457
657
329
839
|
Least significant digit
You can see that the least significant digits, i.e. 0, 5, 6, 7, 7, 9, 9, are
sorted. Moreover, as in the original list, we have
- 457 comes before 657, and
- 329 comes before 839.
We now sort these numbers according to the second least significant digit, so
we obtain
720
329
436
839
355
457
657
|
Second least significant digit
You can see that the 2nd least significant digits, 2, 2, 3, 3, 5, 5, 5 are
sorted. However, note that the least significant digits are no longer sorted.
Nevertheless, note that, as in the list sorted according to the least
significant digit, we have that
- 720 comes before 329,
- 436 comes before 839,
- 355 comes before 457, and
- 457 comes before 657.
Finally, we sort the numbers according to the most significant digit, to obtain
329
355
436
457
657
720
839
|
Most significant digit
So, the most significant digits are sorted, 3, 3, 4, 4, 6, 7, 8. Moreover,
as in the list sorted according to the 2nd significant digit, we have
- 329 comes before 355, and
- 436 comes before 457.
So, in this example, we performed 3 iterations of the stable sorting algorithm,
e.g. counting sort.
## Properties
- Non-comparison (integer) sorting algorithm
## Applications
- Sort records of information that are keyed by multiple fields.
- Example: sort dates by three keys: year, month, and day.
## Terminology
- Robert Sedgewick and Kevin Wayne in their book "Algorithms" (4th edition),
section 5.1, page 706, call a version of radix-sort applied to strings
"least significant-digit first (LSD) string sort".
## TODO
- The code used for counting sort here is really very similar to the standalone
counting sort algorithm in the module counting_sort.py, so we might want to
reuse that code.
- Add time and space complexity
- Is this algorithm stable? If yes, when?
- Is it in place?
# References
- "Introduction to Algorithms" (3rd edition), by CLRS, chapter 8.3
- "Algorithms in C", R. Sedgewick, chapter 10, p. 133
- "Algorithms" (4th edition), by Robert Sedgewick and Kevin Wayne
- http://opendatastructures.org/ods-java/11_2_Counting_Sort_Radix_So.html
- https://www.youtube.com/watch?v=YXFI4osELGU
- http://www.allisons.org/ll/AlgDS/Sort/Radix/
- https://wiki.python.org/moin/BitwiseOperators
"""
__all__ = ["radix_sort"]
import sys
def lsd(a: list,
w: int = None,
# The value of k can make a big difference in performance. If we can
# assume e.g. that we're using only ASCII chars, then we know that k
# is quite small.
k: int = sys.maxunicode,
# TODO: support a more general key
# other we may need to assume that the first parameter is always a
# string (or something that we can index) and index would be the index
key: callable = lambda string, index: ord(string[index])) -> list:
"""The least-significant-digit first (LSD) string sort, which stably sorts
fixed-length strings.
This implementation is based on the pseudocode and information given in
section 5.1 of the book "Algorithms" (4th edition), by Robert Sedgewick and
Kevin Wayne.
"""
if len(a) == 0:
return []
if not isinstance(w, int):
w = len(a[0])
if w < 0:
raise ValueError("w must be >= 0")
if not all(len(x) == w for x in a):
raise ValueError("the length of each string in a should be equal to "
"w = {}".format(w))
# TODO: check correctness of key.
# TODO: check correctness of k, maybe as an assertion, because we may
# get index out of range
# TODO: support also the sort of integers (probably we need to convert them
# to strings): see CLRS.
# TODO: this is in-place, but the algorithm below is not.
n = len(a)
b = [None] * n
for d in range(w - 1, -1, -1):
# Sort by key-indexed counting on dth char.
c = [0] * (k + 1) # In the book, it's denoted by "count"
# Compute frequency counts.
for x in range(n):
c[key(a[x], d) + 1] += 1
# Transform counts to indices.
for x in range(k):
c[x + 1] += c[x]
# Distribute.
for x in range(n):
b[c[key(a[x], d)]] = a[x]
c[key(a[x], d)] += 1
# Copy back.
for x in range(n):
a[x] = b[x]
# TODO: deal with the case where w is not divisible by d; don't forget the
# test cases.
# TODO: deal with wrong values for w and d.
def radix_sort(a: list,
w: int = 32,
d: int = 2) -> list:
"""Radix-sort algorithm that sorts w-bit integers with w // d rounds of
the stable counting sort. At each round, we sort the list according to d
bits.
Time complexity
+--------------+--------------+--------------+
| Best | Average | Worst |
+--------------+--------------+--------------+
| | Θ(d*(n + k)) | Θ(d*(n + k)) |
+--------------+--------------+--------------+
"""
assert isinstance(a, list)
assert isinstance(w, int)
assert isinstance(d, int)
if not all(isinstance(x, int) for x in a):
raise TypeError("all elements of a should be integers")
if not all(x >= 0 for x in a):
raise ValueError("all elements be >= 0")
def index(x: int, p: int) -> int:
# x is an element of a
# p is the current iteration number
# (x >> d * p) & ((1 << d) - 1) is the integer whose binary
# representation is given by bits
# (p + 1) * d - 1, ..., p * d of x, where x = a[i].
#
# Example
#
# Let x = 3, d = 2 and p = 0.
# Then (x >> d * p) & ((1 << d) - 1) = (3 >> 2 * 0) & ((1 << 2) - 1) =
# (3 >> 0) & (4 - 1) = 3 & 3 = 3.
#
# Let x = 7, d = 2 and p = 1.
# Then (x >> d * p) & ((1 << d) - 1) = (7 >> 2 * 1) & ((1 << 2) - 1) =
# (7 >> 2) & (4 - 1) = 1 & 3 = 1.
return (x >> d * p) & ((1 << d) - 1)
n = len(a)
# w // d of counting sort.
for p in range(w // d):
# This block of code is an adaptation of the counting sort algorithm
# for this radix sort algorithm.
# The auxiliary counter list of size 1 << d, that is len(c) = 2^p.
k = 1 << d
c = [0] * k
for i in range(n):
c[index(a[i], p)] += 1
for i in range(1, k):
c[i] += c[i - 1]
# The result list for iteration p.
b = [None] * n
for i in range(n - 1, -1, -1):
c[index(a[i], p)] -= 1
b[c[index(a[i], p)]] = a[i]
a = b
return b
def example1():
a: list = []
b = radix_sort(a)
print(b)
a = [2]
b = radix_sort(a)
print(b)
a = [10, 2]
b = radix_sort(a)
print(b)
# a = [10, 2, -3]
# b = radix_sort(a)
# print(b)
def example2():
# Example taken from Sedgewick and Wayne's book, p. 706.
a = [
"4PGC938",
"2IYE230",
"3CIO720",
"1ICK750",
"1OHV845",
"4JZY524",
"1ICK750",
"3CIO720",
"1OHV845",
"1OHV845",
"2RLA629",
"2RLA629",
"3ATW723"
]
lsd(a, 7, 2)
from pprint import pprint
pprint(a)
if __name__ == '__main__':
example1()
example2()
|
82c4d56cc267398e0365edf435b938aa67d5277d | bssrdf/ands | /ands/algorithms/dp/rod_cut.py | 7,047 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Meta-info
Author: Nelson Brochado
Created: 30/08/2015
Updated: 07/03/2018
# Description
Given a rod of length u, and a table of prices pᵢ, for i = 0, 1, ..., where pᵢ
is the price for a rod of length i, determine the maximum revenue rᵤ obtainable
by cutting up the rod and selling the pieces.
Note: if the price pᵤ for a rod of length u is large enough, an optimal solution
may require no cutting at all.
We can cut up a rod of length u in 2ᵘ⁻¹ different ways, since we have an
independent option of cutting, or not cutting, at distance i inches from the
left end, for i = 1, 2, ... , u - 1.
# TODO
- Add complexity analysis.
# References
- http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html
- Introduction to Algorithms (3rd edition) by CLSR
- Slides by prof. E. Papadopoulou
"""
__all__ = ["recursive_rod_cut",
"memoized_rod_cut",
"bottom_up_rod_cut",
"extended_bottom_up_rod_cut"]
import sys
def recursive_rod_cut(prices: list, n: int) -> int:
"""Returns the maximum revenue of cutting a rod of length n. It does not
return which rod pieces you need to pick to obtain the maximum revenue.
prices contains the prices for each rod of different length.
prices[0]: price of the rod of length 0 => not useful!
prices[1]: price of the rod of length 1.
.
.
.
princes[i]: prince of rod of length i.
Time complexity: O(2ⁿ)."""
if n == 0: # Base case
return 0
max_revenue = -sys.maxsize
for i in range(1, n + 1): # Last i is n.
max_revenue = max(max_revenue,
prices[i] + recursive_rod_cut(prices, n - i))
return max_revenue
def _memoized_rod_cut_aux(prices: list, n: int, revenues: list,
s: list) -> int:
"""Auxiliary function for the memoized_rod_cut function."""
# If the following condition is true, that would mean that the revenue for a
# rod of length n has already been "memoised", and we don't need to
# recompute it again, but we simply return it.
if revenues[n] >= 0:
return revenues[n]
max_revenue = -sys.maxsize
if n == 0: # If the size of the rod is 0, then max_revenue is 0.
max_revenue = 0
else:
for i in range(1, n + 1):
q = _memoized_rod_cut_aux(prices, n - i, revenues, s)
if prices[i] + q > max_revenue:
max_revenue = prices[i] + q
s[n] = i
# Memoising the maximum revenue for sub-problem with a rod of length n.
revenues[n] = max_revenue
return max_revenue
def memoized_rod_cut(prices: list, n: int) -> int:
"""Top-down dynamic programming version of recursive_rod_cut, using
"memoisation" to store sub problems' solutions. Memoisation is basically the
name to the technique of storing what it has previously been computed.
In this algorithm, as oppose to the plain recursive one, instead of
repeatedly solving the same sub-problems, we store the solution to a
sub-problem in a table, the first time we solve the sub-problem, so that
this solution can simply be looked up, if needed again.
The disadvantage of this solution is that we need additional memory, i.e. a
table, to store intermediary solutions.
Time complexity: Θ(n²)."""
# Initializing the revenues list of the sub-problems (of length i=0, ...,n)
# to a small and negative number, which simply means that we have not yet
# computed the revenue for those sub-problems.
# Note: revenue values are always non-negative, unless prices contain
# negative numbers.
revenues = [-sys.maxsize] * (n + 1)
# Optimal first cut for rods of length 0 ... n.
s = [0] * (n + 1)
return _memoized_rod_cut_aux(prices, n, revenues, s), s
def bottom_up_rod_cut(prices: list, n: int) -> int:
"""Bottom-up dynamic programming solution to the rod cut problem.
Time complexity: Θ(n²)."""
revenues = [-sys.maxsize] * (n + 1)
revenues[0] = 0 # Revenue for rod of length 0 is 0.
for i in range(1, n + 1):
max_revenue = -sys.maxsize
for j in range(1, i + 1): # Find the max cut position for length i.
max_revenue = max(max_revenue, prices[j] + revenues[i - j])
revenues[i] = max_revenue
return revenues[n]
def extended_bottom_up_rod_cut(prices: list, n: int) -> tuple:
"""Dynamic programming bottom-up solution to the rod cut problem.
It returns a tuple, whose first item is a list of the revenues and second is
a list containing the rod pieces that are used in the revenue.
Time complexity: O(2ⁿ)."""
revenues = [-sys.maxsize] * (n + 1)
s = [[]] * (n + 1) # Used to store the optimal choices.
revenues[0] = 0
s[0] = [0]
for i in range(1, n + 1):
max_revenue = -sys.maxsize
for j in range(1, i + 1):
# Note: j + (i - j) = i.
# What does this mean, or why should this fact be useful?
# At each iteration of the outer loop, we are trying to find the
# max_revenue for a rod of length i (and we want also to find which
# items we are including to obtain that max_revenue). To obtain a
# rod of size i, we need at least 2 other smaller rods, unless we do
# not cut the rod. Now, to obtain a rod of length i, we need to
# insert together a rod of length j < i and a rod of length
# i - j < j, because j + (i - j) = i, as we stated at the beginning.
if max_revenue < prices[j] + revenues[i - j]:
max_revenue = prices[j] + revenues[i - j]
if revenues[i - j] != 0:
s[i] = [j] + s[i - j]
else:
# revenue[i] (current) uses a rod of length j.
# left most cut is at j.
s[i] = [j]
revenues[i] = max_revenue
return revenues, s
def _rod_cut_solution_print(n: int, s: list) -> None:
"""prices is the list of initial prices.
n is the number of those prices - 1.
s is the solution returned by memoized_rod_cut."""
while n > 0:
print(s[n], end=" ")
n = n - s[n]
print()
if __name__ == "__main__":
p1 = [0, 1, 5, 8, 9, 10, 17, 17, 20]
def test_recursive_rod_cut():
print("Revenue:", recursive_rod_cut(p1, len(p1) - 1))
def test_memoized_rod_cut():
r, s = memoized_rod_cut(p1, len(p1) - 1)
print("Revenue:", r)
print("s:", s)
_rod_cut_solution_print(len(p1) - 1, s)
def test_bottom_up_rod_cut():
print("Revenue:", bottom_up_rod_cut(p1, len(p1) - 1))
def test_extended_bottom_up_rod_cut():
r, s = extended_bottom_up_rod_cut(p1, len(p1) - 1)
print("Revenues:", r)
print("s:", s)
test_recursive_rod_cut()
test_memoized_rod_cut()
test_bottom_up_rod_cut()
test_extended_bottom_up_rod_cut()
|
90342388d68ad8d2c5df0015262c5c9d047361c7 | cyj907/snake | /Apple.py | 1,019 | 3.65625 | 4 | # -*- coding: cp936 -*-
#2016_6_27
#by cyj
from Const import *
import random
class Apple:
def __init__(self):
#self.x=random.randint(0,SCREEN_WITH-APPLE_WIDTH+1)
#self.y=random.randint(0,SCREEN_HEIGHT-APPLE_HEIGHT+1)
self.x = random.randint(0, Grid_X-1) * APPLE_WIDTH
self.y = random.randint(0, Grid_Y-1) * APPLE_WIDTH
#print self.x / APPLE_WIDTH, self.y / APPLE_WIDTH
def _GenApplePos(self):
#self.x=random.randint(0,SCREEN_WITH-APPLE_WIDTH+1)
#self.y=random.randint(0,SCREEN_HEIGHT-APPLE_HEIGHT+1)
self.x = random.randint(0, Grid_X-1) * APPLE_WIDTH
self.y = random.randint(0, Grid_Y-1) * APPLE_WIDTH
#print self.x / APPLE_WIDTH, self.y / APPLE_WIDTH
def SetApple(self):
self._GenApplePos()
# public method for getting the rectangle of apple
def getRect(self):
return self.x, self.y, self.x + APPLE_WIDTH - 1, self.y + APPLE_HEIGHT - 1
def GetApplePos(self):
return self.x, self.y
|
a7cb31e5a5fb69d44408740c9cb620d56c199ef3 | cyj907/snake | /old/Apple.py | 989 | 3.578125 | 4 | # -*- coding: cp936 -*-
#2016_6_22
#by zhs
from Const import *
import random
class Apple:
def __init__(self,pygame,screen,applePic):
self.pygame = pygame
self.screen = screen
self.x=random.randint(0,SCREEN_WITH-APPLE_WIDTH+1)
self.y=random.randint(0,SCREEN_HEIGHT-APPLE_HEIGHT+1)
self.applePic=applePic
def _GenApplePos(self):
self.x=random.randint(0,SCREEN_WITH-APPLE_WIDTH+1)
self.y=random.randint(0,SCREEN_HEIGHT-APPLE_HEIGHT+1)
def SetApple(self):
self._GenApplePos()
def ShowApple(self):
# self.pygame.draw.rect(self.screen,APPLE_COLOR,(self.x,self.y,APPLE_WIDTH,APPLE_HEIGHT))
self.screen.blit(self.applePic,(self.x,self.y))
# public method for getting the rectangle of apple
def getRect(self):
return (self.x, self.y, self.x + APPLE_WIDTH - 1, self.y + APPLE_HEIGHT - 1)
def GetApplePos(self):
return (self.x,self.y)
|
6023573a1cd2e9ec93af7bde69cc279781e8281a | sys-ryan/machine-learning-basic | /01. Data Preprocessing/01_Data_Preprocessing.py | 2,704 | 3.828125 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
x = dataset.iloc[:, :-1].values # [rows, columns]
y = dataset.iloc[:, -1].values
# Taking care of missing data - data preprocessing tools.
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer.fit(x[:, 1:]) # connect to the object
x[:, 1:] = imputer.transform(x[:, 1:]) # replace missing values according to the strategy
print(x)
# Encoding categorical data - one hot incoding (to avoid numerical order)
# Encoding the Independent Variable
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0])], remainder='passthrough')
x = np.array(ct.fit_transform(x))
print(x)
# Encoding Dependant Variable
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)
print(y)
#Splitting the dataset into Training set and Test set
# split the dataset and then apply feature scaling
# test set is supposed to be a brand new set
# test set is not something you're suppose to work with during the learning process
# * To prevent information leakage
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
#random_state : seed for random variable
print('x_train: ')
print(x_train)
print('x_test: ')
print(x_test)
print('y_train: ')
print(y_train)
print('y_test: ')
print(y_test)
#Feature Scaling
# 이렇듯 단위가 서로 상이하면 머신러닝의 결과가 잘못될 수 있습니다. 정확한 분석을 위해서는 Feature를 서로 정규화시켜주는 작업이 필요합니다. 이를 Feature Scaling이라고 합니다.
# Standardisation, Normalization 이 있음.
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train[:, 3:] = sc.fit_transform(x_train[:, 3:])
x_test[:, 3:] = sc.transform(x_test[:, 3:]) #apply the same transform used for x_train
'''
'fit' just calculates the mean and standard deviation parameters required for scaling and saves these nos. in the object 'sc' internally
'transform' applies the standardization formula using previously calculated mean and standard deviation on all values
'fit_transform' does it together
we do not use fit_transform on test data because we want to calculate values for test set using std dev and mean of train set as we are predicting dependent values for test set using train set values.
'''
print(x_train)
print(x_test)
|
defaf80c7ae83d4a81d6eda52fbcb78e75a8eebc | liuhuijun11832/python-learning | /importandio.py | 2,692 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# 导入一个模块的某个方法,import *代表所有方法(但是_开头的名字不在此列),同时被导入模块中的可执行代码在第一次也会执行
from mynumbers import printme
import math
import pickle
import pprint
printme("哈哈哈哈哈哈")
"""dir函数可以找到模块内定义的所有名称,以一个字符串列表的形式返回,如果没有参数,那就是当前模块"""
print(dir())
"""当使用from package import item这种形式的时候,对应的item既可以是包里面的子模块(子包),或者包里面定义的其他名称,比如函数,类或者变量"""
"""如果使用形如import item.subitem.subsubitem这种导入形式,除了最后一项,都必须是包,而最后一项则可以是模块或者是包,但是不可以是类,函数或者变量的名字"""
print('{}和{}'.format("google", "alibaba"))
print('{1}和{0}'.format("google", "alibaba"))
print('{site}和{url}'.format(site="google", url="http://www.google.com"))
print('常量PI的值近似为{0:.3f}'.format(math.pi))
str = input("请输入:")
print("你输入的内容是:", str)
"""打开文件的模式:
r:默认,只读,从文件头开始
rb:只读,文件头,二进制
r+:读写,文件头开始
w:只写,文件头,覆盖,新建
wb:只写,文件头,覆盖新建,二进制
w+:读写,文件头,覆盖,新建
a:追加,新建
ab:二进制追加,新建
a+:读写,追加,新建
ab+:二进制读写,追加,新建
"""
# 文件的只写
f = open("E:\\test.txt", "w")
f.write("python 是一个非常好的语言。 \n是的,的确非常好\n")
# 返回文件对象当前所处的位置,它是从文件头开始算起的字节数
print(f.tell())
# 能够改变文件当前的位置,第一个参数为移动多少位,如果第二个参数时0表示文件开头,为1表示当前位置,为2表示文件结尾
f.seek(5, 0)
f.close()
# 文件的只读
r = open("E:\\test.txt", "r")
tmpStr = r.readline()
print(tmpStr)
tmpEntityStr = r.readlines()
print(tmpEntityStr)
r.close()
# pickle模块实现了基本的数据序列化和反序列化
# 将数据保存到文件
data1 = {'a': [1, 2, 3, 4, 5*6], 'b': ('string', u'Unicode String'), 'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
# x = pickle.load(selfref_list)
output = open('E:\\data.pkl', 'wb')
pickle.dump(data1, output)
pickle.dump(selfref_list, output, -1)
output.close()
# 从文件中重构python对象
pkl_file = open('E:\\data.pkl', 'rb')
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
data3 = pickle.load(pkl_file)
pprint.pprint(data3)
pkl_file.close()
|
49abc06f0104dcdcf9a949d040db84d2c98fde02 | liuhuijun11832/python-learning | /mythread.py | 1,722 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import time, threading
'''python的标准库内置了两个模块,_thread和threading,前者是低级模块,后者是高级模块,一般情况下,使用高级模块'''
def loop():
print('线程正在运行:{}'.format(threading.current_thread().name))
n = 0
while n < 5:
n += 1
print('线程 {} >>> {}'.format(threading.current_thread().name, n))
time.sleep(1)
print('线程 {} 结束'.format(threading.current_thread().name))
print('线程{}正在运行...'.format(threading.current_thread().name))
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join( )
print('线程 {} 结束'.format(threading.current_thread().name))
'''线程和进程最大的区别在于:进程中的同一变量是拷贝存放于每个进程中,互不影响;而多线程中,所有变量由所有线程共享,所以通常需要加一把锁'''
# 假如这是银行存款
balance = 0
lock = threading.Lock()
def change_it(n):
# 先存后取,结果为0
global balance
balance += n
balance -= n
def run_thread(n):
for i in range(100000):
# 首先要获取锁
lock.acquire()
try:
change_it(n)
finally:
# 还需要释放锁
lock.release()
# python中会有Gil锁,然后每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行,所以python只能利用到一个核,然后多线程交替执行
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
# 线程安全的本地变量,
local = threading.local()
|
ee4a2f8840f7f7471601eb338fc0197dddf36594 | char-n/python-cookbook-demo | /chapter-01/1.18-映射名称到序列元素.py | 577 | 4.09375 | 4 | #!usr/bin/env python
# encoding: utf-8
# @Author : niuzhifa 1944044667@qq.com
# @Time : 2018/2/24 20:28
# 命名元组
from collections import namedtuple
MyTuple = namedtuple('MyTuple', ['name', 'age'])
my_tuple = MyTuple('niuzhifa', '100')
print(my_tuple)
# 支持所有的普通元组操作
# 索引
print(len(my_tuple))
# 解压
name, age = my_tuple
print(name, age)
# 如果要改变命名元组的属性.需要使用_replace方法,会创建一个全新的元组,并把相应的字段用新的值替换
replace = my_tuple._replace(name='zhangsan')
print(replace)
print(my_tuple)
|
c6ca5bd01d03dcec7a9a68fb514ab269d2a93fe5 | Jularin/Codeforces-problems | /58A.py | 244 | 3.734375 | 4 | string = input()
List = ["h","e","l","l","o",]
counter = 0
for letter in List:
if string.find(letter)!=-1:
string = string[string.find(letter)+1:]
counter += 1
else:
counter-=1
if counter==5:
print("YES")
else:
print("NO") |
2c37670e2fd9f985c938dec3ff2aadc6e39febbb | Jularin/Codeforces-problems | /59A.py | 202 | 4.03125 | 4 | string = input()
up = 0
low = 0
for i in string:
if i.isupper():
up+=1
elif i.islower():
low+=1
if low>=up:
print(string.lower())
else:
print(string.upper())
|
3291814482c27d26ced5c20e783b4798a29db805 | Gusbell/CP3-Thitiwat-Srisawangpanyakul | /Exercise11_Thitiwat_S.py | 182 | 3.890625 | 4 | number = int(input("Number: "))
c = number
d = -1
for i in range(number):
c -= 1
d += 2
print(" "*(c) + "*"*(d))
#เป็นโจทย์ที่มันมาก
|
8f4b21a601c7e3a2da6c26971c7c7bb982d4a242 | hashncrash/IS211_Assignment13 | /recursion.py | 2,230 | 4.625 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 14 Assignment - Recursion"""
def fibonnaci(n):
"""Returns the nth element in the Fibonnaci sequence.
Args:
n (int): Number representing the nth element in a sequence.
Returns:
int: The number that is the given nth element in the fibonnaci sequence.
Examples:
>>> fibonnaci(1)
1
>>> fibonnaci(10)
55
"""
if n == 1 or n == 2:
return 1
else:
return fibonnaci(n - 1) + fibonnaci(n - 2)
def gcd(a, b):
"""Returns the greatest common divisor of two numbers.
Args:
a (int): an integer to find the greatest common divisor with b
b (int): an integer to find the greatest common divosor with a
Returns:
int: An integer representing the largest number that divides both given
integers a and b without leaving a remainder.
Examples:
>>> gcd(252, 105)
21
>>> gcd(100, 27)
1
"""
if b == 0:
return a
else:
return gcd(b, a % b)
def compareTo(s1, s2):
"""Compares two strings and returns a value depending on the comparison of
the two strings.
Args:
s1(str): a string to be compared to another given string in the second
argument.
s2(str): a string to be compared to the first given argument (s1).
Returns:
int: A value corresponding with the comparison of two strings; A
positive value if s1 > s2, a negative value if s1 < s2, and 0 if they
are the same.
Examples:
>>> compareTo("abracadabra", "poof")
-112
>>> compareTo("lmno", "hijkl")
108
>>> compareTo("", "")
0
>>> compareTo("boo", "book")
-111
"""
if s1 == '' and s2 == '':
return 0
elif ord(s1[0]) > ord(s2[0]):
return 0 + ord(s1[0])
elif ord(s1[0]) < ord(s2[0]):
return 0 - ord(s2[0])
elif s1[1:2] == '' and not s2[1:2] == '':
return 0 - ord(s2[0])
elif s2[1:2] == '' and not s1[1:2] == '':
return 0 + ord(s1[0])
elif s1[1:2] == '' and s2[1:2] == '':
return 0
else:
return compareTo(s1[1:], s2[1:])
|
989886a9986ed963d661016e4d03f63c4cf93495 | mawrobel/database_test | /DB_Picle_test.py | 767 | 3.53125 | 4 | from initdata import db
import pickle
"i'm Pickling record from .txt file"
dbfile = open('people-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()
"printing record in console"
dbfile = open('people-pickle', 'rb')
db = pickle.load(dbfile)
for key in db:
print(key, "=>\n", db[key])
dbfile.close()
"Make separate .pkl file for all records from initdata"
from initdata import Anastasia, John
for (key, record) in [('Anastasia', Anastasia), ('John', John)]:
recfile = open(key + '.pkl', 'wb')
pickle.dump(record, recfile)
recfile.close()
"Modify Anastasia's record"
Anafile = open('Anastasia.pkl', 'rb')
Ana = pickle.load(Anafile)
Anafile.close()
Ana['age'] += 1
Anafile = open('Anastasia.pkl', 'wb')
pickle.dump(Ana, Anafile)
Anafile.close()
|
7e50120d6e273dc64b440c847a7bfb4b2f8599da | PyladiesSthlm/study-group | /string_processing/elisabeth_anna.py | 1,377 | 4.34375 | 4 | #!/usr/bin/env python
import sys
import argparse
def palindrome_check(string_to_check):
letters_to_check = len(string_to_check)
if letters_to_check % 2 == 0:
letters_to_check = letters_to_check/2
else:
letters_to_check = (letters_to_check -1)/2
print letters_to_check
samma = 0
for i in range(letters_to_check):
if string_to_check[i] == string_to_check[len(string_to_check)-1-i]:
samma = samma +1
if letters_to_check == samma:
print "True"
return True
else:
print "False"
return False
def encrypt(number, string_to_encrypt):
new_string = ""
for i in range(len(string_to_encrypt)):
new_char = ord(string_to_encrypt[i]) + int(number)
new_letter = chr(new_char)
new_string = new_string + new_letter
print new_string
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Different string handling functions')
parser.add_argument("-e", "--encrypt", nargs = "+", help="use the encrypt function")
parser.add_argument("-p", "--palindrome", help="use the palindrome function")
args = parser.parse_args()
if args.encrypt:
encrypt(args.encrypt[1], args.encrypt[0])
elif args.palindrome:
palindrome_check(args.palindrome)
else:
print "no arguments"
|
7fa4bf9d6bda35cf52863bf075f0f5af79d6cc09 | nathanspang/spotifyClone | /main.py | 1,401 | 3.828125 | 4 | import datetime
from playlist import Playlist
from song import Song
nextAction = input(
'Welcome to Spotify, would like to create a new playlist (new) or exit (exit)?: ')
playlists = []
if nextAction.lower() == 'new':
songs = []
playlistName = input('What would you like to name your playlist? ')
playlistGenre = input('What genre will this playlist contain? ')
anotherSong = input('Would you like to add a song? (y) or (n) ')
print()
while anotherSong.lower() == 'y':
songTitle = input('Song Title: ')
songArtist = input('Song Artist: ')
songGenre = input('Song Genre: ')
songDuration = input('Song Duration: ')
newSong = Song(songTitle, songArtist, songGenre,
datetime.datetime.today().strftime('%Y-%m-%d'), songDuration)
songs.append(newSong.title)
anotherSong = input('Would you like to add a song? (y) or (n) ')
print()
newPlaylist = Playlist(playlistName, playlistGenre, songs)
playlists.append(newPlaylist.name)
print('Playlist Added!')
print(f'Current Playlists: {playlists}')
print(f'Songs in created playlist: {songs}')
print()
else:
print(
'Invalid Input, enter [new] to add new playlist, or [view] to view playlists.')
initial = input(
'Welcome to Spotify, would like to create a new playlist (new) or exit (exit): ')
|
8d1de591706470db3bbcf26374ff958f393e85f7 | tungnc2012/learning-python | /if-else-elif.py | 275 | 4.21875 | 4 | name = input("Please enter your username ")
if len(name) <= 5:
print("Your name is too short.")
elif len(name) == 8:
# print("Your name is 8 characters.")
pass
elif len(name) >= 8:
print("Your name is 8 or more characters.")
else:
print("Your name is short.") |
9843199e0fa79cab66b2a51d5ced461e7adc385f | oneilk/data-structures | /python/queue.py | 468 | 3.6875 | 4 | from collections import deque
class Queue:
def __init__(self) -> None:
self.buffer = deque()
def enqueue(self, val):
self.buffer.appendleft(val)
def dequeue(self):
return self.buffer.pop()
def is_empty(self):
return len(self.buffer) == 0
def size(self):
return len(self.buffer)
if __name__ == "__main__":
q = Queue()
q.enqueue(69)
q.enqueue(420)
print(q.dequeue())
print(q.size()) |
cf7d2340ccc1992e993c969f9be8adc88b2afd7f | rdr42/Artificial-Inteligence-CSCE-A405 | /Project/Assignment 1/MeetingSession/Node.py | 5,997 | 3.53125 | 4 | from Board import *
class Node:
def __init__(self):
self.parent = None
self.parentdirection = None
self.children = {} #Store node objects{up or left or down or right: node}
self.value = board #[0,1,2,3,4,4,5]
def populateChildren(self):
index = self.value.blank
if(index == 0):
if (self.parentdirection != 'r'):
rightpieces = self.value.pieces
temp = rightpieces[0]
rightpieces[0] = rightpieces[1]
rightpieces[1] = temp
self.children.update({'r':Node(Board(rightpieces))})
if (self.parentdirection != 'd'):
downpieces = self.value.pieces
temp = downpieces[0]
downpieces[0] = downpieces[3]
downpieces[3] = temp
self.children.update({'r':Node(Board(downpieces))})
elif(index == 1):
if (self.parentdirection != 'r'):
rightpieces = self.value.pieces
temp = rightpieces[1]
rightpieces[1] = rightpieces[2]
rightpieces[2] = temp
self.children.update({'r':Node(Board(rightpieces))})
if (self.parentdirection != 'd'):
downpieces = self.value.pieces
temp = downpieces[1]
downpieces[1] = downpieces[4]
downpieces[4] = temp
self.children.update({'r':Node(Board(downpieces))})
if (self.parentdirection != 'l'):
leftpieces = self.value.pieces
temp = downpieces[1]
leftpieces[1] = downpieces[0]
leftpieces[0] = temp
self.children.update({'r':Node(Board(leftpieces))})
elif(index == 2):
if (self.parentdirection != 'l'):
leftpieces = self.value.pieces
temp = downpieces[2]
leftpieces[2] = downpieces[1]
leftpieces[1] = temp
self.children.update({'r':Node(Board(leftpieces))})
if (self.parentdirection != 'd'):
downpieces = self.value.pieces
temp = downpieces[2]
downpieces[2] = downpieces[5]
downpieces[5] = temp
self.children.update({'r':Node(Board(downpieces))})
elif(index == 3):
if (self.parentdirection != 'u'):
uppieces = self.value.pieces
temp = uppieces[3]
uppieces[3] = uppieces[0]
uppieces[0] = temp
self.children['u'] = Node(Board(uppieces))
if (self.parentdirection != 'r'):
rightpieces = self.value.pieces
temp = rightpieces[3]
rightpieces[3] = rightpieces[4]
rightpieces[4] = temp
self.children['r'] = Node(Board(rightpieces))
if (self.parentdirection != 'd'):
downpieces = self.value.pieces
temp = downpieces[3]
downpieces[3] = downpieces[6]
downpieces[6] = temp
self.children['d'] = Node(Board(downpieces))
elif(index == 4):
if (self.parentdirection != 'u'):
uppieces = self.value.pieces
temp = uppieces[4]
uppieces[4] = uppieces[1]
uppieces[1] = temp
self.children['u'] = Node(Board(uppieces))
if (self.parentdirection != 'r'):
rightpieces = self.value.pieces
temp = rightpieces[4]
rightpieces[4] = rightpieces[5]
rightpieces[5] = temp
self.children['r'] = Node(Board(rightpieces))
if (self.parentdirection != 'd'):
downpieces = self.value.pieces
temp = downpieces[4]
downpieces[4] = downpieces[7]
downpieces[7] = temp
self.children['d'] = Node(Board(downpieces))
if (self.parentdirection != 'l'):
leftpieces = self.value.pieces
temp = downpieces[4]
leftpieces[4] = downpieces[3]
leftpieces[3] = temp
self.children.update({'r':Node(Board(leftpieces))})
elif(index == 5):
if (self.parentdirection != 'u'):
uppieces = self.value.pieces
temp = uppieces[5]
uppieces[5] = uppieces[2]
uppieces[2] = temp
self.children['u'] = Node(Board(uppieces))
if (self.parentdirection != 'd'):
downpieces = self.value.pieces
temp = downpieces[5]
downpieces[5] = downpieces[8]
downpieces[8] = temp
self.children['d'] = Node(Board(downpieces))
if (self.parentdirection != 'l'):
leftpieces = self.value.pieces
temp = downpieces[5]
leftpieces[5] = downpieces[4]
leftpieces[4] = temp
self.children.update({'r':Node(Board(leftpieces))})
elif(index == 6):
if (self.parentdirection != 'u'):
uppieces = self.value.pieces
temp = uppieces[6]
uppieces[6] = uppieces[3]
uppieces[3] = temp
self.children['u'] = Node(Board(uppieces))
if (self.parentdirection != 'r'):
rightpieces = self.value.pieces
temp = rightpieces[6]
rightpieces[6] = rightpieces[7]
rightpieces[7] = temp
self.children['r'] = Node(Board(rightpieces))
elif(index == 7):
if (self.parentdirection != 'u'):
uppieces = self.value.pieces
temp = uppieces[7]
uppieces[7] = uppieces[4]
uppieces[4] = temp
self.children['u'] = Node(Board(uppieces))
if (self.parentdirection != 'r'):
rightpieces = self.value.pieces
temp = rightpieces[7]
rightpieces[7] = rightpieces[8]
rightpieces[8] = temp
self.children['r'] = Node(Board(rightpieces))
if (self.parentdirection != 'l'):
leftpieces = self.value.pieces
temp = downpieces[7]
leftpieces[7] = downpieces[6]
leftpieces[6] = temp
self.children.update({'r':Node(Board(leftpieces))})
elif(index == 8):
if (self.parentdirection != 'u'):
uppieces = self.value.pieces
temp = uppieces[8]
uppieces[8] = uppieces[5]
uppieces[5] = temp
self.children['u'] = Node(Board(uppieces))
if (self.parentdirection != 'l'):
leftpieces = self.value.pieces
temp = downpieces[8]
leftpieces[8] = downpieces[7]
leftpieces[7] = temp
self.children.update({'r':Node(Board(leftpieces))})
|
a990fb6d918b3f762ee78669ee18078b19853bb8 | rdr42/Artificial-Inteligence-CSCE-A405 | /Project/Assignment 3/Game/main.py | 10,105 | 3.921875 | 4 | # Assignment 3
# main.py
# EJ Rasmussen erasmussen3@alaska.edu
# Rafael Reis rrdosreis@alaska.edu
# Hunter Johnson huntergj2020@gmail.com
import math
import copy
from datetime import datetime
class Node():
def __init__(self):
self.children = {}
self.board = None
self.depth = None
self.player = None
class Board():
def __init__(self):
self.board = [3,3,3,3,3,3,0,3,3,3,3,3,3,0]
self.op2 = [7,8,9,10,11,12]
self.op1 = [0,1,2,3,4,5]
def printBoard(self):
print(' ',self.board[12],self.board[11],self.board[10],self.board[9],self.board[8],self.board[7])
print(self.board[13],' ',self.board[6])
print(' ',self.board[0],self.board[1],self.board[2],self.board[3],self.board[4],self.board[5])
#Returns true if current player is able to steal stones from opponent's board
def shouldSteal(self,board,pieceValue,index,player):
arr = []
if player == '1':
arr = self.op1
else:
arr = self.op2
if pieceValue == 1 and board[index] == 0 and index in arr:
return True
else:
return False
#Steals the opponents stones opposite to current cup and put them into our cup
def stealing(self,board,player,index):
arr = []
position = index
cupIndex = None
steal = None
if player == '1':
cupIndex = 6
if position == 0:
steal = 12
if position == 1:
steal = 11
if position == 2:
steal = 10
if position == 3:
steal = 9
if position == 4:
steal = 8
if position == 5:
steal = 7
else:
cupIndex = 13
if position == 7:
steal = 5
if position == 8:
steal = 4
if position == 9:
steal = 3
if position == 10:
steal = 2
if position == 11:
steal = 1
if position == 12:
steal = 0
stolenStones = board[steal]
board[steal] = 0
board[cupIndex] += stolenStones
# This function helps get the next cup index by looping around once you get to north's storage cup
def specialLoop(self, index):
if index < 13:
return index + 1
else:
return 0
# Returns -1 if index is invalid for player
# Returns 1 if value at index is valid
# Returns 0 if value at index is 0
# Returns 100 if player 1 wins
# Returns 200 if player 2 wins
def movePiece(self,board,index,player):
if player == '1':
if index not in self.op1:
return -1
else:
#get value of index piece
if board[index] == 0:
return 0
else:
pieceValue = board[index]
board[index] = 0
while pieceValue > 0:
increment = self.specialLoop(index)
if increment != 13:
if self.shouldSteal(board,pieceValue,increment,player):
self.stealing(board,player,increment)
board[increment] += 1
pieceValue -= 1
index = increment
return 1
if player == '2':
if index not in self.op2:
return -1
else:
#get value of index piece
if board[index] == 0:
return 0
else:
pieceValue = board[index]
board[index] = 0
while pieceValue > 0:
increment = self.specialLoop(index)
if increment != 6:
if self.shouldSteal(board,pieceValue,increment,player):
self.stealing(board,player,increment)
board[increment] += 1
pieceValue -= 1
index = increment
return 1
def gameOver(self, board):
totalP2 = 0
for i in self.op2:
totalP2 += self.board[i]
if totalP2 == 0:
return True
totalP1 = 0
for i in self.op1:
totalP1 += self.board[i]
if totalP1 == 0:
return True
return False
# This function searches the provided tree for the maximum possible value achievable
# It returns a tuple of the max value to be achieved and the cup to select to get there
def alphaBeta(self,node, a, b):
alpha = (a, None)
beta = (b, None)
if not node.children:
return (self.heuristic(node.board), None)
# Max
if node.player == '1':
for key in node.children:
val = self.alphaBeta(node.children[key], alpha[0], beta[0])
if val[0] > alpha[0]:
alpha = (val[0], key)
if alpha[0] >= beta[0]:
break
return alpha
# Min
if node.player == '2':
for key in node.children:
val = self.alphaBeta(node.children[key], alpha[0], beta[0])
if val[0] < beta[0]:
beta = (val[0], key)
if beta[0] <= alpha[0]:
break
return beta
# This function scores the current board state from the perspective of south
def heuristic(self, board):
grade = 0
for i in range(7):
grade += board[i]
for i in range(7,14):
grade -= board[i]
return grade
# This function creates the tree of board states to be visited by alpha beta cutoff minimax
def createTree(self, node):
possibleMoves = []
if node.depth == 0 or self.gameOver(node.board):
return
if node.player == '1':
for i in self.op1:
if node.board[i] != 0:
possibleMoves.append(i)
else:
for i in self.op2:
if node.board[i] != 0:
possibleMoves.append(i)
for i in possibleMoves:
childNode = Node()
childBoard = copy.deepcopy(node.board)
err = self.movePiece(childBoard, i, node.player)
if err != 1:
print("Error")
childNode.board = childBoard
childNode.depth = node.depth - 1
if node.player == '1':
childNode.player = '2'
else:
childNode.player = '1'
node.children[i] = childNode
self.createTree(childNode)
def gameLoop(self):
depth = int(input("Input the depth of the alpha beta cutoff, positive integers only:\n"))
over = False
self.printBoard()
bad = True
if bad:
while bad:
currentPlayer = input("Who goes first? Computer or Opponent ? (1 or 2)\n")
if currentPlayer != '1':
if currentPlayer != '2':
print("BAD INPUT. Type 1 for computer or 2 for opponent.")
bad = True
else:
bad = False
else:
if currentPlayer != '1':
print("BAD INPUT. Type 1 for computer or 2 for opponent.")
bad = True
else:
bad = False
print(" ")
while not over:
print("*********************************")
print(" ")
self.printBoard()
print(" ")
print("*********************************")
if currentPlayer == '1':
node = Node()
node.board = self.board
node.depth = depth
node.player = '1'
before = datetime.now()
self.createTree(node)
chooseMove = self.alphaBeta(node, float("-inf"), float("inf"))[1]
after = datetime.now()
print("Time taken:", after - before)
moveError = self.movePiece(self.board, chooseMove,currentPlayer)
if moveError == -1 or moveError == 0:
if moveError == -1:
print('Invalid index, please play again.')
if moveError == 0:
print('Invalid index, there is nothing there')
goodMove = False
while not goodMove:
node = Node()
node.board = self.board
node.depth = depth
node.player = '1'
before = datetime.now()
self.createTree(node)
chooseMove = self.alphaBeta(node, float("-inf"), float("inf"))[1]
after = datetime.now()
print(after - before)
moveError = self.movePiece(self.board, chooseMove,currentPlayer)
if moveError != -1 and moveError != 0:
goodMove = True
print("|| Original Move: ",chooseMove,", Decoded move for other team: ",self.decodeMove(chooseMove)," ||")
currentPlayer = '2'
else:
chooseMove = int(input("Opponent, input options: 7 8 9 10 11 12:\n------------------------------------\n")) #some function takes in current board state
moveError = self.movePiece(self.board,chooseMove,currentPlayer)
if moveError == -1 or moveError == 0:
if moveError == -1:
print('Invalid index, please play again.')
if moveError == 0:
print('Invalid index, there is nothing there')
goodMove = False
while not goodMove:
chooseMove = int(input("Opponent, input options: 7 8 9 10 11 12:\n------------------------------------\n"))
moveError = self.movePiece(self.board,chooseMove,currentPlayer)
if moveError != -1 and moveError != 0:
goodMove = True
currentPlayer = '1'
if self.gameOver(self.board):
print("Game is over")
self.printBoard()
print(" ")
score = self.collectStones()
print("Our Total: ",score[0],", Opponent Total: ",score[1])
if score[0] > score[1]:
print("WE WON !!!!!!!!!!!!!!!!!")
elif score[0] == score[1]:
print("WE TIED.")
else:
print("Opponent won.")
over = True
def collectStones(self):
playerOneStones = 0
playerTwoStones = 0
for i in range(7):
playerOneStones += self.board[i]
for i in range(7,14):
playerTwoStones += self.board[i]
return [playerOneStones,playerTwoStones]
def decodeMove(self,move):
return move + 7
def main():
a = Board()
a.gameLoop()
main() |
58ccb45897ee8c15fa03151e021380635327c256 | rdr42/Artificial-Inteligence-CSCE-A405 | /Project/Assignment 1/Final Code/main.py | 1,955 | 4.09375 | 4 | from Heuristic import *
from Board import *
# This function accepts two 1d lists and will return true if the two lists have the same parity
def parity(start, end):
# Get parity of start state
startPairs = 0
for i in range(9):
for j in range(i+1, 9):
if start[i] > start[j] and start[i] and start[j]:
startPairs += 1
# Get parity of end state
endPairs = 0
for i in range(9):
for j in range(i+1, 9):
if end[i] > end[j] and end[i] and end[j]:
endPairs += 1
# Return if both are even or odd
return startPairs % 2 == endPairs % 2
# Main function prompts the user for input and then runs the three different search methods
def main():
print("Input your states with numbers delimited by commas and the blank space represented as a 0")
print("For example the board:")
print("[ ,1,2]")
print("[3,4,5]")
print("[6,7,8]")
print("Will be inputted as: 0,1,2,3,4,5,6,7,8")
# Get user input and split into lists of string values
startBoard = input("\nStart State: ").split(",")
endBoard = input("\nEnd State: ").split(",")
if (len(startBoard) != 9) or (len(endBoard) != 9):
print("Must enter 9 values for each state, exiting.")
exit()
# Convert strings to ints
for i in range(9):
startBoard[i] = int(startBoard[i])
endBoard[i] = int(endBoard[i])
# Check for parity
if (not parity(startBoard, endBoard)):
print("Parities don't match")
return
# 0 is BFS
# 1 is Misplaced
# 2 is Manhattan
h1 = Heuristic(0, startBoard, endBoard)
h2 = Heuristic(1, startBoard, endBoard)
h3 = Heuristic(2, startBoard, endBoard)
h4 = Heuristic(3, startBoard, endBoard)
print("\nRunning BFS")
h1.hMethod()
print("\nRunning Tiles Out of Place")
h2.hMethod()
print("\nRunning Manhattan Distance")
h3.hMethod()
print("\nRunning Gaschnig")
h4.hMethod()
# This calls our main function
main()
#Sample Inputs
#Start: 6,1,3,0,2,4,8,7,5
#End: 1,2,3,8,0,4,7,6,5
#Start: 2,3,1,7,0,8,6,5,4
#End: 1,2,3,8,0,4,7,6,5
|
4f5802add04976a8c86e237e5792ebee29bbb08f | maxifo/posti_testit | /postitoimipaikka.py | 463 | 3.53125 | 4 | import urllib.request
import json
with urllib.request.urlopen('https://raw.githubusercontent.com/theikkila/postinumerot/master/postcode_map_light.json') as response:
data = response.read()
postinumerot = json.loads(data)
def main():
postinumero = (input("Kirjoita postinumero: "))
if postinumero in postinumerot:
print(postinumerot[postinumero])
else:
print("tuntematon postinumero!")
if __name__ == '__main__':
main()
|
ab716b0d941af3fbb5d0cb77e88c7f609a6bad2a | sekerez/Project-Euler | /Problem 7.py | 540 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 12:56:50 2020
@author: isakjones
"""
def find_nth_prime(n):
def is_prime(x, L = []):
"""
Classic function, but returns a list.
"""
if x in L:
return True
elif x == 1 or x % 2 == 0:
return False
for divisor in range(1, round(x ** .5)):
if is_prime(divisor, L):
if x % divisor == 0:
return False
L.append(x)
return True, L |
68d2e8fa70e61ef9353974661bcb9df0823e1811 | mirokuxy/SFU_ACM_2016 | /oct29/F.py | 517 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
import math
def isPrim(n):
for i in xrange(2, int(math.sqrt(n)) ):
if n%i == 0:
return False
return True
def isCarm(n):
for i in xrange(2, n):
if pow(i, n, n) != i:
return False
return True
for line in sys.stdin:
n = int(line.strip())
if n == 0:
break
if (not isPrim(n)) and isCarm(n):
print "The number {0} is a Carmichael number.".format(n)
else:
print "{0} is normal.".format(n)
|
7de4e99e276c3e0ba73fc82112b55f7ee8190d5c | ayazzy/Plotter | /searches.py | 1,673 | 4.1875 | 4 | '''
This module has two functions.
Linear Search --> does a linear search when given a collection and a target.
Binary Search --> does a binary search when given a collection and a target.
output for both functions are two element tuples.
Written by: Ayaz Vural
Student Number: 20105817
Date: March 22nd 2019
'''
def linearSearch(collection,target):
count = 0
for item in collection:
count +=1
if target== item:
return target,count
return None, count
def binarySearch(collection,target):
low = 0
high = len(collection) - 1
count = 0
while high >= low:
count = count + 1
mid = (high + low) // 2
if target == collection[mid]:
return target, count
if target < collection[mid]:
high = mid - 1
else:
low = mid + 1
return None, count
if __name__ == "__main__":
print("~~TESTING~~")
aList = [1,2,3,4,5,6,7,8,9]
print(aList)
print("\n")
print("Testing the binarySearch function")
print("input is aList and target is 9. Expected output is 9 and 4 in a tuple")
print(binarySearch(aList,9 ))
print("\n")
print("input is the aList and target is 12. Since 12 is not in the list expected output is None and 4")
print(binarySearch(aList,12 ))
print("\n")
print("Testing the linearSearch function")
print("input is aList and target is 9. Expected output is 9 and 9 in a tuple")
print(linearSearch(aList,9))
print("\n")
print("input is aList and target is 11. Expected output is none and 9 in a tuple")
print(linearSearch(aList,11))
|
2fd4e56f396cd5bc76e2ae42f9e166af2163720e | yi-ye-zhi-qiu/liamlab | /dsa_in_python/0826/ps2.py | 2,019 | 3.875 | 4 | import sys; print(sys.version)
'''
Remove all adjacent duplicates. Given a string S
of lowercase letters, a duplicated removal consists
of choosing two adjacent and equal letters
and removing them.
'''
def f(s: str) -> str:
l = []
for i in range(len(s)):
if i<len(s)-1 and s[i] == s[i+1]:
#optimize removal of i<len(s)-1
l.pop()
else:
l.append(s[i])
return ''.join(l)
'''
Given a string S of lower and upper case letters,
return a good string, defined as not having:
s[i] is a lower-case letter and s[i+1] is the same
letter as upper-case or vice versa.
'''
def g(s: str) -> str:
l = []
for i in range(len(s)-1):
#detect iI or Ii ... i == I.lower(), i.upper() == I
#do not detect gi, gI, ff, II, if I==I or f==f w/ no upper/lower
l.append(s[i])
if s[i] != s[i+1] and s[i].lower() == s[i+1] or s[i].upper() == s[i+1]:
prev =l.copy()
l.pop()
print(f'{s[i]} is in violation to {s[i+1]}, popped {prev} to {l}')
l.append(s[-1])
return ''.join(l);
def h(target: list, n: int) -> list:
l = []
for i in range(1,n+2):
print(i)
if i in target:
l.append('Push')
if l.count('Push')-l.count('Pop') != len(target) and i not in target:
l.append('Push')
l.append('Pop')
return target,n,l
def o(nums1: list, nums2: list) -> list:
l = []
for i in range(len(nums1)):
val = nums1[i]
index = nums2.index(val)
subset = nums2[index:]
print(subset)
m = val
for j in range(len(subset)):
if subset[j] > m:
l.append(subset[j])
m = subset[j]
break;
if m == val:
l.append(-1)
print(l)
return l
if __name__ == "__main__":
print(f('leEeetcode'),'\n')
print(g('giIiraffEe'),'\n')
print(h([2,3,4],4),'\n')
print(o([4,1,2],[1,3,4,2]))
|
3a07c999f55e027796c9e65625d5db3ab4c9024f | jake3991/mavsim_template_files | /mavsim_python/chap4/wind_simulation.py | 1,556 | 3.65625 | 4 | """
Class to determine wind velocity at any given moment,
calculates a steady wind speed and uses a stochastic
process to represent wind gusts. (Follows section 4.4 in uav book)
"""
import sys
sys.path.append('..')
import numpy as np
class wind_simulation:
def __init__(self, Ts):
# steady state wind defined in the inertial frame
self._steady_state = np.array([[0., 0., 0.]]).T
# self.steady_state = np.array([[3., 1., 0.]]).T
# Dryden gust model parameters (pg 56 UAV book)
# HACK: Setting Va to a constant value is a hack. We set a nominal airspeed for the gust model.
# Could pass current Va into the gust function and recalculate A and B matrices.
Va = 17
self._A =
self._B =
self._C =
self._gust_state =
self._Ts = Ts
def update(self):
# returns a six vector.
# The first three elements are the steady state wind in the inertial frame
# The second three elements are the gust in the body frame
return np.concatenate(( self._steady_state, self._gust() ))
def _gust(self):
# calculate wind gust using Dryden model. Gust is defined in the body frame
w = np.random.randn() # zero mean unit variance Gaussian (white noise)
# propagate Dryden model (Euler method): x[k+1] = x[k] + Ts*( A x[k] + B w[k] )
self._gust_state += self._Ts * (self._A @ self._gust_state + self._B * w)
# output the current gust: y[k] = C x[k]
return self._C @ self._gust_state
|
22a8000dfe247162fd1ad7fc2a21190a2f9d0c32 | AsmaTouqir/TIC-TAC-TOE-GAME | /final1_projectlab.py | 4,005 | 3.765625 | 4 |
from tkinter import *
from tkinter import messagebox
import random as r
#add all main widgets for taking player information
def button(frame):#Function to define a button
Label(frame,text='Player 1 name:',font=('times 20 bold italic'),bg="#765751").grid(row=5,column=0) #label for planyer name 1
player1name=StringVar() #Special Variable for storing player name 1
enterplayer1name=Entry(frame,textvariable=player1name,width=40) #creating text-box
enterplayer1name.grid(row=5,column=1)
Label(frame,text='Player 2 name:',font=('times 20 bold italic'),bg="#765751").grid(row=6,column=0) #label for player name 2
player2name=StringVar() #special variable for storing player name 2
enterplayer2name=Entry(frame,textvariable=player2name,width=40) #text box for player number two
enterplayer2name.grid(row=6,column=1) #placing the above widget
b=Button(frame,padx=1,bg="#84EA11",width=3,text=" ",font=('arial',50,'bold'),relief=GROOVE,bd=5)
#save information button
def save():
text="TIC TAC TOE PLAYERS:"+"\n"+"p1: "+enterplayer1name.get()+"\n"+"p2: "+enterplayer2name.get()+"\n"+"'"+a+"' has won"
with open("data.txt",'w') as f:
f.writelines(text)
button_ok=Button(frame,text='save',font=('Ariel 15 bold italic'),bg='#84EA11',relief=GROOVE,command=save)
button_ok.grid(row=7,column=1)
button_quit=Button(frame,text='exit',font=('Ariel 15 bold italic'),bg='#84EA11',relief=GROOVE,command=root.destroy)
button_quit.grid(row=8,column=1)
def enterplayername_delete():
enterplayer1name.delete(first=0,last=22)
enterplayer2name.delete(first=0,last=22)
B=Button(frame, text="clear",font=('Ariel 15 bold italic'),bg='#84EA11',relief=GROOVE,command=enterplayername_delete)
B.grid(row=8,column=2)
return b
def change_a(): #Function to change the operand for the next player
global a
for i in ['O','X']:
if not(i==a):
a=i
break
def reset(): #Resets the game
global a
for i in range(3):
for j in range(3):
b[i][j]["text"]=" "
b[i][j]["state"]=NORMAL
a=r.choice(['O','X'])
def check(): #Checks for victory or Draw
for i in range(3):
if(b[i][0]["text"]==b[i][1]["text"]==b[i][2]["text"]==a or b[0][i]["text"]==b[1][i]["text"]==b[2][i]["text"]==a):
messagebox.showinfo("Congrats!!","'"+a+"' has won")
reset()
if(b[0][0]["text"]==b[1][1]["text"]==b[2][2]["text"]==a or b[0][2]["text"]==b[1][1]["text"]==b[2][0]["text"]==a):
messagebox.showinfo("Congrats!!","'"+a+"' has won")
reset()
elif(b[0][0]["state"]==b[0][1]["state"]==b[0][2]["state"]==b[1][0]["state"]==b[1][1]["state"]==b[1][2]["state"]==b[2][0]["state"]==b[2][1]["state"]==b[2][2]["state"]==DISABLED):
messagebox.showinfo("Tied!!","The match ended in a draw")
reset()
def click(row,col):
b[row][col].config(text=a,state=DISABLED,disabledforeground=colour[a])
check()
change_a()
label.config(text=a+"'s Chance",bg="#765751")
############### Main Program #################
root=Tk() #Window defined
root.title("Tic-Tac-Toe")#Title given
root.configure(bg="#765751")
a=r.choice(['O','X']) #Two operators defined
colour={'O':"#1142EA",'X':"#FF2E24"}
b=[[],[],[]]
for i in range(3):
for j in range(3):
b[i].append(button(root))
b[i][j].config(command= lambda row=i,col=j:click(row,col))
b[i][j].grid(row=i,column=j)
label=Label(text=a+"'s Chance",font=('arial',20,'bold'),bg="#765751")
label.grid(row=3,column=0,columnspan=3)
root.mainloop()
|
fdd3b067454c1c79902e5b55c924144ad1ddd2e7 | davideflo/Python_code | /StackExchangeClassifier.py | 3,183 | 3.65625 | 4 | # Stack Exchange Question Classifier
import pandas as pd
import numpy as np
import json
import codecs
def read_dataset(path):
with codecs.open(path, 'r', 'utf-8') as myFile:
content = myFile.read()
dataset = json.loads(content)
#dataset = pd.read_table(content)
return dataset
train = pd.read_table("input00.txt", header = 0, delimiter = "\t", quoting = 3)
label = open("output00.txt", 'r')
test_num_classes = []
for line in label:
test_num_classes.append(str(line))
test_indices = np.random.random_integers(0, train.shape[0]-1, 1000)
train_indices = set(range(train.shape[0])).difference(set(test_indices))
Train = train.ix[train_indices]
Train_classes = []
for index in train_indices:
Train_classes.append(test_num_classes[index])
Test = train.ix[test_indices]
Test_classes = []
for index in test_indices:
Test_classes.append(test_num_classes[index])
from bs4 import BeautifulSoup
example1 = BeautifulSoup(str(Train.ix[0]))
import re
letters_only = re.sub("[^a-zA-Z]", " ", example1.get_text())
# [] indicates group membership and ^ means "not". In other words, the re.sub() statement above says, "Find anything that is NOT a lowercase letter (a-z) or an upper case letter (A-Z), and replace it with a space."
lower_case = letters_only.lower()
words = lower_case.split()
import nltk
#nltk.download()
# look into some NLP documentation
from nltk.corpus import stopwords # import the stop words list
print(stopwords.words("english"))
def review_to_words(raw_review):
review_text = BeautifulSoup(str(raw_review)).get_text()
letters_only = re.sub("^[a-zA-Z]", " ", review_text)
words = letters_only.lower().split()
stops = set(stopwords.words("english"))
meaningful_words = [w for w in words if not w in stops]
return(" ".join(meaningful_words))
true_words = []
for i in train_indices:
true_words.append(review_to_words(Train.ix[i].values))
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(analyzer = "word", tokenizer = None,
preprocessor = None, stop_words = None, max_features = 6000)
train_data_features = vectorizer.fit_transform(true_words)
train_data_features = train_data_features.toarray()
vocab = vectorizer.get_feature_names()
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(n_estimators=200)
num_classes = []
for x in Train_classes:
if x == 'electronics':
num_classes.append(0)
elif x == 'mathematica':
num_classes.append(1)
elif x == 'android':
num_classes.append(2)
elif x == 'security':
num_classes.append(3)
elif x == 'gis':
num_classes.append(4)
elif x == 'photo':
num_classes.append(5)
elif x == 'scifi':
num_classes.append(6)
elif x == 'unix':
num_classes.append(7)
elif x == 'apple':
num_classes.append(8)
else:
num_classes.append(9)
classifier = rfc.fit(train_data_features, num_classes)
test_words = []
for i in test_indices:
test_words.append(review_to_words(Test.ix[i].values))
test_data_features = vectorizer.fit_transform(test_words)
test_data_features = test_data_features.toarray()
result = classifier.predict(test_data_features)
result2 = classifier.predict(train_data_features) |
fcccfab3841587604297a1e43f9ffb1d5710d3eb | Mohanibanez/Task-Generator | /app.py | 4,767 | 3.875 | 4 | #Importing Modules and the functions
#In line 11 you are making available the code you need to build web apps with flask.
#flask is the framework here(library), while Flask is a Python class datatype(specific class).
#In other words, Flask is the prototype used to create instances of web application or web applications if you want to put it simple.
#What we also did is we imported the render_template method from the flask framework and then we passed an HTML file(line 47 and line 75)
#to that method.
#The method will generate a jinja2 template object out of that HTML and return it to the browser when the user visits associated URL.
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
#So, once we import Flask, we need to create an instance of the Flask class for our web app.
#That’s what line 18 does. __name__ is a special variable that gets as value the string "__main__" when you’re executing the script.
app = Flask(__name__) #__name__ becomes __main__ when executed.
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' #The database URI that should be used for the connection.
db = SQLAlchemy(app)
#The baseclass for all your models is called db.Model. It’s stored on the SQLAlchemy instance you have to create.
#Use Column to define a column.
#The name of the column is the name you assign it to.
#If you want to use a different name in the table you can provide an optional first argument which is a string with the desired column name.
#Primary keys are marked with primary_key=True.
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True) #Number of tasks
content = db.Column(db.String(200), nullable=False) #Task description
date_created = db.Column(db.DateTime, default=datetime.utcnow) #Date created
def __repr__(self):
return '<Task %r>' % self.id
#That index function is mapped to the home ‘/’ URL.
#That means when the user navigates to localhost:5000, the home function will run and it will return its output on the webpage.
#If the input to the route method was something else, let’s say ‘/about/’, the function output would be shown when the user visited localhost:5000/about/.
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST': #If the request is provided by the User, I.e.,Inputting data, the below code is followed
task_content = request.form['content'] #Iniliazing a variable to save the contents in the "contents" field.
new_task = Todo(content=task_content) #creating a Todo object(a new task)
try:
db.session.add(new_task) #adding data to our model
db.session.commit() #commiting the data to our model
return redirect('/') #redirect it back to index page
except:
return 'There was an issue adding your task' #if it fails(above 3 lines)
else:
tasks = Todo.query.order_by(Todo.date_created).all() #To display all current tasks in table
return render_template('index.html', tasks=tasks) #Returning the tasks to template
@app.route('/delete/<int:id>') #New route to delete a Task
def delete(id):
task_to_delete = Todo.query.get_or_404(id) #Gets the Task by id, else it 404s
try:
db.session.delete(task_to_delete)
db.session.commit()
return redirect('/') #Redirect back to home page
except:
return 'There was a problem deleting that task'
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
task = Todo.query.get_or_404(id)
if request.method == 'POST':
task.content = request.form['content']
try:
db.session.commit()
return redirect('/')
except:
return 'There was an issue updating your task'
else:
return render_template('update.html', task=task)
#Something you should know is that Python assigns the name "__main__" to the script when the script is executed.
#If the script is imported from another script, the script keeps it given name (e.g. hello.py).
#In our case we are executing the script. Therefore, __name__ will be equal to "__main__".
#That means the if conditional statement is satisfied and the app.run() method will be executed.
#This technique allows the programmer to have control over script’s behavior.
if __name__ == "__main__":
app.run(debug=True)
#The Python script handles the communication between the web server and the web client (i.e. browser)
#while the HTML documents are responsible for the structure of the page content.
|
71026e3df48bd93838388a0bfd170bd9a94a0a83 | AungTun1130/Daily-Planner-Assistant | /TkinterUI/Tkinter_calculatorUI.py | 3,913 | 4.09375 | 4 | from tkinter import *
root =Tk()
root.title("Simple Calculator")
number = Entry(root,width =35)
number.grid(row= 0,column =0,columnspan=3,padx = 10,pady=10)
math_func_type = ['add','subtract','multiply','divide']
def button_click(num):
#number.delete(0,END)
current = number.get()
number.delete(0,END)
number.insert(0,str(current) + str(num))
def button_clear():
number.delete(0,END)
def add():
first_number = float(number.get())
global f_num
global math_func
math_func= math_func_type[0]
f_num = first_number
number.delete(0,END)
def subtract():
first_number = float(number.get())
global f_num
global math_func
math_func= math_func_type[1]
f_num = first_number
number.delete(0,END)
def multiply():
first_number = float(number.get())
global f_num
global math_func
math_func= math_func_type[2]
f_num = first_number
number.delete(0,END)
def divide():
first_number = float(number.get())
global f_num
global math_func
math_func= math_func_type[3]
f_num = first_number
number.delete(0,END)
def button_equal():
second_number = number.get()
number.delete(0, END)
if math_func == math_func_type[0]:
number.insert(0,f_num+float(second_number))
elif math_func == math_func_type[1]:
number.insert(0,f_num-float(second_number))
elif math_func == math_func_type[2]:
number.insert(0,f_num*float(second_number))
elif math_func == math_func_type[3]:
number.insert(0,f_num/float(second_number))
button_size_x=40
button_size_y=20
button_1 = Button(root,text ="1",padx=button_size_x,pady=button_size_y,command = lambda: button_click(1))
button_2 = Button(root,text ="2",padx=button_size_x,pady=button_size_y,command = lambda: button_click(2))
button_3 = Button(root,text ="3",padx=button_size_x,pady=button_size_y,command = lambda: button_click(3))
button_4 = Button(root,text ="4",padx=button_size_x,pady=button_size_y,command = lambda: button_click(4))
button_5 = Button(root,text ="5",padx=button_size_x,pady=button_size_y,command = lambda: button_click(5))
button_6 = Button(root,text ="6",padx=button_size_x,pady=button_size_y,command = lambda: button_click(6))
button_7 = Button(root,text ="7",padx=button_size_x,pady=button_size_y,command = lambda: button_click(7))
button_8 = Button(root,text ="8",padx=button_size_x,pady=button_size_y,command = lambda: button_click(8))
button_9 = Button(root,text ="9",padx=button_size_x,pady=button_size_y,command = lambda: button_click(9))
button_0 = Button(root,text ="0",padx=button_size_x,pady=button_size_y,command = lambda: button_click(0))
button_add = Button(root,text ="+",padx=button_size_x-1,pady=button_size_y,command = add)
button_subtract = Button(root,text ="-",padx=button_size_x,pady=button_size_y,command = subtract)
button_multiply = Button(root,text ="x",padx=button_size_x,pady=button_size_y,command = multiply)
button_divide = Button(root,text ="/",padx=button_size_x,pady=button_size_y,command = divide)
button_equal = Button(root,text ="=",padx=button_size_x+49,pady=button_size_y,command = button_equal)
button_clear = Button(root,text ="Clear",padx=button_size_x+39,pady=button_size_y,command = button_clear)
button_1.grid(row=3,column=0)
button_2.grid(row=3,column=1)
button_3.grid(row=3,column=2)
button_4.grid(row=2,column=0)
button_5.grid(row=2,column=1)
button_6.grid(row=2,column=2)
button_7.grid(row=1,column=0)
button_8.grid(row=1,column=1)
button_9.grid(row=1,column=2)
button_0.grid(row=4,column =0)
button_clear.grid(row=4,column =1,columnspan =2)
button_add.grid(row=5,column =0)
button_equal.grid(row=5,column =1,columnspan =2)
button_subtract.grid(row=6,column =0)
button_multiply.grid(row=6,column =1)
button_divide.grid(row=6,column =2)
root.mainloop() |
a4b22a4a32ffa1afb1508d232388d6bc759e0485 | avi651/PythonBasics | /ProgrammeWorkFlow/Tabs.py | 233 | 4.125 | 4 | name = input("Please enter your name: ")
age = int(input("Hi old are you, {0}? ".format(name))) #Adding type cast
print(age)
if age > 18:
print("You are old enough to vote")
else:
print("Please come back in {0}".format(18 - age)) |
8580b07e67a3498ed833fcf79689dd919aebe2b1 | avi651/PythonBasics | /HelloWorld/HelloWorld.py | 296 | 3.96875 | 4 | print("Hello World!")
print(1+2)
print(7+6)
print()
greeting = "Hello"
name = input("PlEASE ENTER YOUR NAME") #Its Like Scan f
print(greeting + " " + name)
splintString = "This string has been\nsplit over\nseveral\nlines"
print(splintString)
tabbedString = "1\t2\t3\t5\t6"
print(tabbedString)
|
9b2f359901f6a835563e878a9f103dec0b110a86 | nguiaSoren/Snake-game | /scoreboard.py | 1,123 | 4.3125 | 4 | from turtle import Turtle
FONT = ("Arial", 24, "normal")
#
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
# Set initials score to 0
self.score = 0
# Set colot to white
self.color("white")
# Hide the turtle, we wonly want to see the text
self.hideturtle()
# Do not draaw when the turtle will move
self.penup()
# Move the turtle to the top
self.goto(0,370)
# Write initial score
self.write(arg = f"Score: {self.score}", align="center", font=FONT)
def update_score(self):
"Update current score"
# Clear the screen (erase the writings and drawings)
self.clear()
# Update the score attribute
self.score += 1
# Write the new text with the new score
self.write(arg = f"Score: {self.score}", align="center", font=FONT)
def game_over(self):
"Show game over message"
# Show game over message at the center of the screen
self.goto(0,0)
self.write(arg = "Game Over", align="center", font=FONT) |
35f407f0a1398bd8588f0320bd6e63e79182eb66 | Yustynn/digital-world | /Past Exams/2016/Section C/QN7.py | 1,310 | 3.53125 | 4 | def maxProductThree(l):
'''
TEST CASE 1: 0 positive numbers
>>> maxProductThree([-5, -10, -12, -7])
-350
TEST CASE 2: 1 positive number
>>> maxProductThree([-5, 10, -12, -7])
840
TEST CASE 3: 2 positive numbers
>>> maxProductThree([-5, 10, -12, 7])
600
TEST CASE 4a: >3 positive numbers
>>> maxProductThree([-5, 10, 1, -12, 7])
600
TEST CASE 4b: >3 positive numbers
>>> maxProductThree([-5, 10, 9, -12, 7])
630
'''
prod = lambda nums: reduce(lambda prev, curr: prev*curr, nums)
l.sort()
positive = [n for n in l if n > 0]
negative = [n for n in l if n < 0]
num_positive = len(positive)
if num_positive == 0:
return prod(l[-3:])
if num_positive == 1:
return prod(l[0:2] + [l[-1]])
if num_positive == 2:
return prod(positive[-1:] + negative[-2:])
neg_poss = prod(negative[0:2])
pos_poss = prod(positive[-3:-1])
return l[-1] * max(neg_poss, pos_poss)
# Test Cases
#print maxProductThree([6,-3,-10,0,2])
#print maxProductThree([6,-3,-10,0,2, 1])
#print maxProductThree([6,3,-10,0,2, 1])
#print maxProductThree([11, 6,-3,-10,0,2, 1])
#print maxProductThree([4, 6,-3,-10,0,2, 1])
if __name__ == '__main__':
import doctest
doctest.testmod()
|
61f811e7f51828634bbbecae0c29310d1018c579 | ruanmirandac/Python | /exercicios/ex005.py | 222 | 3.984375 | 4 | # Exercício Python #005 - Antecessor e Sucessor
print(40*'=')
num1 = int(input('Digite um número:'))
print(f'O antecessor do número {num1} é {num1-1}')
print(f'O sucessor do número {num1} é {num1+1}')
print(40*'=')
|
d9442feba85d179b29b482bd6e804ac30afb4c6d | manasbundele/computer-vision-projects | /modified-mnist/resnet_mnist.py | 5,003 | 4 | 4 | '''
By: Manas Bundele
Project Constraints:
The goal is to train a CNN to recognize images of digits from the MNIST dataset. This dataset consists of
gray level images of size 28x28. There is a standard partitioning of the dataset into training and testing.
The training has 60,000 examples and the testing has 10,000 examples. Standard CNN models achieves over
99% accuracy on this dataset.
In this project you are asked to solve a similar problem of creating a classifier for the MNIST data. However,
the training data in our case has only 6,000 images, and each image is shrunk to size 7x7. Specifically,
your program must include the following:
1. Your program must set the random seeds of python and tensorflow to 1 to make sure that your results
are reproducible.
2. The first layer in the network must be a 4 ⇥ 4 maxpooling layer. This e↵ectively shrinks the images
from 28x28 to 7x7.
3. Your program will be tested by training on a fraction of 0.1 of the standard training set. The testing
data will be the entire standard testing set.
4. The training and testing in you program should not take more than 6 minutes.
Results:
The designed network was able to achieve over 90% accuracy in under 4 and 1/2 minutes.
based on code from https://www.tensorflow.org/tutorials
'''
import tensorflow as tf
import numpy as np
import cv2
# set the random seeds to make sure your results are reproducible
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(1)
# specify path to training data and testing data
folderbig = "big"
foldersmall = "small"
train_x_location = foldersmall + "/" + "x_train.csv"
train_y_location = foldersmall + "/" + "y_train.csv"
test_x_location = folderbig + "/" + "x_test.csv"
test_y_location = folderbig + "/" + "y_test.csv"
print("Reading training data")
x_train_2d = np.loadtxt(train_x_location, dtype="uint8", delimiter=",")
x_train_3d = x_train_2d.reshape(-1,28,28,1)
x_train = x_train_3d
y_train = np.loadtxt(train_y_location, dtype="uint8", delimiter=",")
print("Pre processing x of training data")
x_train = x_train / 255.0
# erosion: preprocessing to improve the visibility to the model
for image_index in range(x_train.shape[0]):
kernel = np.ones((2,2),np.uint8)
res = cv2.erode(x_train[image_index,:,:,:],kernel,iterations = 1)
res = res.reshape(-1,28,28,1)
x_train[image_index,:,:,:] = res
# Residual network
inputs = tf.keras.Input(shape=(28,28,1))
intermediate_output = tf.keras.layers.MaxPool2D(4, 4, padding='same')(inputs)
intermediate_output = tf.keras.layers.Conv2D(128, (2,2), padding='same')(intermediate_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
intermediate_output = tf.keras.layers.Conv2D(256, (2,2), padding='same')(intermediate_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
block_1_output = intermediate_output
intermediate_output = tf.keras.layers.Conv2D(128, 2, padding='same')(block_1_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
intermediate_output = tf.keras.layers.Conv2D(256, 2, padding='same')(intermediate_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
block_2_output = tf.keras.layers.add([intermediate_output, block_1_output])
intermediate_output = tf.keras.layers.Conv2D(256, 2, padding='same')(block_2_output)
intermediate_output = tf.layers.batch_normalization(intermediate_output)
intermediate_output = tf.keras.layers.Activation("relu")(intermediate_output)
intermediate_output = tf.keras.layers.Flatten()(intermediate_output)
intermediate_output = tf.keras.layers.Dense(512, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(intermediate_output)
intermediate_output = tf.keras.layers.Dropout(0.1)(intermediate_output)
outputs = tf.keras.layers.Dense(10, activation='softmax')(intermediate_output)
model = tf.keras.Model(inputs, outputs)
model.summary()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print("train")
model.fit(x_train, y_train, epochs=10)
print("Reading testing data")
x_test_2d = np.loadtxt(test_x_location, dtype="uint8", delimiter=",")
x_test_3d = x_test_2d.reshape(-1,28,28,1)
x_test = x_test_3d
y_test = np.loadtxt(test_y_location, dtype="uint8", delimiter=",")
print("Pre processing testing data")
x_test = x_test / 255.0
# erosion
for image_index in range(x_test.shape[0]):
kernel = np.ones((2,2),np.uint8)
res = cv2.erode(x_test[image_index,:,:,:],kernel,iterations = 1)
res = res.reshape(-1,28,28,1)
x_test[image_index,:,:,:] = res
print("evaluate")
model.evaluate(x_test, y_test)
|
a29cf36377da7f9ae513cd980c579aed1cd49ff1 | brianquinlan/learn-tensorflow | /positive-number-classifier/generatedata.py | 469 | 3.828125 | 4 | #!/usr/bin/env python3
"""Generate "data.csv", which is used as classifier training data.
The CSV file is formatted like:
value1,value2,positive
-3.12,4.23,True
-5,5,False
-4,-4.1,False
...
"""
import random
with open('data.csv', 'w') as f:
f.write('value1,value2,positive\n')
for _ in range(1000000):
value1 = random.uniform(-1000, 1000)
value2 = random.uniform(-1000, 1000)
f.write('%s,%s,%s\n' % (value1,value2,(value1+value2)>0)) |
bf3b9963811de2b52415398c637f3c25f64c72b6 | NoValeria/organiser | /utility/note.py | 3,415 | 3.640625 | 4 | from exceptions import MyException
from utility.my_date import MyDate
from utility.my_time import MyTime
class Note(object):
"""класс описывает заметку(задание)"""
def __init__(self, start: MyTime = None, end: MyTime = None, date: MyDate = None, title: str = None, description: str = None, important: int = None):
if start is not None and end is not None and start >= end:
raise MyException("Конечное время меньше или равно начальному!")
if title == "" or description == "":
raise MyException("Заполните все поля!")
# заполнение полей объекта
self.__start = start
self.__end = end
self.__date = date
self.__title = title
self.__description = description
self.__important = important
def __str__(self):
"""строковое представление заметки"""
answer = str(self.__start) + "-" + str(self.__end) + " "
answer += str(self.__date) + "\n" + self.__title + "\n" + self.__description
return answer
def __eq__(self, other):
if type(other) is Note:
return other.__date == self.__date and other.__start == self.__start
raise TypeError("Ошибка сравнения заметок!")
def set_by_database_row(self, row: list):
"""функция устанавливает значения полей класса исходя из списка
элементов, полученного из базы данных"""
self.__start = MyTime(s=row[4])
self.__end = MyTime(s=row[5])
self.__title = row[6]
self.__description = row[7]
self.__important = int(row[10])
d = MyDate()
d.set_date(int(row[1]), int(row[2]), int(row[3]))
self.__date = d
def to_mysql_list(self):
"""функция формирует список параметров для занесения заметки в БД"""
return (str(self.__date.get_day()), str(self.__date.get_month_number()),
str(self.__date.get_year()), str(self.__start), str(self.__end),
self.__title, self.__description, str(self.__date.get_number_of_week()),
self.__date.get_name_of_day_in_week(), str(self.__important))
def get_date(self) -> MyDate:
"""функция возвращает дату текущей заметки"""
return self.__date
def get_start(self) -> MyTime:
"""функция возвращает время начала текущего задания(заметки)"""
return self.__start
def get_end(self) -> MyTime:
"""функция возвращает время окончания текущего задания(заметки)"""
return self.__end
def get_title(self) -> str:
"""функция возвращает заголовок заметки"""
return self.__title
def get_description(self) -> str:
"""функция возвращает описание заметки"""
return self.__description
def is_important(self) -> bool:
"""функция возвращает значение важности заметки"""
return self.__important == 1
|
c0157c828d7736f95776068bb06718c3a5005f1f | DAVIDnHANG/DS-Unit-3-Sprint-2-SQL-and-Databases | /module2-sql-for-analysis/eleaphantsql.py | 3,033 | 3.8125 | 4 | import psycopg2
#read docs use help()
#help(psycopg2.connect)
#setting up for psycopy2.connect
dbname = 'wbtaflae'
user = 'wbtaflae'
password = 'PrFRj3SJLlpPBhmG8I0SY3ogazL6bmGz'
host = 'salt.db.elephantsql.com'
rpg_conn = psycopg2.connect( dbname =dbname, user=user, password=password, host=host)
print(rpg_conn)
#create the cursor once we established a connection to database server
rpg_curs = rpg_conn.cursor()
#once the cursor is established, we can now execute quires command
rpg_curs.execute('SELECT * FROM test_table;')
#this is the code to look at content of table.
rpg_curs.fetchall()
import sqlite3
#open connection to sql3
rpg_conn = sqlite3.connect('C:\\Users\\D3MoNa\\PycharmProjects\\Month3\\SQLAndDataBase\\module1-introduction-to-sql\\rpg_db.sqlite3')
#similar after connect to database we need a cursor
rpg_curs = rpg_conn.cursor()
#count how many character there are
print(rpg_curs.execute('select count(*) From charactercreator_character').fetchall())
#count how many unique names there are
print(rpg_curs.execute('select COUNT(distinct name) FROM charactercreator_character').fetchall())
#
character = rpg_curs.execute('SELECT * from charactercreator_character;').fetchall()
print(character[0],
character[-1],
len(character))
#get table schema. information to use to query tables in posques.
print('\n' , rpg_curs.execute('PRAGMA table_info(charactercreator_character);').fetchall())
#create the table for SQL.
create_character_tables = """
CREATE TABLE charactercreator_characters(
character_id Serial Primary key,
name VARCHAR(30),
level INT,
exp INT,
hp INT,
strength INT,
intelligence INT,
dexterity INT,
wisdom INT
);
"""
#just to show that we have an empty tables
#rpg_curs.execute(create_character_tables)
#show_tables = """
#SELECT *
#FROM pg_catalog.pg_tables
#WHERE schemaname != 'pg_catalog'
#AND schemaname != 'information_schema';
#"""
#rpg_curs.execute(show_tables)
rpg_curs.fetchall()
##turn into a string
##[1:] chop off the index. "serialNumber"
example_insert = """INSERT INTO charactercreator_character (name, level, exp, hp, strength, intelligence, dexterity, wisdom) VALUES """ + str(character[0][1:])
print(example_insert)
#how to do this for all rows? 302...
for character in character:
insert_character = """
INSERT INTO charactercreator_characters
(name, level, exp, hp, strength, intelligence, dexterity, wisdom)
VALUES """ + str(character[1:]) + ';'
rpg_curs.execute(insert_character)
print(insert_character)
rpg_curs.execute('SELECT * FROM charactercreator_characters;')
print(rpg_curs.fetchall())
rpg_curs.close()
rpg_conn.commit()
rpg_curs=rpg_conn.cursor()
rpg_curs.execute('SELECT * FROM charactercreator_characters;')
rpg_characters = rpg_curs.fetchall()
#do a for loop to check chracter is the same as
#for character, pg_character in zip(characters, pg_characters):
# assert character == pg_character
|
d088b276ca230b21476595bc9abc00086a211094 | pobingxiaoxiao/leopy | /leopy/algorithm/search.py | 477 | 3.953125 | 4 | '''
python implement of search algorithms.
'''
def binary_search(data, find):
'''
binary search of a sorted list.
'''
start = 0
stop = len(data)-1
while(stop>=start):
mid = int((start + stop)/2)
if(find == data[mid]):
print('the index is {}'.format(mid))
break
elif(find<data[mid]):
stop = mid-1
else:
start = mid+1
else:
print('the data is not in the list.') |
6f15a358204db42647368f4b628e36ae08754e5d | yize11/suoxue | /python爬虫/05/requests_session.py | 903 | 3.5625 | 4 | import requests
# 创建session对象,支持跨请求访问
cus_session = requests.session()
url = 'https://passport.jiayuan.com/dologin.php?pre_url=http://www.jiayuan.com/usercp/'
formdata = {
'name': '18518753265',
'password': 'ljh123456',
'remem_pass': 'on',
'_s_x_id': '7a106b00170857e594da431080ae0761',
'ljg_login': '1',
'm_p_l': '1',
'channel': '',
'position': '',
}
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
}
response = requests.post(url=url, data=formdata, headers=headers)
print(response.status_code)
if response.status_code == 200:
pageurl = 'http://usercp.jiayuan.com/v2/?from=login'
cus_session.get(url=pageurl, headers=headers)
if response.status_code == 200:
with open('page.html', 'w') as file:
file.write(response.text)
|
9f2629a5e6777831e577446199b8d78dee253b70 | gtenorio/Code-Eval-Challenges | /m_count_prime.py | 503 | 3.515625 | 4 | __author__ = 'Gio'
#Code Eval: Counting Primes
import sys
import math
def isPrime(ashton):
p = True
for j in range(2, int(math.sqrt(ashton))):
if (ashton % j == 0):
p = False
break
return(p)
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
a = ""
b = ""
c = 0
total = 0
temp = test.split(',')
for i in temp:
if c == 0:
a = int(i)
c += 1
else:
c = 0
b = int(i)
for eric in range(a, b):
if isPrime(eric):
total+=1
print(total)
test_cases.close()
|
4ff70b598377f2c513acc184232346c497245da7 | kishoraen1/kishore-python | /Ex12.py | 275 | 3.84375 | 4 | x = float (input ("Enter 1st Number = "))
y = int (input ("Enter 2nd Number = "))
ch = input ('Enter a Char = ') [0]
result = eval(input('Enter An Expression = '))
print(type(x))
print(type(y))
print(type(ch))
print (type(result))
z = x+y
print (z)
print(ch)
print (result)
|
3256df7c7a7003cb7ffe86abd873c0b6cc65b6bf | kishoraen1/kishore-python | /ifstatements.py | 319 | 4 | 4 | import math
x = int(input('Enter First Number of your choice = '))
y = int(input('Enter Second Number of your choice = '))
z = int(input('Enter Third Number of your choice = '))
if (x > y) and (x >z) :
print('X is Greatest')
elif (y > x) and (y >z):
print('Y is Greatest')
else:
print ('Z is Greatest')
|
7df95e08944b6e7ce18ce4213d730e6861c37ddd | kishoraen1/kishore-python | /numpy_arrays_Operations.py | 342 | 3.734375 | 4 | from numpy import *
from array import *
# array
arr1 = array('i',[1,10,3,24,5])
arr2 = array('i',[1,2,3,4,5])
arr3 = array('i',[])
for e in range(0, len(arr1)):
arr3.append (arr1[e] + arr2[e])
print(arr3)
max = 0
for i in range(0,len(arr1)):
if max > arr1[i]:
continue
else:
max = arr1[i]
print (max)
|
027440085636632a087c02a62ac9278ba94313cf | vuagieucot/pythoncorner | /Multi_Threading/threading1.py | 856 | 3.796875 | 4 | import threading
import time
class myThread(threading.Thread):
"""
Thread count down
"""
def __init__(self, threadId, name, count):
threading.Thread.__init__(self)
self._threadId = threadId
self._name = name
self._count = count
def run(self):
print('Starting: {}\n'.format(self._name))
print_time(self._name, 1, self._count)
print('Exiting: {}\n'.format(self._name))
def print_time(name, delay, count):
while count:
time.sleep(delay)
print('{0}: {1} {2}\n'.format(name, time.ctime(time.time()), count))
count -=1
thread1 = myThread(1, 'Thread-1', 10)
thread2 = myThread(2, 'Thread-2', 5)
thread3 = myThread(3, 'Thread-3', 20)
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
print('Finish main thread')
|
187aab7c76d32190b0ce030ad8487380bb435ab8 | vuagieucot/pythoncorner | /backtracking/sudoku_solver_base.py | 1,764 | 3.5 | 4 | from board import board
def solve(bo):
print_board(board)
print('='*25)
find = find_empty(bo)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if valid(bo, i, (row, col)):
bo[row][col] = i
if solve(bo):
return True
#backtrack if solve doesn't return True
bo[row][col] = 0
return False
def valid(bo, num, pos):
for i in range(len(bo[0])):
#if num in pos doesn't appear in another slot on same row
if bo[pos[0]][i] == num and pos[1] != i:
return False
for i in range(len(bo)):
#if num in pos doesn't appear in another slot on same column
if bo[i][pos[1]] == num and pos[0] != i:
return False
#check the 3x3 box containing position
#row = (3box_row, 3box_row + 3)
#row = (3box_col, 3box_col + 3)
box_row, box_col = pos[0]//3, pos[1]//3
for i in range(box_row*3, box_row*3+3):
for j in range(box_col*3, box_col*3+3):
if bo[i][j] == num and (i,j) != pos:
return False
return True
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print('-'*24)
for j in range(len(bo[0])):
if j%3 == 0 and j != 0:
print(' | ', end = '')
if j == 8:
print(bo[i][j])
else:
print(bo[i][j], end = ' ')
def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[i])):
if bo[i][j] == 0:
return (i, j) #row, column
return None
print_board(board)
print('='*25)
solve(board)
print_board(board)
|
bb448e97ec6a500d46668660d1ee6007a4bfbd46 | kornel45/rocket_game | /text_styler.py | 1,905 | 3.671875 | 4 | from typing import Tuple, List
import pygame
def make_font(fonts: list, size: int) -> pygame.font.Font:
"""
Method responsible for making font of certain size. You can specify name of font, then it will
be searched in system fonts. If None then default font will be returned
:param fonts: list of fonts
:param size: size
:return: pygame surface representing font
"""
available = pygame.font.get_fonts()
choices = map(lambda font: font.lower().replace(' ', ''), fonts)
for choice in choices:
if choice in available:
return pygame.font.SysFont(choice, size)
return pygame.font.Font(None, size)
_cached_fonts = {}
def get_font(font_preferences: List[str], size: int) -> pygame.font.Font:
"""
Method responsible for creating (if not already cached) and getting font surface
:param font_preferences: font name
:param size: font size
:return: pygame surface representing font
"""
global _cached_fonts
key = str(font_preferences) + '|' + str(size)
font = _cached_fonts.get(key, None)
if font is None:
font = make_font(font_preferences, size)
_cached_fonts[key] = font
return font
_cached_text = {}
def create_text(text: str, fonts: list, size: int, color: Tuple[int, int, int]) -> pygame.Surface:
"""
Method responsible for rendering image from pygame font surface
:param text: text we want to show
:param fonts: fonts we want to use (first available will be chosen)
:param size: size of text
:param color: color of text
:return: image of a rendered pygame font
"""
global _cached_text
key = '|'.join(map(str, (fonts, size, color, text)))
image = _cached_text.get(key, None)
if image is None:
font = get_font(fonts, size)
image = font.render(text, True, color)
_cached_text[key] = image
return image
|
4a1f6d688bff6f9fd75d547242a506ece1d4b22b | anshu3012/ENPM-661_Project-3_Phase_3-4_Group_38 | /Phase 3/Astar_rigid_nonholo.py | 14,872 | 3.546875 | 4 | # ENPM661
# Project 3 Phase 3
# Group 38
# ===== Libraries =====
import numpy as np
import cv2
import math
from math import pi
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.patches import Polygon
import time
# ===== User Inputs (Error-checking and robot dimensions) =====
print("This code will implement A* Algorithm for a Rigid Robot with Non-Holonomic Constraints")
# Error-checking functions
def inputNum(message):
"""Only takes an integer as input"""
while True:
user = input(message)
try:
output = float(user)
break;
except ValueError:
print('\n!!! ERROR !!! Input needs to be a number. Please try again.\n')
return output
def inputNumZeroPos(message):
"""Only allows numbers 0 and above"""
output = inputNum(message)
while output < 0:
print("\n!!! ERROR !!! Please enter a number that is 0 or positive.\n")
output = inputNum(message)
return output
# Robot wheel radius, distance between wheels, and clearance
wheel_radius = 0.038
dist_bw_wheels = 0.354
clearance = inputNumZeroPos("Please enter the desired clearance: ")
clr = clearance
# ===== Map =====
# Map dimensions
xMin = -5.1
xMax = 5.1
yMin = -5.1
yMax = 5.1
# Generate map
fig, ax = plt.subplots()
ax.set(xlim=(xMin,xMax), ylim = (yMin, yMax))
plt.grid()
plt.xlim(xMin,xMax)
plt.ylim(yMin,yMax)
plt.title('ENPM661 Project-3 Phase-3 Group-38',fontsize=10)
# ===== Obstacles =====
# Plot obstacles
# circles
centres = [(0, 0), (2, 3), (-2, -3), (2, -3)]
cirR = 1 + clr
for centre in centres:
ax.add_artist(plt.Circle(centre, cirR, color = "red"))
# squares
corners = [(-4.85, -0.75), (-2.85, 2.35), (3.35, -0.75)]
for corner in corners:
ax.add_artist(plt.Rectangle((corner[0] - clr, corner[1] - clr), 1.5 + 2 * clr, 1.5 + 2 * clr, fc='r'))
# border
rc = clr + 0.1 # border of map
borderTop = [[xMax,yMax],[xMax,yMax - rc],[xMin,yMax - rc],[xMin,xMax]] # top border
borderRight = [[xMax,yMax],[xMax,yMin],[xMax - rc,yMin],[xMax - rc,yMax]] # right border
borderBottom = [[xMax,yMin + rc],[xMax,yMin],[xMin,yMin],[xMin,yMin + rc]] # bottom border
borderLeft = [[xMin + rc,yMax],[xMin + rc,yMin],[xMin,yMin],[xMin,yMax]] # left border
ax.add_artist(Polygon(borderTop, color = "red"))
ax.add_artist(Polygon(borderRight, color = "red"))
ax.add_artist(Polygon(borderBottom, color = "red"))
ax.add_artist(Polygon(borderLeft, color = "red"))
# Function to check if point is inside obstacle
def inside_obstacle(x,y):
"""Returns true if x,y coordinate is inside obstacle
Returns false if x,y coordinate is NOT inside obstacle"""
obstacle_check = 0 # 0 means not inside obstacle, 1 means inside obstacle
# circles
centres = [(0, 0), (2, 3), (-2, -3), (2, -3)]
cirR = 1 + clr
for centre in centres:
cirX = centre[0]
cirY = centre[1]
if ((x - cirX)**2 + (y - cirY)**2) <= cirR**2:
#print("HIT CIRCLE")
obstacle_check = 1
# squares
corners = [(-4.85, -0.75), (-2.85, 2.35), (3.35, -0.75)]
for corner in corners:
if x >= (corner[0] - clr) and y >= (corner[1] - clr)\
and y <= (corner[1] + 1.5 + clr) and x <= (corner[0] + 1.5 + clr):
#print("HIT SQUARE")
obstacle_check = 1
# border
rc = clr + 0.1 # border of map
if x <= xMin + rc or x >= xMax - rc:
#print("HIT BORDER")
obstacle_check = 1
if y <= yMin + rc or y >= yMax - rc:
#print("HIT BORDER")
obstacle_check = 1
if obstacle_check == 1:
return True
else:
return False
# ===== User Inputs (Coordinates) =====
# Error Checking functions
def inputNumX(message):
"""Only allows numbers between start and end"""
output = inputNum(message)
while output < xMin or output > xMax:
print("\n!!! ERROR !!! Please enter a number between ", xMin, " and ", xMax, "\n")
output = inputNum(message)
return output
def inputNumY(message):
"""Only allows numbers between start and end"""
output = inputNum(message)
while output < yMin or output > yMax:
print("\n!!! ERROR !!! Please enter a number between ", yMin, " and ", yMax, "\n")
output = inputNum(message)
return output
# Start point coordinates
start_cords_x = inputNumX("Please enter the starting x coordinate: ")
start_cords_y = inputNumY("Please enter the starting y coordinate: ")
# Obstacle check
while inside_obstacle(start_cords_x,start_cords_y) == 1:
print("\n!!! ERROR !!! Coordinates inside obstacle. Please try again.\n")
start_cords_x = inputNumX("Please enter the starting x coordinate: ")
start_cords_y = inputNumY("Please enter the starting y coordinate: ")
# Starting angle
start_theta = inputNum("Please enter the starting angle in degrees: ")
start_theta = start_theta*pi/180 # convert deg to radians
# Goal point coordinates
goal_cords_x = inputNumX("Please enter the goal x coordinate: ")
goal_cords_y = inputNumY("Please enter the goal y coordinate: ")
# Obstacle check
while inside_obstacle(goal_cords_x,goal_cords_y) == 1:
print("\n!!! ERROR !!! Coordinates inside obstacle. Please try again.\n")
goal_cords_x = inputNumX("Please enter the goal x coordinate: ")
goal_cords_y = inputNumY("Please enter the goal y coordinate: ")
# Wheel velocity inputs
rpm1 = inputNum("Please enter a wheel speed in RPM: ")
rpm2 = inputNum("Please enter another wheel speed in RPM: ")
# ===== Action Set =====
# Threshold
thresholdXY = 0.4 # Creates a 500 x 500 map to explore
thresholdTheta = 30 # Angle [deg] threshold for theta
# 8-action set using user-defined wheel speeds
actions = [[0,rpm1],\
[rpm1,0],\
[rpm1,rpm1],\
[0,rpm2],\
[rpm2,0],\
[rpm2,rpm2],\
[rpm1,rpm2],\
[rpm2,rpm1]]
# Generate node
def generate_node_location(uL,uR,point):
"""
8-action space
Inputs:
uL: Left wheel RPM
uR: Right wheel RPM
x: Initial X cartesian coordinate of robot
y: Initial Y cartesian coordinate of robot
theta: Initial theta angle of robot in RADIANS
Output:
xF: Final X cartesian coordinate of robot
yF: Final Y cartesian coordinate of robot
thetaF: Final theta angle of robot in RADIANS
cost: Final cost
"""
# Parameters
x = point[0]
y = point[1]
theta = point[2]
r = wheel_radius
L = dist_bw_wheels
#print("point ", point)
# Final position and cost calculation
t=0
dt=0.1
cost = 0
while t<2:
t=t+dt
dx=(r/2)*(uL+uR)*math.cos(theta)*dt
dy=(r/2)*(uL+uR)*math.sin(theta)*dt
dtheta=(r/L)*(uR-uL)*dt
dcost = math.sqrt(dx**2 + dy**2)
x=x+dx
y=y+dy
theta=theta+dtheta
cost += dcost
new_point = [x,y,theta]
base_cost = cost
#print("new_point ", new_point)
#print("base_cost ", base_cost)
return new_point, base_cost
# ===== Node class and functions =====
class Node:
def __init__(self, point):
self.point = point # [x, y, theta]
self.cost = math.inf # initially all the new nodes have infinite cost attached to them
self.parent = None
self.action = [0,0] # [w1,w2] left and right wheel speeds
def pop_queue_element(queue): # Priority Queue, outputs the node with least cost attached to it
min_a = 0
for elemt in range(len(queue)):
if queue[elemt].cost < queue[min_a].cost:
min_a = elemt
return queue.pop(min_a)
def cost_to_goal(point, goal_node_pos):
point = [point[0],point[1]]
point_x = point[0]
point_y = point[1]
goal_x = goal_node_pos[0]
goal_y = goal_node_pos[1]
euc_dist = np.sqrt((point_x-goal_x)**2 + (point_y-goal_y)**2)
point = np.array(point)
goal = np.array(goal_node_pos)
euc_dist = np.linalg.norm(point - goal)
return euc_dist
def find_node(point, queue):
for elem in queue:
if elem.point == [[int(point[0]/thresholdXY)],[int(point[1]/thresholdXY)],[int(point[2]/thresholdTheta)]]:
return queue.index(elem)
else:
return None
# Check if path crosses inside obstacle
def path_inside_obstacle(uL,uR,point):
"""
Checks if curve path goes inside an obstacle
Returns true if path crosses obstacle
Returns false if path is free of obstacles
Inputs:
uL: Left wheel speed
uR: Right wheel speed
point: [x,y,theta] robot position and angle
"""
path_check = 0
# 0 is path is NOT inside obstacle
# 1 is path is inside obstacle
# Parameters
x = point[0]
y = point[1]
theta = point[2]
r = wheel_radius
L = dist_bw_wheels
# Curve path
t=0
dt=0.001 #fine resolution to detect while path draws inside an obstacle
while t<2:
t=t+dt
dx=(r/2)*(uL+uR)*math.cos(theta)*dt
dy=(r/2)*(uL+uR)*math.sin(theta)*dt
dtheta=(r/L)*(uR-uL)*dt
x=x+dx
y=y+dy
theta=theta+dtheta
if inside_obstacle(x,y) == 1:
path_check = 1
break
if path_check == 1:
return True
else:
return False
# Plot curve
def plot_curve(uL,uR,point,color):
"""
Plots curve in matplotlib
Inputs:
uL: A user-defined wheel speed in RPM
uR: Another user-defined wheel speed in RPM
point: [x,y,theta] current point and angle of robot
color: "color" of plot line
"""
# Parameters
x = point[0]
y = point[1]
theta = point[2]
r = wheel_radius
L = dist_bw_wheels
#print("point ", point)
# Plot
t=0
dt=0.1
while t<2:
t=t+dt
dx=(r/2)*(uL+uR)*math.cos(theta)*dt
dy=(r/2)*(uL+uR)*math.sin(theta)*dt
dtheta=(r/L)*(uR-uL)*dt
plt.plot([x,x+dx],[y,y+dy], color)
x=x+dx
y=y+dy
theta=theta+dtheta
plt.pause(0.001)
# ===== Generate graph =====
ax.set_aspect('equal')
print("Generating graph")
# A star search algorithm
def a_star_algo(clr, start_node_pos, goal_node_pos):
# Initial parameters
start_node = Node(start_node_pos)
start_node.cost = 0
xRange = abs(xMin - xMax)
yRange = abs(yMin - yMax)
thetaRange = 360
visited = np.zeros([int(xRange/thresholdXY),int(yRange/thresholdXY),int(thetaRange/thresholdTheta)])
queue = [start_node]
nodes = [[start_cords_x,start_cords_y,start_theta,0,0]]
counter = 0
# Show goal region
goal_region = 0.3
ax.add_artist(plt.Circle((goal_cords_x, goal_cords_y), goal_region, color = "green"))
# A star search
while queue:
current_node = pop_queue_element(queue)
current_point = current_node.point
visited[int(current_point[0]/thresholdXY)][int(current_point[1]/thresholdXY)][int(current_point[2]/thresholdTheta)] = 1
if ((current_point[0] - goal_node_pos[0])**2 + (current_point[1] - goal_node_pos[1])**2) <= goal_region**2:
print("Goal reached")
#print("current_point[0] ", current_point[0])
#print("current_point[1] ", current_point[1])
return current_node, nodes, counter
for action in actions:
w1 = action[0]
w2 = action[1]
new_point, base_cost = generate_node_location(w1,w2,current_point)
in_obstacle = inside_obstacle(new_point[0],new_point[1])
path_in_obstacle = path_inside_obstacle(w1,w2,new_point)
if in_obstacle != 1 and path_in_obstacle == False:
new_node = Node(new_point)
new_node.parent = current_node
new_node.action = [w1,w2]
if visited[int(new_point[0]/thresholdXY)][int(new_point[1]/thresholdXY)][int(new_point[2]/thresholdTheta)] == 0:
new_node.cost = base_cost + new_node.parent.cost + cost_to_goal(new_point, goal_node_pos)
visited[int(new_point[0]/thresholdXY)][int(new_point[1]/thresholdXY)][int(new_point[2]/thresholdTheta)] = 1
queue.append(new_node)
nodes.append([current_point[0],current_point[1],current_point[2],w1,w2])
counter += 1
plot_curve(w1,w2,current_point,"black")
if ((new_point[0] - goal_node_pos[0])**2 + (new_point[1] - goal_node_pos[1])**2) <= goal_region**2:
print("Goal reached")
#print("current_point[0] ", current_point[0])
#print("current_point[1] ", current_point[1])
return new_node, nodes, counter
else:
node_exist_index = find_node(new_point, queue)
if node_exist_index is not None:
temp_node = queue[node_exist_index]
if temp_node.cost > base_cost + new_node.parent.cost + cost_to_goal(new_point, goal_node_pos):
temp_node.cost = base_cost + new_node.parent.cost + cost_to_goal(new_point, goal_node_pos)
temp_node.parent = current_node
else:
continue
return None, nodes, counter
start_node_pos = [start_cords_x, start_cords_y, start_theta]
goal_node_pos = [goal_cords_x, goal_cords_y] # goal theta ignored
# Record time
start_time = time.time()
# Search map
result, nodes, counter = a_star_algo(clr, start_node_pos, goal_node_pos)
# Print final time
print("Time explored = %2.3f seconds " % (time.time() - start_time))
# ===== Backtrack =====
print("Backtracking...")
def track_back(node):
p = list()
p.append(node)
p.append(node.parent)
parent = node.parent
if parent is None:
return p
while parent is not None:
p.append(parent)
parent = parent.parent
p_rev = list(p)
return p_rev
if result is not None:
nodes_list = track_back(result)
x = []
y = []
theta = []
w1 = []
w2 = []
for elem in nodes_list:
x.insert(0,elem.point[0])
y.insert(0,elem.point[1])
theta.insert(0,elem.point[2])
w1.insert(0,elem.action[0])
w2.insert(0,elem.action[1])
for index in range(1,len(x)):
if index != (len(x) - 2):
X = x[index - 1]
Y = y[index - 1]
Theta = theta[index - 1]
W1 = w1[index]
W2 = w2[index]
#print("x ", X, "y ", Y, "theta ", Theta, "w1 ", W1, "w2 ", W2)
plot_curve(W1,W2,[X,Y,Theta],"blue")
print("Search complete. Close window to close program")
else:
print("Sorry, result could not be reached")
# Show map
plt.show()
plt.close()
# END
|
b573b7b9a21a1d10bb188a792ed54a8c70726ffd | sca4cs/Data-Structures | /queue/queue.py | 517 | 3.6875 | 4 | import sys
sys.path.append('../linked_list')
from linked_list import LinkedList
class Queue:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def enqueue(self, item):
self.storage.add_to_tail(item)
self.size += 1
def dequeue(self):
if self.size > 0:
self.size -= 1
return self.storage.remove_head()
def len(self):
# length = 0
# h = self.storage.head
# while h:
# length += 1
# h = h.get_next()
# return length
return self.size
|
03b349b074f375a123a1dcb3446e13dee2276a79 | luzperdomo92/test_python | /for_loop.py | 101 | 3.5625 | 4 | prices =[10, 20, 20]
total = 0
for item in prices:
total += item
print("total {}".format(total))
|
ddfe13cbff04a326ed196b20beb8f1414364b086 | luzperdomo92/test_python | /hello.py | 209 | 4.25 | 4 | name = input("enter your name: ")
if len(name) < 3:
print("name must be al least 3 characters")
elif len(name) > 20:
print("name can be a maximun 50 characteres")
else:
print("name looks good!")
|
e0c9d64fc8ec7f496d330b1a54f415918ff9b176 | VakhoGeoLab/J_davalebebi | /Davaleba_3.py | 325 | 3.828125 | 4 |
def pyramid(number):
pyr_result = "a" * number
return pyr_result
def illuminati(number):
x = 0
space = 0
while x <= number:
space = int((number - x) / 2)
space_result = " " * space
print(space_result, pyramid(x))
x += 2
def main():
illuminati(14)
main() |
529d0a319ac6368dc8e5a8d3bf8b03aead86c409 | roadpilot/learning-python | /chap06/2-for.py | 148 | 3.875 | 4 | #!/usr/bin/env python3
animals = ('bear', 'bunny', 'swordfish', 'cat')
for pet in animals:
print(pet)
for pet in range(5):
print(pet) |
4263e428cb002dfcbae8d38c6be9e2c475805d53 | racheliWeiss/birthday-wishert | /main.py | 2,916 | 3.71875 | 4 | import smtplib
import pandas
import datetime as dt
import random
now = dt.datetime.now()
day = now.day
month = now.month
today = (month, day)
birthday = pandas.read_csv("birthdays.csv")
MY_EMAIL = "rhlywyyys@gmail.com"
MY_PASSWORD= "RACHELI200"
birthday_dict = {(data_row.month, data_row.day): data_row for (index, data_row) in birthday.iterrows()}
if today in birthday_dict:
birthday_Person = birthday_dict[today]
file_path = f"letter_templates/letter_{random.randint(1,3)}.txt"
with open(file_path) as file_letter:
contants = file_letter.read()
contants=contants.replace("[name]", birthday_Person["name"])
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(MY_EMAIL, MY_PASSWORD)
connection.sendmail(from_addr=MY_EMAIL,
to_addrs=birthday_Person["email"],
msg=f"Subject:Happy Birthday\n\n{contants}"
)
##################### Normal Starting Project ######################
# 2. Check if today matches a birthday in the birthdays.csv
# HINT 1: Create a tuple from today's month and day using datetime. e.g.
# today = (today_month, today_day)
# HINT 2: Use pandas to read the birthdays.csv
# HINT 3: Use dictionary comprehension to create a dictionary from birthday.csv that is formated like this:
# birthdays_dict = {
# (birthday_month, birthday_day): data_row
# }
#Dictionary comprehension template for pandas DataFrame looks like this:
# new_dict = {new_key: new_value for (index, data_row) in data.iterrows()}
#e.g. if the birthdays.csv looked like this:
# name,email,year,month,day
# Angela,angela@email.com,1995,12,24
#Then the birthdays_dict should look like this:
# birthdays_dict = {
# (12, 24): Angela,angela@email.com,1995,12,24
# }
#HINT 4: Then you could compare and see if today's month/day tuple matches one of the keys in birthday_dict like this:
# if (today_month, today_day) in birthdays_dict:
# 3. If there is a match, pick a random letter (letter_1.txt/letter_2.txt/letter_3.txt) from letter_templates and replace the [NAME] with the person's actual name from birthdays.csv
# HINT 1: Think about the relative file path to open each letter.
# HINT 2: Use the random module to get a number between 1-3 to pick a randome letter.
# HINT 3: Use the replace() method to replace [NAME] with the actual name. https://www.w3schools.com/python/ref_string_replace.asp
# 4. Send the letter generated in step 3 to that person's email address.
# HINT 1: Gmail(smtp.gmail.com), Yahoo(smtp.mail.yahoo.com), Hotmail(smtp.live.com), Outlook(smtp-mail.outlook.com)
# HINT 2: Remember to call .starttls()
# HINT 3: Remember to login to your email service with email/password. Make sure your security setting is set to allow less secure apps.
# HINT 4: The message should have the Subject: Happy Birthday then after \n\n The Message Body.
|
631b16127effc928bed56d0f9634b5fdd190795d | RashedNuman/Projects | /Russian Translator.py | 1,709 | 3.78125 | 4 | """
Russian Translator
Written in Python 3.8.1
requires words.txt document
"""
import io
import sys
import time
import os as system
def examples():
print("\n \n \n")
print('=' *25)
print("\n")
with open("words.txt", "r") as file:
for line in file:
word = line.split()[0]
print(word + "\n")
print('=' *25)
return None
def translator():
if system.path.isfile("./words.txt") == True:
print("\n \n Dictionary file found... Continuing... \n \n")
else:
print("\n \n Dictionary File not found, please place words.txt in the same directory as the code then run again")
sys.exit()
english_phrase = str(input("Translate : "))
english_word_list = english_phrase.split()
russian_phrase = ''
for en_word in english_word_list:
with open("words.txt", "r") as file:
for line in file:
x = line.split()
if x[0] == en_word:
translated = x[2]
russian_phrase += translated + " "
file.close()
print(russian_phrase)
return None
print("Welcome to the russian translator \n")
print("it can only translate very few phrases / words due to the insane manual work needed \n")
while True:
menu = str(input(" \n Enter 1 to continue or 2 to display translation dictionary or 0 to exit : "))
if menu == '1':
translator()
elif menu == '2':
examples()
elif menu == '0':
sys.exit()
|
daf14930f91f00be998a203212c8932c495c94f2 | RashedNuman/Projects | /Ceaser Cipher Encryptor.py | 10,487 | 4.0625 | 4 | """
Ceaser Cipher Encryptor
Description: Python script that runs ceaser cipher on a txt document, encrypts
decrypts files, can also encrypt based on date
Language: python 3.8.1
Author : Rashed Alnuman
"""
# importing libraries at the start to use
import sys
import errno
import time
from datetime import datetime
def main():
"""
void function
no parameters
Main function, displays a interactive selection menu that prompts the user to enter a valid
input to choose the service they wish to use, in case of invalid input loops back to prompt
for valid input. Surrounded by try-catch block which either restarts the main function to
handle an exception. upon user choice to exit, exits with exit code 0
"""
try:
print(" \t Hello to the Ceaser Cipher \n \n")
choice = int(input("Enter 1 to encrypt, Enter 2 to decrypt, Enter 3 to Exit: "))
except EOFError:
main()
if choice == 1:
while True:
choice2 = int(input("Enter 1 to encrypt manually by key, Enter 2 to encrypt by date: "))
if choice2 == 1:
manual_encrypt()
break
elif choice2 == 2:
encrypt_date()
break
else:
print("Invalid input, please pick a correct option")
continue
elif choice == 2:
decrypt()
elif choice == 3:
sys.exit(0)
else:
print("Invalid choice, please enter a valid choice")
main()
def encrypt_date():
"""
void function
no parameters
Encrypts based on the current day of the month, uses daytime and the now() method
to extract the current date and then extract the day of the month to place it as
the key. For the sake of simplicity theres no point in the key being greater than
25 which loops back and causes potential errors, key value is altered to be less
than 25 if the day of month is more than 25. callst he encrypt function to continue
"""
try:
current_date = str(datetime.date(datetime.now()))
date_split = current_date.split("-")
key = int(date_split[2])
while key > 25:
key = key //2 +5
file = str(input("Enter file name: "))
filename = open(file, "r+")
string = filename.read()
encrypt(string, key, 1)
except IOError as ioe:
if ioe.errno == errno.EACCES:
print("Unreadable File, please enter a readable file... \n \n")
encrypt_date()
elif ioe.errno == errno.ENOENT:
print("File does not exist, enter a existing file... \n \n")
encrypt_date()
except Exception:
print("An error has occured \n \n")
main()
###########
def manual_encrypt():
"""
void function
no parameters
manual encryption prompts the user to manually enter an encryption key.
The value of the key cannot be less than 1 nor greater than 25. User is
prompted to enter a new value everytime the key is an invalid value.
calls the encrypt function to continue the encryption process
"""
try:
key = int(input("Enter the left shift value key: "))
if key < 1 or key > 25:
print("Key value cannot exceed 25 or go below 1, enter a new value")
encrypt()
file = str(input("Enter file name: "))
filename = open(file, "r+")
string = filename.read()
encrypt(string, key, 0)
except IOError as ioe:
if ioe.errno == errno.EACCES:
print("Unreadable File, please enter a readable file... \n \n")
manual_encrypt()
elif ioe.errno == errno.ENOENT:
print("File does not exist, enter a existing file... \n \n")
manual_encrypt()
except Exception:
print("An error has occured \n \n")
main()
#######################
def encrypt(string, key, stat):
"""
void function
parameters: str() String, int() key, int() stat
Encrypts the string provided based on the key, and removes hidden key in the file
in case the file was automatically encrypted by date. encrypts the string by
altering the ascii value to change it to another letter, cannot translate to non
letters, will revolve back to the end of the alphabet if it goes out of letter range.
Does not encrypt blank spaces or non letters.
writes the encrypted data on a new file.
"""
try:
text = ""
for i in string:
for k in i:
if ord(k) >= 97 and ord(k) <= 122:
if ord(k) - key < 97:
letter = chr( ord(k) +26 -key)
text += letter
else:
letter = chr( ord(k) - key)
text += letter
elif ord(k) >= 65 and ord(k) <= 90: # if its a capital
if ord(k) - key < 65:
letter = chr( ord(i) +26 -key)
text += letter
else:
letter = chr( ord(k) - key)
text += letter
else:
text += k
encrFile = str(input("Encrypted file name: "))
newfile = open(encrFile +".txt", "w+")
if stat == 0:
newfile.write(text)
else:
x = 'k'+str(key)
newfile.write(text+x)
newfile.close()
print("encryption successfull")
print("Your encrypted text has been saved as " + encrFile + ".txt")
print("returning to main menu... \n \n")
time.sleep(2)
main() # Calls the main function again
except IOError:
print("Error occured during encryption, possibly unreadable data or corrupt file, return to menu... \n \n")
main()
except Exception:
print("An unknown error has occured, returning to menu... \n \n")
main()
def decrypt():
"""
void function
no parameters
reverses the algorithm of the encrypt function. in case file was
automatically encyrpted by date, extracts the key from the file
decrypts it automatically also.
writes the decrypted data on a new file
"""
try:
try:
file = input("Enter the txt file you wish to decrypt: ")
myfile = open(file, "r+")
file_text = myfile.read()
method = int(input("Enter 1 to decrypt manually or 2 for auto detection decryption: "))
if method == 1:
key = int(input("Enter the key: "))
file_text2 = file_text
elif method == 2:
# Extracts the key from the file
file_key = ""
for i in range(len(file_text) -1, 0, -1):
x = file_text[i]
if x == "k":
file_key += x
break
file_key += x
old = file_key.replace('k',"")
key = int(old[::-1])
remove = 'k'+str(key)
file_text2 = file_text.replace(remove,"")
except EOFError:
print("Stop messing with the space bar please, \n \n")
decrypt()
except ValueError:
print("Invalid input type, enter the apporpiate data type in inputs... \n \n")
decrypt()
text = ""
for i in file_text2:
for k in i:
if ord(k) >= 97 and ord(k) <= 122:
if ord(k) + key > 122:
letter = chr( ord(k) - 26 + key)
text += letter
else:
letter = chr(ord(k) + key)
text += letter
elif ord(k) >= 65 and ord(k) <= 90:
if ord(k) + key > 90:
letter = chr( ord(k) -26 +key)
text += letter
else:
letter = chr(ord(k) + key)
text += letter
else:
text += k
print(text)
print("decryption successfull")
name = str(input("Decryption file name: "))
newfile = open(name+".txt", "w+")
newfile.write(text)
newfile.close()
time.sleep(2)
main()
except IOError as ioe:
if ioe.errno == errno.EACCES:
print("Unreadable File, please enter a readable file... \n \n")
decrypt()
elif ioe.errno == errno.ENOENT:
print("File does not exist, enter a existing file... \n \n")
decrypt()
except IndexError:
print("Could not process key in the data file, may be altered or corrupt... \n \n")
decrypt()
except ValueError:
print("Could not identify file key in the data file, enter the key manually... \n \n")
decrypt()
except Exception:
print("Unknown problem has occured, Either UTF error or something else, returning to menu... \n \n")
main()
#---------------------------------------------------------------------------------------------------#
main() # calling the main function to start the code
|
f2ff7a9d8dab2e486422394a1bac5b46ec84c986 | naoya7076/math_puzzle | /python/question1.py | 283 | 3.5625 | 4 | num = 11
while True:
num_str = str(num)
bin_str = format(num, 'b')
oct_str = format(num, 'o')
if num_str == num_str[::-1]\
and bin_str == bin_str[::-1]\
and oct_str == oct_str[::-1]:
print(num)
break
else:
num += 2
|
15b01864d211e3bd0010709f428df92c75f33e80 | ocoyoyix/cookieTest | /mutations.py | 4,205 | 3.78125 | 4 | """
Authors: Orlando Coyoy, Ya'Kuana Davis, Roger Trejo
Course Name: CSCI 3725
Assignment Name: PQ1
Date: September 25, 2020
Description: This file includes a collection of functions that will either assist or cause mutations on given recipe objects
"""
import random
from classes import Recipe, Ingredient
def ingredient_from_set(file_list, ingredient_names, amount=False):
"""Returns an ingredient from the inspiring set.A boolean is sent in the parameter to determine if we also need to change the ingredients amount"""
# Finds the random file
if(len(file_list) == 1):
afile = file_list[0]
else:
afile = file_list[random.randint(0, (len(file_list)-1))]
# This while loop ensures that the chosen ingredient from the i
# nspiring set does not match an ingredient in the curent
# list of ingredients
while(True):
# Chooses a random line from the random file
lines = open(afile).read().splitlines()
my_line = random.choice(lines)
print(my_line)
# ingredient_name = my_line.split(' g ')[1]
if (my_line.find(" g ") != -1):
ingredient_name = my_line.split(' g ')[1]
ingredient_amount = my_line.split()[0]
else:
ingredient_name = " ".join(my_line.split()[1:])
if(ingredient_names.count(ingredient_name) == 0):
if (amount):
return Ingredient(ingredient_name, ingredient_amount)
else:
return ingredient_name
def change_ingredient_amount(recipe_obj):
"""Changes the ingredient amount of a random selected ingredient."""
# gets a random ingredient to change
ingredient = random.choice(recipe_obj.ingredients)
previous_amount = ingredient.amount
new_amount = random.randrange(1, 10)
# this if statement makes sure that
# there will always be a change in the amount
if previous_amount == new_amount:
new_amount += 1
ingredient.amount = new_amount
# Calculates the new total ounces of ingredients
# in the recipe and then normalizes each quantity for
# the final total to equal 100
def change_ingredient_name(recipe_obj, file_list):
"""An ingredient is selected uniformly at random from the recipe.
Its name is changed to that of another ingredient that is chosen at random
from the ones in the inspiring set."""
ingredient = random.choice(recipe_obj.ingredients)
new_name = ingredient_from_set(file_list, recipe_obj.ingredients)
# This is where the ingredient name is changed
while (ingredient.name == new_name):
new_name = ingredient_from_set(file_list, recipe_obj.ingredients)
ingredient.name = new_name
# Calculates the new total ounces of ingredients
# in the recipe and then normalizes each quantity for
# the final total to equal 100
def change_topping(recipe_obj, file_list):
"""A topping is selected uniformly at random from the recipe. This topping is replaced with another random topping from the topping set"""
existing_toppings = recipe_obj.get_toppings()[1]
new_ing = ingredient_from_set(file_list, existing_toppings, True)
if(len(recipe_obj.get_toppings()[0]) == 0):
recipe_obj.ingredients.append(new_ing)
else:
index_to_change = random.choice(recipe_obj.get_toppings()[0])
recipe_obj.ingredients[index_to_change] = new_ing
def add_ingredient(recipe_obj, file_list):
"""An ingredient is selected uniformly at random from the inspiring set
and added to the recipe."""
ingredient_name = ingredient_from_set(file_list, recipe_obj.ingredients)
# The amount of the new ingredient will be an int ,i, such that
# 1<=1<10
ingredient_amount = random.randrange(1, 10)
recipe_obj.ingredients.append(
Ingredient(ingredient_name, ingredient_amount))
def delete_ingredient(recipe_obj):
"""An ingredient is selected uniformly at random from the recipe,
and removed from the recipe."""
# random ingredient index is chosen
choose_ingredient = random.randint(0, len(recipe_obj.ingredients) - 1)
# removes the ingredient from the recipe object
recipe_obj.ingredients.pop(choose_ingredient)
|
8f2c41872f9b14089c2d2c6cfd7bcc458e1199ce | ste920ven/project2-pd7 | /Group_1/storage/factual-proof-trial2.py | 636 | 3.5 | 4 | #!/usr/bin/python
#based on Mr. Z's NYT rest code
import urllib
import json
import sys
class Rester:
def __init__(self,url):
self.url = url
def call(self,q):
urlstring = "%s?%s"%(self.url,q)
print urlstring
request = urllib.urlopen(urlstring)
#result = request.read();
result = json.loads(request.read())
return result
r = Rester("http://api.v3/factual.com/t/restaurants-us/read")
qstring = "q=Sushi,New York&KEY=drr6uQjOApDhEhzIbCVd63B70xUm71fIIr04CIxN"
result = r.call(qstring) # remember rester converts from json
for rest in result['response']['data']:
print rest['name']
print
|
96fc0c2e46fb4da7412b685df80924afc6737f65 | abr-98/Bus_stop_finder_unsupervised | /groundtruth/extract_lat_long.py | 663 | 3.96875 | 4 | import sys
def read_data(file_name):
"""
read the data from a csv file
"""
raw= open(file_name).read().split('\n')[1:]
data=[]
for line in raw:
if '\r' in line:
line=line.split('\r')[0]
line=line.split(',')
data.append(line)
while len(data[-1]) < 3:
data.pop()
return data
def write_file(data,file_name):
out_file = open(file_name+"_out","w")
i=1
out_file.write("stop_number,latitude,longitude\n")
for each_point in data:
s = str(each_point[0])+","+str(each_point[1])
out_file.write(str(i)+","+s+"\n")
i+=1
def main():
file_name=sys.argv[1]
data = read_data(file_name);
write_file(data,file_name)
print data[:2]
main() |
77f9bef0cdf41261a0a3595d19720ef71757a9e8 | Nufuee/python | /list_comprehensions.py | 965 | 4.03125 | 4 | def fib(n):
assert n >= 0
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
# Construct a list of the fibonacci numbers from 1 to 10 using a loop
fibs = []
for i in range(1, 10):
fibs.append(fib(i))
print(fibs)
# List comprehension
[fib(i) for i in range(1, 10)]
# Dictionary comprehension
{i: fib(i) for i in range(1, 10)}
# Set comprehension
{fib(i) for i in range(1, 10)}
# Filtering with list comprehensions
data = [fib(i) for i in range(1, 10)]
[x for x in data if x % 2 == 0]
# Write a function to calculate the square of a number
def square(n):
return n * n
# Write a list comprehension using the square function to calculate the square of the numbers
# between 20 and 25 inclusive
print([square(n) for n in range(20, 26)])
# Write a function which constructs a list of tuples (a, square(a)) for the numbers 0 to 100 if the square is divisible by 5
print([(a, square(a)) for a in range(0,101) if square(a) % 5 == 0])
|
988542e4616bff6a5cd81f01ea9134c95a9e42dd | rakhi26b/Assignments | /Milky_cookies.py | 1,717 | 4.0625 | 4 | import sys
import math
#Number of tests to be run through code
print ("Enter number of tests to be run for T: ")
Not1= int(sys.stdin.readline())
print (Not1)
#check the number of test
if Not1 < 1 or Not1> 1000:
print("ERROR: Incorrect NumberOfTests : ", Not1)
# Iterative Python program to check if a string is subsequence of another string
# Returns true if str1 is a subsequence of str2
def isSubSequence(str1,str2):
m = len(str1)
n = len(str2)
p=len(str3)
j = 0 # Index of str1
i = 0 # Index of str2
k=0 #index of str3
# Traverse both str1 and str2
# Compare current character of str2 with
# first unmatched character of str1
# If matched, then move ahead in str1
while j<m and i<n :
if str1[j] == str2[i] :
j=j+1
i = i + 1
return i==n
def issub(str2,str3):
n = len(str2)
p=len(str3)
i = 0 # Index of str2
k=0 #index of str3
while i<n and k<p:
if str3[k] == str2[i] :
k=k+1
i=i+1
# If all characters of str1 matched, then j is equal to m
return i==n
# Driver Program
if __name__ == "__main__":
#for loop for no. of test case to run
for index in range(0, Not1):
min=int(input())#Minutes spend in kitchen
print(min)
str2= input()
str1="cookie milk"
str3="milk milk"
if isSubSequence(str1,str2):
print ("Yes")
elif issub(str2,str3):
print ("Yes")
else:
print("No")
|
3a081791eeb4411c63d09f90206981556b94d7f2 | yunzhou/crack_code | /level_order_traversal.py | 1,068 | 3.640625 | 4 | class TreeNode:
def __init__(self, data,left=None,right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
#return "data {} --> [left : {} --- right : {}]".format(self.data,self.left,self.right)
return "data {}".format(self.data)
def levelOrderPrint(root):
results = []
level = 0
list = [root]
results=list
while True:
list = []
print(str(level) + ":" + str(results))
for node in results:
if node.left is not None:
list.append(node.left)
if node.right is not None:
list.append(node.right)
if len(list)==0:
break
else:
results=list
level += 1
if __name__ == '__main__':
n1 = TreeNode('x')
n2 = TreeNode('y')
n3 = TreeNode('z')
n4 = TreeNode('a')
n5 = TreeNode('b')
n6 = TreeNode('c')
n1.left = n2
n1.right = n3
n2.left = n4
n3.left = n5
n3.right = n6
print(n1)
levelOrderPrint(n1)
|
852f9a203fc6573361c9c2d81f11bfdceaaef442 | yunzhou/crack_code | /code_8_2.py | 665 | 3.75 | 4 | import numpy as np
N=8
board = np.zeros((N, N))
board[0,2]=1
board[1,2]=1
board[6,3]=1
board[4,4]=1
board[7,0]=1
print(board)
current_path = []
def is_free(x, y):
return board[x, y] == 0
def get_path(x, y):
p = (x, y)
current_path.append(p)
if (x == 0 and y == 0):
return True
success = False
if (x >= 1 and is_free(x - 1, y)):
success = get_path(x - 1, y) # go right
if (not success and y >= 1 and is_free(x, y - 1)):
success = get_path(x, y - 1) # go right
if (not success):
current_path.remove(p)
return success
if __name__ == '__main__':
get_path(N-1, N-1)
print(current_path)
|
fa6f2ec276230e1b909410fff13166f79a397efa | yunzhou/crack_code | /code_1_1.py | 333 | 3.859375 | 4 | '''
1.1 Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?
'''
def isUniqueChars(s):
appears = [False]*256
for c in s:
idx = ord(c)
if appears[idx]:
return False
else:
appears[idx]=True
return True |
93628cc03226430b588c561e6603679b5f243163 | yunzhou/crack_code | /code_3_5.py | 1,063 | 3.96875 | 4 | class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def deque(self):
if len(self.s2)==0 and len(self.s1)==0:
return None
else:
if len(self.s2)==0:
while(len(self.s1)!=0):
self.s2.append(self.s1.pop())
return self.s2.pop()
def peek(self):
if len(self.s2)==0 and len(self.s1)==0:
return None
else:
if len(self.s2)==0:
while(len(self.s1)!=0):
self.s2.append(self.s1.pop())
return self.s2[-1]
def enqueue(self,v):
self.s1.append(v)
if __name__ == '__main__':
q=MyQueue()
q.enqueue('x')
q.enqueue('y')
q.enqueue('z')
q.enqueue('a')
print(q.peek())
print(q.peek())
print(q.deque())
print(q.deque())
print(q.deque())
q.enqueue('1')
q.enqueue('2')
q.enqueue('3')
print(q.deque())
print(q.deque())
print(q.deque())
print(q.deque())
print(q.deque())
print(q.deque())
|
a2ca7819f3d7302ad0dbe3a8b2c9dbc30d774f16 | colinmyrick/CalTrac | /FoodOpt.py | 512 | 3.578125 | 4 | from tkinter import *
import tkinter as tk
class FoodOpt:
def __init__(self, item, side, servingI, servingS):
self.item = item
self.side = side
self.servingI = servingI
self.servingS = servingS
foodList = {
"Chicken": 335,
"Rice": 205,
"Pizza": 285,
"Fish": 150,
"Fries": 365,
"Beef": 215,
"Green Beans": 30
}
def calCalc(food, serving):
return foodList[food]*serving
|
0167ee7ec16e1a9e69838b818848b0c01c3b5324 | maysuircut007/Numpy | /19.Reshape & Resize.py | 291 | 3.828125 | 4 | import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10])
# reshape
b = a.reshape(2, 5) # reshape ต้องเก็บค่าในตัวแปลใหม่
print(b)
a.resize(2, 5) # resize ไม่ต้องเก็บค่าในตัวเเปลใหม่
print(a) |
e827005bb137eb39d8d507178962a9aadf36dffe | maysuircut007/Numpy | /22.Array และค่าทางสถิติ.py | 647 | 3.578125 | 4 | import numpy as np
a = np.array([1, 2, 3, 4, 5, 6,])
print(a.sum())
print(a.prod())
print(a.max())
print(a.min())
print(a.mean())
print(a.argmax()) # index ที่ข้อมูลค่ามากที่สุด
print(a.argmin()) # index ที่ข้อมูลค่าน้อยที่สุด
x = np.array([[10,30,40],[100,88,50],[77,43,42]])
print(np.min(x,axis = 1)) # axis = 1 คือเเนวนอน
print(np.min(x, axis = 0)) # axis = 0 คือเเนวตั้ง
print(np.max(x,axis = 1)) # axis = 1 คือเเนวนอน
print(np.max(x, axis = 0)) # axis = 0 คือเเนวตั้ง
|
dbf6efbca82317fe6db54b4328f64335603e4a9c | Muhammad-Elgendi/Machine-Learning-Notes | /Chapter 2 Regression/Section 2 Multiple Linear Regression/Multiple Linear Regression.py | 11,009 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
What is the P-value meaning ?
In plain english:
The p-value is actually the probability of getting a sample like ours,
or more extreme than ours IF the null hypothesis is true.
So, we assume the null hypothesis is true
and then determine how “strange” our sample really is.
If it is not that strange (a large p-value)
then we don’t change our mind about the null hypothesis.
As the p-value gets smaller, we start wondering
if the null hypothesis really is true and well maybe we should
change our minds (and reject the null hypothesis).
In more formal way :
The p-value is used to determine
if the outcome of an experiment is statistically significant.
A high p-value means that, assuming the null hypothesis is true,
this outcome was very likely.
A low p-value means that, assuming the null hypothesis is true,
there is a very low likelihood that this outcome was a result of luck.
"""
"""
How to calculate p-value ?
"""
"""
what is dummy variable trap ?
"""
"""
What to do if we have multiple independant variable and one of
them is categorical ?
"""
"""
What is the techniques to select the variables that is will be in our
model ?
1- All variables in the model (Not recommended)
2- Backward elimination
3- Forward selection
4- Bidirectional elimination aka Stepwise regression
5- Score comparision
"""
# import pandas library and give it an alias (pd)
import pandas as pd
# load the dataset from csv file
dataset = pd.read_csv('50_Startups.csv')
# split dataset into independant x and dependant y variables
x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
# encode the categorical features of the dataset
# here we have state feature is last feature
# so we can use either 3 or the reverse order which is -1
# we first need to apply LabelEncoder which will encode the text into
# numbers then we will apply the OneHotEncoder to create the dummy
# variables corresponding to state feature values (which are numbers)
# because OneHotEncoder can't encode text values
# import OneHotEncoder,LabelEncoder classes
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
# create an instance of LabelEncoder class
"""
used to transform non-numerical labels
(as long as they are hashable and comparable) to numerical labels.
"""
labelEncoder = LabelEncoder()
# apply lablel encoding to state feature
x[:,-1] = labelEncoder.fit_transform(x[:,-1])
# create an instance of OneHotEncoder class
# with parameter categorical_features which is an array
# that has the indexs of categorical data
oneHotEncoder = OneHotEncoder(categorical_features = [-1])
# apply the OneHot Encoding to independant variables x
x = oneHotEncoder.fit_transform(x).toarray()
# Avoid the dummy varible trap
# (This is optional because the LinearRegression class avoids it)
# mainly avoiding the trap is done by keeping n-1 of dummy variables
# which meaning deleting one of them (we will delete the first one)
x = x[:,1:]
# split dataset into training and test set
# import train_test_split class
from sklearn.cross_validation import train_test_split
# split the dataset
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.2 ,random_state = 42)
# we will not applying any feature scaling here since the library
# take care of it for us
# import LinearRegression class
from sklearn.linear_model import LinearRegression
# create an instance of LinearRegression called regressor
regressor = LinearRegression()
# train the model with training set
regressor.fit(x_train,y_train)
# predict test set target values or independant variable values
# and assign the predicted values to y_predicted
y_predicted = regressor.predict(x_test)
# as you can see we take all the independant variables into our model
# but this is not recommanded to be done so we will find the best
# independant variables that is statisticaly significant to
# the dependant variable
# and this can applied by one of the five techniques stated before
# but now we will choose only one of them
# let's apply the backward elimination
# one of the interesting libraries that will calculate p-values for
# each independant variable is statsmodel library specifically
# the summary() method
# let's import statsmodel library and give it an alias (sm)
import statsmodels.formula.api as sm
# remember the linear model equation for mulible variables
# it's y = b0 + b1*x1 + b2*x2 + b3*x3 ..... + bn*xn
# for n of variables
# again b0 here is a constant like b in the quation stated before
# (y = mx + b)
# and all of b1 , b2 , b3 .... and bn are a coefficient like m
# in the above equation
# but here in the statsmodels implementation of linear equation
# the constant b0 is not exist so we add a new independant variable
# to our dataset but what value we are going to add so that the
# model can find the best constant value without any of effects of
# our new added value
# well , as you can see we will add this (b0*x0) to the statsmodels
# linear equation and x0 here will the new added independant variable
# to the dataset
# and since b0*1 = b0 we will assign one(1) to our new added variable
# adding a column with ones to the dependant variable x
# using numpy append method
# let's import numpy library and give it an alias (np)
import numpy as np
# adding a column with ones to the dependant variable x
# and since we want the column of ones to be the first column in x
# we will append x to a vector of ones
x = np.append(arr = np.ones((50,1),np.int) ,
values = x ,
axis = 1)
# now we will start backward elimination
"""
Backward Elimination
STEP 1: Select a significance level to stay in the model
(e.g. SL = 0.05)
STEP 2: Fit the model with all possible predictors
STEP 3: Consider the predictor with the highest P-value.
If P > SL, go to STEP 4, otherwise go to END
STEP 4: Remove the predictor
STEP 5: Fit model without this variable
END: Your Model Is Ready
"""
# step 1 let's say our significance level is 0.05
# step 2 let's fit the model with all posible predictors
# let's create a variable called x_optimal that will contains
# all independant variables for now
x_optimal = x[:]
# step 3 : let's create a new model and fit it to x_optimal
# OLS is the class of linear model in statsmodels library
sm_regressor = sm.OLS(exog = x_optimal , endog = y).fit()
# now let's see the p-value of each independant variable
sm_regressor.summary()
"""
variable p-value
const 0.000
x1 0.953
x2 0.990
x3 0.000
x4 0.608
x5 0.123
"""
# step 3 Consider the predictor with the highest P-value.
# If P > SL, go to STEP 4, otherwise go to END
# here we consider x2 and go to step 4
# step 4 we will remove x2
# which is the third dummy variable of state feature
# and its index is 2 from x_optimal
x_optimal = x[:,[0,1,3,4,5]]
# step 5 :re fit the model with the new x_optimal
sm_regressor = sm.OLS(exog = x_optimal , endog = y).fit()
# going back to step 3
# now let's see the p-value of each independant variable
sm_regressor.summary()
"""
variable p-value
const 0.000
x1 0.940
x2 0.000
x3 0.604
x4 0.118
"""
# here we consider x1 and go to step 4
# step 4 we will remove x1
# which is the secund dummy variable of state feature
# and its index is 1 from x_optimal
x_optimal = x[:,[0,3,4,5]]
# step 5 :re fit the model with the new x_optimal
sm_regressor = sm.OLS(exog = x_optimal , endog = y).fit()
# going back to step 3
# now let's see the p-value of each independant variable
sm_regressor.summary()
"""
variable p-value
const 0.000
x1 0.000
x2 0.602
x3 0.105
"""
# step 3 here again x2 has the highest p-value
# and it is > 0.05
# step 4 we will remove x2
# which is the administration feature
# and its index is 4 from x_optimal
x_optimal = x[:,[0,3,5]]
# step 5 :re fit the model with the new x_optimal
sm_regressor = sm.OLS(exog = x_optimal , endog = y).fit()
# going back to step 3
# now let's see the p-value of each independant variable
sm_regressor.summary()
"""
variable p-value
const 0.000
x1 0.000
x2 0.060
"""
# step 3 here again x2 has the highest p-value
# and it is > 0.05
# step 4 we will remove x2
# which is the 'marketing spend' feature
# and its index is 5 from x_optimal
x_optimal = x[:,[0,3]]
# step 5 :re fit the model with the new x_optimal
sm_regressor = sm.OLS(exog = x_optimal , endog = y).fit()
# going back to step 3
# now let's see the p-value of each independant variable
sm_regressor.summary()
"""
variable p-value
const 0.000
x1 0.000
"""
# here all the variables have p-value < 0.05
# so this is the end and now The Model Is Ready
# so the conclusion is that
# " R&D Spend feature has the highest statistical significant effect
# On the dependant variable profit"
# see all of the redundant lines above BAD THING isn't it ?
# so let's implement the backward elimination algorithm method
def backwardElimination(x, sl):
numVars = len(x[0])
for i in range(0, numVars):
regressor_OLS = sm.OLS(y, x).fit()
maxVar = max(regressor_OLS.pvalues).astype(float)
if maxVar > sl:
for j in range(0, numVars - i):
if (regressor_OLS.pvalues[j].astype(float) == maxVar):
x = np.delete(x, j, 1)
regressor_OLS.summary()
return x
# and we can use it like this
# select a significance level
sl = 0.05
# assign the output of the method to x_optimal
x_optimal = backwardElimination(x[:], sl)
# easy and nice ^^
# that's was Backward Elimination with considering p-values only
# Is there a better way ? well ,yes.
# Backward Elimination with p-values and Adjusted R Squared
def backwardEliminationWithAdjustedRSquared(x, SL):
numVars = len(x[0])
temp = np.zeros((50,6)).astype(int)
for i in range(0, numVars):
regressor_OLS = sm.OLS(y, x).fit()
maxVar = max(regressor_OLS.pvalues).astype(float)
adjR_before = regressor_OLS.rsquared_adj.astype(float)
if maxVar > SL:
for j in range(0, numVars - i):
if (regressor_OLS.pvalues[j].astype(float) == maxVar):
temp[:,j] = x[:, j]
x = np.delete(x, j, 1)
tmp_regressor = sm.OLS(y, x).fit()
adjR_after = tmp_regressor.rsquared_adj.astype(float)
if (adjR_before >= adjR_after):
x_rollback = np.hstack((x, temp[:,[0,j]]))
x_rollback = np.delete(x_rollback, j, 1)
print (regressor_OLS.summary())
return x_rollback
else:
continue
regressor_OLS.summary()
return x
# and we can use it like this
# select a significance level
sl = 0.05
# assign the output of the method to x_optimal
x_optimal = backwardEliminationWithAdjustedRSquared(x[:], sl)
|
450b68eb2689957ce61da69333d6a0588820339d | GTVanitha/PracticePython | /bday_dict.py | 1,003 | 4.34375 | 4 |
birthdays = {
'Vanitha' : '05/05/90',
'Som' : '02/04/84',
'Vino' : '08/08/91'
}
def b_days():
print "Welcome to birthday dictionary! We know the birthdays of:"
names = birthdays.keys()
print ',\n'.join(names)
whose = raw_input("Who's birthday do you want to look up?")
if (whose in names):
print whose , "'s birthday is ", birthdays[whose]
print "Thank you for using birthday dictionary. Happy day :)"
else:
print "Sorry. We do not have ", whose, " birthday date."
add = raw_input(" Do you want to add it ? (y/n)" )
if add == 'y':
name = raw_input("Enter name:")
bday = raw_input("Enter birth date:")
birthdays[name] = bday
print "Added ", name, "'s birthday to dictionary. Try accessing it!"
b_days()
else:
print "Thank you for using birthday dictionary. Happy day :)"
b_days()
|
822e17a0fd1caa0782da452119f681ad52c61afe | GTVanitha/PracticePython | /char_input.py | 616 | 3.96875 | 4 | import datetime
while True:
try:
name = raw_input("Enter your name:")
age = int(input("Enter your age and I will tell you when you will turn 100 :"))
except:
print "Enter valid input"
continue
else:
break
print "Hello %s" %(name)
# Get current time
now = datetime.datetime.now()
age_diff = 100-age
c_year = now.year
done_year = c_year + age_diff
exp_year = c_year + age_diff
if age > 100:
print "You have crossed 100 %d years back. Year:%d" %(abs(age_diff), done_year)
else:
print "You will turn 100 in %d years. Year:%d" %(age_diff, exp_year)
|
b7b3aa7bcf6cda1e31693370913753cb681a815e | GTVanitha/PracticePython | /rand.py | 383 | 4.09375 | 4 | import random
a= random.randint(1,9)
print "**You have enter a Guessing Game :) **"
user_inp = input("Enter a random number between 1 to 9.")
if (user_inp < a):
print "Your guess:%d is lesser than random number:%d" %(user_inp, a)
elif (user_inp > a):
print "Your guess:%d is greater than random number:%d" %(user_inp, a)
else:
print "Woohoo!! You guessed it right!"
|
216b4c8cf3ebb561618aecf3d3e6b87161598d55 | GTVanitha/PracticePython | /som_programs/list_palindrome.py | 199 | 4.28125 | 4 | a = raw_input("Enter a String to check if it is palidrome or not : ")
b = ''
b = ''.join(reversed(a))
print b
if b == a:
print("%s is a palidrome") %a
else:
print('%s is not a palidrome') %a
|
c7c527b7a199e64d3b190076b14aad9badf48429 | GTVanitha/PracticePython | /som_programs/age.py | 315 | 4.09375 | 4 | #! /usr/bin/env python
name = raw_input("Enter your name : ")
while 1:
try:
age = input("Enter your age : ")
except :
print("enter a valid age : ")
continue
else :
break
x = 100 - age
if ( age > 100):
print ( " You are more than 100 years old")
else :
print (" Your will turn 100 in %d years") %(x)
|
b728eb510e7de0b86a65ba7f82c93f7c58874c19 | Veronika988/Algorithms-on-Graphs | /week6/contraction_hierarchies_small_and_large_dist.py3 | 9,811 | 3.84375 | 4 | """
Coursera/Algorithms on Graphs/Week 6 (Advanced Shortest Paths)
- optional/Tasks 3-4 - contraction hierarchies (small and large road networks)
By Shostatskyi. Copyright 2017
Note Coursera Honor Code
"""
import sys
import queue
import time
# Maximum allowed edge length
maxlen = 2 * 10**7
class Shortcut:
def __init__(self, _from, _to, _dist):
self._from = _from
self._to = _to
self._dist = _dist
class QueueItem:
def __init__(self, d, v):
self.dist = d;
self.node = v;
def __lt__(self, other):
return self.dist < other.dist
def __gt__(self, other):
return self.dist > other.dist
class Graph:
def __init__(self, n, adj, cost):
self.n = n
self.INF = n * maxlen
self.adj = adj
self.cost = cost
self.bi_dist = [[self.INF] * n, [self.INF] * n]
self.visited = [False] * n
self.visited_r = [False] * n
self.workset = []
self.rank = [self.INF] * n
self.dist = [self.INF] * n
self.shortcuts = []
self.is_adding_shortcuts = False
self.node_level = [0] * n
self.max_outgoing = [0] * n
self.min_outgoing = [self.INF] * n
for i in range(0, n):
self.max_outgoing[i] = max(self.adj[0][i]) if len(self.adj[0][i]) else 0
self.min_outgoing[i] = min(self.adj[0][i]) if len(self.adj[0][i]) else self.INF
def clear_containers(self):
for v in self.workset:
self.bi_dist[0][v] = self.bi_dist[1][v] = self.INF
self.visited[v] = self.visited_r[v] = False
self.workset = []
def process(self, u, q, side):
length = len(self.adj[side][u])
for i in range(0, length):
v = self.adj[side][u][i]
if self.bi_dist[side][v] > self.bi_dist[side][u] + self.cost[side][u][i]:
self.bi_dist[side][v] = self.bi_dist[side][u] + self.cost[side][u][i];
q.put(QueueItem(self.bi_dist[side][v], v))
def modified_dijkstra(self, s, t):
self.clear_containers()
estimate = self.INF
q = queue.PriorityQueue()
q_r = queue.PriorityQueue()
q.put(QueueItem(0, s))
q_r.put(QueueItem(0, t))
self.bi_dist[0][s] = 0;
self.bi_dist[1][t] = 0;
while not q.empty() or not q_r.empty():
if not q.empty():
u = q.get().node
if self.bi_dist[0][u] <= estimate:
self.process(u, q, 0)
self.workset.append(u)
self.visited[u] = True
if self.visited_r[u] and self.bi_dist[0][u] + self.bi_dist[1][u] < estimate:
estimate = self.bi_dist[0][u] + self.bi_dist[1][u]
if not q_r.empty():
u = q_r.get().node
if self.bi_dist[1][u] <= estimate:
self.process(u, q_r, 1)
self.workset.append(u)
self.visited_r[u] = True
if self.visited[u] and self.bi_dist[0][u] + self.bi_dist[1][u] < estimate:
estimate = self.bi_dist[0][u] + self.bi_dist[1][u]
return -1 if estimate == self.INF else estimate
def witness_searches(self, s, v, limit):
self.clear_containers()
q = queue.PriorityQueue()
q.put(QueueItem(0, s))
self.workset.append(s)
self.dist[s] = 0
hops = 3
while hops and not q.empty():
u = q.get().node
if limit <= self.dist[u]:
break
for i in range(len(self.adj[0][u])):
w = self.adj[0][u][i]
if self.rank[w] < self.rank[v] or w == v:
continue
if self.dist[w] > self.dist[u] + self.cost[0][u][i]:
self.dist[w] = self.dist[u] + self.cost[0][u][i]
q.put(QueueItem(self.dist[w], w))
self.workset.append(w)
hops -= 1
def contracted_neighbors_and_level(self, v):
num = 0
level = 0
for n in self.adj[0][v]:
if self.rank[n] != self.INF:
num += 1
if self.node_level[n] > level:
level = self.node_level[n]
for n in self.adj[1][v]:
if self.rank[n] != self.INF:
num += 1
if self.node_level[n] > level:
level = self.node_level[n]
return num + (level + 1)/2
def update_node_level(self, v):
for n in self.adj[0][v]:
if self.node_level[n] < self.node_level[v] + 1:
self.node_level[n] = self.node_level[v] + 1
for n in self.adj[1][v]:
if self.node_level[n] < self.node_level[v] + 1:
self.node_level[n] = self.node_level[v] + 1
def contract(self, v):
start_time = time.time()
max_outgoing = self.max_outgoing[v]
min_outgoing = self.min_outgoing[v]
num_of_shortcuts = 0
shortcut_cover = set()
for i in range(len(self.adj[1][v])):
u = self.adj[1][v][i]
if self.rank[u] < self.rank[v]:
continue
limit = self.cost[1][v][i] + max_outgoing - min_outgoing
self.witness_searches(u, v, limit)
for j in range(len(self.adj[0][v])):
w = self.adj[0][v][j]
shortcut_needed = True
if self.rank[w] < self.rank[v]:
continue
for k in range(len(self.adj[1][w])):
x = self.adj[1][w][k]
if self.rank[x] < self.rank[v] or x == v:
continue
if self.cost[1][v][i] + self.cost[0][v][j] >= self.dist[x] + self.cost[1][w][k]:
shortcut_needed = False
break
if shortcut_needed:
num_of_shortcuts += 1
shortcut_cover.add(w)
shortcut_cover.add(u)
if self.is_adding_shortcuts:
self.shortcuts.append(Shortcut(u, w, self.cost[1][v][i] + self.cost[0][v][j]))
for w in self.workset:
self.dist[w] = self.INF
self.workset = []
time_cost = (time.time() - start_time)
return 2*(num_of_shortcuts - len(adj[1][v]) - len(adj[0][v])) + self.contracted_neighbors_and_level(v) + len(shortcut_cover) + time_cost*3
def add_shortcuts(self):
for shortcut in self.shortcuts:
#print("add shortcuts")
if self.max_outgoing[shortcut._from] < shortcut._dist:
self.max_outgoing[shortcut._from] = shortcut._dist
if self.min_outgoing[shortcut._from] > shortcut._dist:
self.min_outgoing[shortcut._from] = shortcut._dist
self.adj[0][shortcut._from].append(shortcut._to)
self.adj[1][shortcut._to].append(shortcut._from)
self.cost[0][shortcut._from].append(shortcut._dist)
self.cost[1][shortcut._to].append(shortcut._dist)
def remove_edges(self):
for i in range(0, n):
j = 0
s = len(self.adj[0][i])
while j < s:
v = self.adj[0][i][j]
if self.rank[i] > self.rank[v]:
del self.adj[0][i][j]
del self.cost[0][i][j]
s -= 1
#print("deleted")
continue
j += 1
j = 0
s = len(self.adj[1][i])
while j < s:
v = self.adj[1][i][j]
if self.rank[i] > self.rank[v]:
del self.adj[1][i][j]
del self.cost[1][i][j]
s -= 1
#print("deleted")
continue
j += 1
def preprocess(self):
ordered_nodes = queue.PriorityQueue()
for v in range(0, n):
ordered_nodes.put(QueueItem(self.contract(v), v))
rank_count = 0
self.is_adding_shortcuts = True
while ordered_nodes.qsize() > 1:
v = ordered_nodes.get()
v.dist = self.contract(v.node)
u = ordered_nodes.get()
if v.dist <= u.dist:
# print ("impt = ", v.dist)
self.add_shortcuts()
self.rank[v.node] = rank_count
self.update_node_level(v.node)
else:
ordered_nodes.put(v)
ordered_nodes.put(u)
rank_count += 1
self.shortcuts = []
self.remove_edges()
def readl():
return map(int, sys.stdin.readline().split())
if __name__ == '__main__':
#start_time = time.time()
n,m = readl()
adj = [[[] for _ in range(n)], [[] for _ in range(n)]]
cost = [[[] for _ in range(n)], [[] for _ in range(n)]]
for e in range(m):
u,v,c = readl()
adj[0][u-1].append(v-1)
cost[0][u-1].append(c)
adj[1][v-1].append(u-1)
cost[1][v-1].append(c)
ch = Graph(n, adj, cost)
ch.preprocess()
print("Ready")
#print("preprocessing took %s seconds ---" % (time.time() - start_time))
sys.stdout.flush()
t, = readl()
for i in range(t):
s, t = readl()
print(ch.modified_dijkstra(s-1, t-1))
|
02ca0bd1dab278230efee1d402618c35b1780996 | Oleh60/Education | /Les8Modules.py | 1,411 | 3.921875 | 4 | # import random
# from random import randint
#
# print("Відгадайте число від 0 - 100 використовуючи підказки")
# unknown = int(input("Ведіть число для відгадування: "))
# a = random.randint(0, 100)
#
# count = 0
#
#
# while a != unknown:
#
# count += 1
# if unknown > a:
# print("Введене число більше за загадане")
#
#
# elif unknown < a:
# print("Введене число менше за загадане")
# unknown = int(input("Ведіть число для відгадування: "))
#
# else:
# print(("Вітаємо ви відгадали число!" "\n" f" Спроб використано: {count}"))
import re
print("Пароль повинен містити літери латинського алфавіту"
"нижнього та верхнього регістрів,як мінімум одну цифру"
"та спец. символи як $#@")
password = input("Enter a password: ")
chek1 = re.findall("[a-z]", password)
chek2 = re.findall("[A-Z]", password)
chek3 = re.findall("\d", password)
chek4 = re.findall(r"$|#|@", password)
if 6 <= len(password) <= 16 and chek1 and chek2 and chek3 and chek4:
print("Ваш пароль прийнято")
else:
print("Введено якесь невірне значення")
|
bdae14f047df34a78d7c1b5d1e03696f26327189 | htomeht/scripts | /nonascii.py | 449 | 3.703125 | 4 | #!/usr/bin/python
import os,string
chars={}
def nonascii(string):
for char in string:
if ord(char)>127 and char not in chars:
chars[char]=string
for root, dirs, files in os.walk(os.getcwd()):
for d in dirs:
nonascii(d)
for f in files:
nonascii(f)
print "These non-ascii characters found on filesystem:"
for char,filename in chars.items():
print "%c (%X) in %s" % (char, ord(char), filename)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.