blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cee60e6eecbeccae9418b46fbc2da768592f62b4 | alexayalamcs/advent | /day3/main.py | 925 | 3.8125 | 4 |
def main(is_part_one=False):
with open('data.txt') as data:
trees = data.read().splitlines()
if is_part_one:
count_num_trees(3, 1, trees)
else:
value = 1
value *= count_num_trees(1, 1, trees)
value *= count_num_trees(3, 1, trees)
value *= count_num_trees(5, 1, trees)
value *= count_num_trees(7, 1, trees)
value *= count_num_trees(1, 2, trees)
print(f'The product of trees is: {value}')
def count_num_trees(num_right, num_down, trees):
i = 0
tree_count = 0
N = len(trees[0])
for j in range(num_down, len(trees), num_down):
i += num_right
if trees[j][i % N] == '#':
tree_count += 1
print(f'Right {num_right}, down {num_down} -- Encountered {tree_count} trees')
return tree_count
if __name__ == "__main__":
main(is_part_one=True)
print('-' * 50)
main(is_part_one=False)
|
94e573e4ace6dec653ee7a5ebeac19252c212af0 | snailQQ/lxf_python | /6_2returnFuntion.py | 2,545 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
# 我们来实现一个可变参数的求和。通常情况下,求和的函数是这样定义的:
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
# 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数:
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1,3,5,7,9)
f2 = calc_sum(1,3,5,7,9)
print(f2)
print(f)
print(f())
# 在这个例子中,我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力。
# 请再注意一点,当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数:
# >>> f1 = lazy_sum(1, 3, 5, 7, 9)
# >>> f2 = lazy_sum(1, 3, 5, 7, 9)
# >>> f1==f2
# False
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 3):
fs.append(f(i))
return fs
f1, f2 = count()
print(f1())
print(f2())
# print(f4())
# 全部都是9!原因就在于返回的函数引用了变量i,但它并非立刻执行。等到3个函数都返回时,它们所引用的变量i已经变成了3,因此最终结果为9。
# 返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量。
# 如果一定要引用循环变量怎么办?方法是再创建一个函数,用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:
# 练习
# 利用闭包返回一个计数器函数,每次调用它返回递增整数:
# -*- coding: utf-8 -*-
def createCounter():
num = 0
def counter():
nonlocal num
num = num + 1
return num
return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!')
# 匿名函数 |
2ffb7ba5e16d3cd40805f7d6ca26e653d9efee87 | Laurens117/programming1 | /Les 9/pe 9_5.py | 566 | 3.59375 | 4 | def namen():
namenlijst = {}
count = 0
naam = input("Geef een naam: ")
while naam!='':
if namenlijst.get(naam):
namenlijst[naam] = namenlijst[naam] + 1
else:
namenlijst[naam] = 1
count = count + 1
naam = input("Volgende naam: ")
for name in namenlijst:
if namenlijst[name] >= 2:
print('Er zijn ' + str(namenlijst[name]) + ' studenten met de naam ' + str(name))
else:
print('Er is '+ str(namenlijst[name])+' student met de naam '+str(name))
namen()
|
d16e986d47fe22276828285ff0e867c1dfb349ac | furutuki/LeetCodeSolution | /剑指offer系列/剑指 Offer 22. 链表中倒数第k个节点/solution_recursive.py | 804 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def __init__(self):
self.ans = None
def search(self, node: ListNode, k: int) -> int:
if not node:
return 0
val = 1 + self.search(node.next, k)
if val == k:
self.ans = node
return val
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
self.search(head, k)
return self.ans
s = Solution()
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
node = s.getKthFromEnd(n1, 2)
cur = node
while cur:
print(cur.val)
cur = cur.next
|
891ab6282c8600c282b5ae8641e86f565a6ed8c8 | teovoinea/First-Year-Assignments | /1MD3/Tutorial 10/Q1_voineat.py | 476 | 4.0625 | 4 | from turtle import *
Screen()
def tree(length, angle, factor, degree):
if degree > 0:
degree = degree - 1
left(angle)
forward(length*factor)
#print(degree)
tree(length * factor, angle, factor, degree)
backward(length*factor)
right(angle * 2)
forward(length*factor)
#print(degree)
tree(length * factor, angle, factor, degree)
backward(length*factor)
left(angle)
|
1392dcd8ff4c3b9a4c856d6dcaf9c48da7dc5dfc | liuhuipy/Algorithm-python | /search/find-first-and-last-position-of-element-in-sorted-array.py | 1,236 | 3.671875 | 4 | """
在排序数组中查找元素的第一个和最后一个位置:
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
"""
from typing import List
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
len_nums = len(nums)
l, r = 0, len_nums
while l < r:
mid = (l + r) // 2
if nums[mid] == target:
temp_l_index, temp_r_index = mid - 1, mid + 1
while temp_l_index >= 0 and nums[temp_l_index] == target:
temp_l_index -= 1
while temp_r_index < len_nums and nums[temp_r_index] == target:
temp_r_index += 1
return [temp_l_index + 1, temp_r_index - 1]
if nums[mid] < target:
l = mid + 1
else:
r = mid
return [-1, -1]
|
5a4c845bbb0c5f5fa47e602542cf50d77ea955cf | MinneStephanie2/1NMCT4-LaboBasicProgramming-stephanieminne14 | /week2 selectiestructuren/oefening 1.py | 227 | 3.65625 | 4 | getal1 = int(input("geef een geheel getal"))
getal2 = int(input("geef nog een geheel getal: "))
if (getal1 == getal2):
print("getal {0} is gelijk als {1}".format(getal1,getal2))
else: print("de getallen zijn verschillend") |
52c3014111af1f2f63e767543ff570b4bacc1b08 | bose0003/py_files | /closest_number.py | 2,284 | 3.546875 | 4 |
# test_cases = int(input("Enter the number of test cases: "))
# end_result_list = []
# for _ in range(test_cases):
# inputs = input("Enter the 2 numbers to test: ").split(" ")
# diff = abs(int(inputs[0])) - abs(int(inputs[1]))
# quotient = (abs(diff) // abs(int(inputs[1]))) + 1
# if (quotient == 0):
# if (int(inputs[0]) < 0):
# end_result_list.append(- (int(inputs[1])))
# else:
# end_result_list.append(int(inputs[1]))
# else:
# if (int(inputs[0]) < 0):
# end_result_list.append(-(int(inputs[1]) * quotient))
# else:
# end_result_list.append((int(inputs[1]) * quotient))
# for elm in end_result_list:
# print(elm)
# test_cases = int(input())
# end_result_list = []
# for _ in range(test_cases):
# inputs = input().split(" ")
# n = int(inputs[0])
# m = int(inputs[1])
# quotient = n // m
# closest_first = m * quotient
# if n*m > 0: # Positivity Check
# closest_second = m * (quotient + 1)
# else:
# closest_second = m * (quotient - 1)
# if (abs(n - closest_first) < abs(n - closest_second)):
# end_result_list.append(closest_first)
# else:
# end_result_list.append(closest_second)
# for elm in end_result_list:
# print(elm)
import math
final_list = []
test_case = int(input("Enter the number of test cases: "))
for _ in range(test_case):
inputs = input().split(" ")
if abs(int(inputs[0])) > abs(int(inputs[1])):
m = int(inputs[0])
n = int(inputs[1])
else:
m = int(inputs[1])
n = int(inputs[0])
if abs(m) - abs(n) > abs (n):
if m > 0:
quo = m // n
closest_num = quo * n
closest_num_one = (quo + 1) * n
if abs(m - closest_num) > abs(m - closest_num_one):
final_list.append(closest_num_one)
else:
final_list.append(closest_num)
if m < 0:
quo = abs(m) // n
closest_num_one = (quo + 1) * n
final_list.append(-(closest_num_one))
else:
if m < 0 or n < 0:
final_list.append(-(abs(n)))
else:
final_list.append(abs(m))
for elm in final_list:
print(elm) |
a5748e806fc0775f7b46af9216be4603e616a003 | affo/ilps-sqpp | /graph.py | 3,131 | 4.0625 | 4 | '''
Generating random Graphs basing on Erdos-Renyi model
https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model
'''
import random
class Graph(object):
def __init__(self, n, p, w=1):
'''
Creates a new `DataStructure` representing a graph
with `n` vertices (labeled with incremental integers)
and probability of connection `p`.
The weight of the edge will be at maximum `w` (uniformly
distributed).
'''
self.n = n
if p < 0: p = 0
if p > 1: p = 1
self.p = p
self.w = w
self.data = self._generate(n, p, w)
def _generate(self, n, p, w):
'''
Generates and returns it the internal representation
'''
pass
def insert(self, edge):
'''
Creates and edge (a couple) between
`edge[0]` and `edge[1]`.
'''
pass
def delete(self, edge):
'''
Deletes the edge (if it exists) between
`edge[0]` and `edge[1]`.
'''
pass
def find(self, edge):
'''
Returns if `edge[0]` and `edge[1]` are connected.
'''
pass
def enumerate(self, vertex):
'''
Returns the neighbors of `vertex`
'''
pass
class AdjMatrixGraph(Graph):
def __repr__(self):
r = '\t'
r += '\t'.join([str(i) for i in xrange(self.n)])
r += '\n\t'
r += '\t'.join(['|' for i in xrange(self.n)])
r += '\n'
for i, row in enumerate(self.data):
r += str(i) + ' --\t'
r += '\t'.join([str(el) for el in row])
r += '\n'
return r
def _generate(self, n, p, w):
m = [[0 for _ in xrange(n)] for _ in xrange(n)]
# given that the graph has always to be
# be connected, we have to create a random
# path from vertex 0 to n:
vertices = list(xrange(n))
fromv = random.choice(vertices)
vertices.remove(fromv)
while len(vertices) > 0:
tov = random.choice(vertices)
# ensure connection
m[fromv][tov] = random.randint(1, w)
m[tov][fromv] = m[fromv][tov]
fromv = tov
vertices.remove(fromv)
# now, we can add connections based
# on probability
for i in xrange(n - 1):
for j in xrange(i + 1, n):
if not m[i][j] > 0 and random.random() < p:
m[i][j] = random.randint(1, w)
m[j][i] = m[i][j]
return m
def insert(self, edge):
i = edge[0]
j = edge[1]
self.data[i][j] = random.randint(1, self.w)
self.data[j][i] = self.data[i][j]
def delete(self, edge):
i = edge[0]
j = edge[1]
self.data[i][j] = 0
self.data[j][i] = 0
def find(self, edge):
i = edge[0]
j = edge[1]
return self.data[i][j] > 0
def enumerate(self, vertex):
return [(i, v) for i, v in enumerate(self.data[vertex]) if v > 0]
|
295747455091a5d327f2a5cfc6058fc2eb2ea1bc | LuisPatino92/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-load_from_json_file.py | 318 | 3.609375 | 4 | #!/usr/bin/python3
"""This module has the load_from_json_file function"""
import json
def load_from_json_file(filename):
"""Charges the json of and object and returns it"""
jason_str = ""
with open(filename, 'r', encoding='utf-8') as f:
jason_str = f.read()
return json.loads(jason_str)
|
18668aa951cc7fbe3c0d5ee3fe5e193dcd585cdc | Meowmycks/catpass | /catpass.py | 16,377 | 3.71875 | 4 | #! /usr/bin/python3
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from pathlib import Path #to use Linux/OS X's "touch" function on Windows
import json #to hold our passwords
import getpass #to hide user input for entering passwords
import string #to generate new passwords
import random #also to generate new passwords
import os #to do stuff on the user's operating system
import platform #to determine what operating system the user is using
import signal #to kill the program when the user is done (on Linux/OS X)
import time #to display messages before the screen updates
import collections #for an ordered dictionary to make sorting and finding easier
#padding system for bytestrings
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
#makes clearing the screen easier
def clearscreen(myOS = platform.system()):
#the user is using Linux or OS X
if myOS == 'Linux' or myOS == 'Darwin':
_=os.system("clear")
#the user is using Windows
else:
_=os.system("cls")
#getting AES of passphrase
def getAES(passphrase):
encoded = passphrase.encode()
hashphrase = SHA256.new(data = encoded)
digest = hashphrase.digest()
key = digest[:16]
IV = digest[16:]
return AES.new(key,AES.MODE_CBC,IV)
#encrypting message with given passphrase
def encrypt(message, passphrase):
obj = getAES(passphrase)
padded = pad(message).encode("utf8")
return obj.encrypt(padded)
#decrypting ciphertext with given passphrase
def decrypt(ciphertext,passphrase):
obj = getAES(passphrase)
message = obj.decrypt(ciphertext)
message = unpad(message.decode())
return message
#to generate passwords for accounts
#to prevent possible problems with strings, " and ' are removed from the list
punct = string.punctuation
punct = punct.replace("\"","")
punct = punct.replace("\'","")
def generator(size, chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + punct):
return ''.join(random.choice(chars) for _ in range(int(size)))
#used to separate information into different variables or other things as needed
#there's probably a much better way of doing this but whatever, it works
def getinfo(thelist):
info = ""
for item in thelist:
info = info + item + " "
return info.split()
#the dictionary to hold accounts in
passwords = collections.OrderedDict()
#find the .json file holding encrypted passwords
directory = os.listdir(os.getcwd())
#check if it exists first
#if not, then we make a new one
if "passwords.json" not in directory and "passwords-backup.json" not in directory:
#the user is using Linux or OS X
if platform.system() == 'Linux' or platform.system() == 'Darwin':
_=os.system('touch passwords.json')
_=os.system('touch passwords-backup.json')
#the user is using Windows
else:
Path('passwords.json').touch()
Path('passwords-backup.json').touch()
#getting user input for passphrase creation/verification
clearscreen()
passphrase = getpass.getpass("Enter passphrase: ")
#using passphrase to decrypt passwords
#if given wrong passphrase, it will ask for the passphrase again
#three strikes and you're out
failcount = 0;
while True:
try:
data = open("passwords.json","rb")
encrypted = data.read()
data.close()
if encrypted:
plaintext = decrypt(encrypted,passphrase)
data = open("passwords.json","w")
passwords = json.loads(plaintext)
data.close()
else:
data = open("passwords-backup.json","rb")
encrypted = data.read()
data.close()
if encrypted:
plaintext = decrypt(encrypted,passphrase)
data = open("passwords.json","w")
passwords = json.loads(plaintext)
data.close()
break
except:
failcount+=1
if failcount == 3:
print("\nError: Bad passphrase.")
time.sleep(1)
exit(1)
print("\nSorry, try again.")
passphrase = getpass.getpass("Enter passphrase: ")
#upon login (successful decryption), the user will be greeted
clearscreen()
print("catpass v2020.07.10")
print("An Arguably Competent Password Manager")
print("Made by Meowmycks\n")
#the main menu
while True:
print("A to Add an Account")
print("V to View an Account")
print("C to Change an Account")
print("R to Remove an Account")
print("P to Change Passphrase")
print("E to Exit")
choice = input("\nEnter command: ")
clearscreen()
#the user wants to add a new password
if choice.lower() == 'a':
clearscreen()
site = input("Enter sitename: ")
user = input("Enter username: ")
#to make sure they enter a valid number
while True:
try:
size = int(input("Give a length for your password: "))
break
except ValueError:
pass
for pw in passwords:
siteinfo = getinfo(passwords[pw])
password = generator(size)
passwords[password] = [password]
passwords[password].append(site)
passwords[password].append(user)
info = getinfo(passwords[password])
clearscreen()
print("Account Added")
print("User \'{}\' at \'{}\' has the password \'{}\'\n".format(info[2],info[1],info[0]))
#the user wants to look at a password
if choice.lower() == 'v':
clearscreen()
#if passwords exist then list all of them
if len(passwords) != 0:
print("List of Known Accounts\n")
#we use position to list off each account, this will matter later
position = 1
for pw in passwords:
info = getinfo(passwords[pw])
print("{} | Site: {} | User: {}".format(position,info[1],info[2]))
position += 1
#to make sure they enter a valid number
while True:
try:
accno = int(input("\nChoose an Account Number: "))
break
except ValueError:
pass
#for when they choose a number outside the available list
if accno > 0 and accno <= len(passwords):
verify = getpass.getpass("\nEnter passphrase: ")
clearscreen()
#now that we know what account they want, we go back to that position
#because we are using an ordered dictionary, our job is *much* easier
position = 0
if verify == passphrase:
for pw in passwords:
info = getinfo(passwords[pw])
position+=1
#give the account info at the given index
if position == accno:
print("User \'{}\' at \'{}\' has the password \'{}\'\n".format(info[2],info[1],info[0]))
else:
print("Error: Bad passphrase.\n")
else:
clearscreen()
print("No account exists at that index.\n")
#for when no accounts exist
else:
print("No accounts saved.\n")
#the user wants to change an existing password
if choice.lower() == 'c':
clearscreen()
#you can't change a nonexistent password
if len(passwords) != 0:
#clearscreen()
print("List of Known Accounts\n")
#we use position to list off each account, this will matter later
position = 1
for pw in passwords:
info = getinfo(passwords[pw])
print("{} | Site: {} | User: {}".format(position,info[1],info[2]))
position+=1
#to make sure they enter a valid number
while True:
try:
accno = int(input("\nChoose an Account Number: "))
break
except ValueError:
pass
#for when they choose a number outside the available list
if accno > 0 and accno <= len(passwords):
verify = getpass.getpass("\nEnter passphrase: ")
clearscreen()
#now that we know what account they want, we go back to that position
#because we are using an ordered dictionary, our job is *much* easier
position = 0
canchange = False
if verify == passphrase:
for pw in passwords:
info = getinfo(passwords[pw])
#this holder will become very important later
holdpw = info[0]
position+=1
#change the account info at the given index
if position == accno:
#let the user choose what they want to change
#in all three cases, the user enters new information
#that information overwrites previous information stored in "info"
#which then overwrites the corresponding information in "pw"
#changing passwords is a bit more complicated
#instead of replacing one part, it deletes the key
#and adds a new key in the same spot with the new information
#there's probably a better way to do it but whatever, it works
clearscreen()
while True:
print("S to Change Site")
print("U to Change User")
print("P to Change Password")
print("E to Exit")
print("R does nothing.")
changeme = input("\nEnter command: ")
#change sitename
if changeme.lower() == 's':
clearscreen()
site = input("Enter sitename: ")
info[1] = site
passwords[pw] = info
clearscreen()
print("Site changed successfully.\n")
#change username
elif changeme.lower() == 'u':
clearscreen()
user = input("Enter username: ")
info[2] = user
passwords[pw] = info
clearscreen()
print("User changed successfully.\n")
#change password
elif changeme.lower() == 'p':
clearscreen()
while True:
try:
size = int(input("Give a length for your password: "))
break
except ValueError:
pass
password = generator(size)
info[0] = password
#password replacement has been enabled
canchange = True
clearscreen()
print("Password changed successfully.\n")
#go back to main menu
elif changeme.lower() == 'e':
clearscreen()
break
elif changeme.lower() == 'r':
clearscreen()
print("I said it does nothing, stupid.\n")
pass
else:
clearscreen()
pass
else:
print("Error: Bad passphrase.\n")
#if
if canchange:
#boom
del passwords[holdpw]
passwords[info[0]] = [info[0]]
passwords[info[0]].append(info[1])
passwords[info[0]].append(info[2])
else:
clearscreen()
print("No account exists at that index.\n")
else:
print("No accounts saved.\n")
#the user wants to change their decryption password
if choice.lower() == 'p':
clearscreen()
#make sure the user knows their passphrase
#if they do, then they can change it
#to make sure they know what they're typing, make them do it twice
#if everything checks out, their passphrase changes
verify = getpass.getpass("Enter old passphrase: ")
if passphrase == verify:
newpass = getpass.getpass("Enter new passphrase: ")
verifynewpass = getpass.getpass("Re-enter new passphrase: ")
if newpass == verifynewpass:
passphrase = newpass
clearscreen()
print("Passphrase updated.\n")
else:
clearscreen()
print("Error: New passphrases do not match.\n")
else:
clearscreen()
print("Error: Bad passphrase.\n")
#the user wants to remove a password
if choice.lower() == 'r':
clearscreen()
#you can't remove a nonexistent password
if len(passwords) != 0:
#clearscreen()
print("List of Known Accounts\n")
#we use position to list off each account, this will matter later
position = 1
for pw in passwords:
info = getinfo(passwords[pw])
print("{} | Site: {} | User: {}".format(position,info[1],info[2]))
position+=1
#to make sure they enter a valid number
while True:
try:
accno = int(input("\nChoose an Account Number: "))
break
except ValueError:
pass
#now that we know what account they want, we go back to that position
#because we are using an ordered dictionary, our job is *much* easier
position = 0
if accno > 0 and accno <= len(passwords):
#make sure it's the user doing it
verify = getpass.getpass("\nEnter passphrase: ")
clearscreen()
if verify == passphrase:
for pw in passwords:
info = getinfo(passwords[pw])
#delete the account at the given index
if position == accno-1:
del passwords[info[0]]
clearscreen()
print("Account removed.\n")
break
else:
position+=1
pass
else:
print("Error: Bad passphrase.\n")
else:
clearscreen()
print("No account exists at that index.\n")
else:
print("No accounts saved.\n")
#the user wants to close the program
#when exiting the program, we encrypt and dump our passwords into the json file
if choice.lower() == 'e':
dump = json.dumps(passwords)
encrypted = encrypt(dump,passphrase)
data = open("passwords.json","wb")
data.write(encrypted)
data.close()
data = open("passwords-backup.json","wb")
data.write(encrypted)
data.close()
clearscreen()
exit(1)
|
b8fc620acc497ca7efea706ea5aaad33118e73f1 | zhangfuli/leetcode | /多进程多线程/多线程打印1~100.py | 660 | 3.578125 | 4 | import threading
import time
def worker():
global count
while True:
lock.acquire() # 加锁
count += 1
print(threading.current_thread(), count)
lock.release() # 操作完成后释放锁
if count >= 99:
break
time.sleep(1)
print(1)
def main():
threads = []
for i in range(2): # 控制线程的数量
t = threading.Thread(target=worker, args=())
threads.append(t)
for i in threads:
i.start()
for i in threads:
i.join() # 将线程加入到主线程中
if __name__ == '__main__':
lock = threading.Lock()
count = 0
main()
|
6c55696ee34f816ef75b0990ba7d99cb4e7ba554 | claviering/python-room | /leetcode/841-850/844 比较含退格的字符串.py | 1,293 | 3.734375 | 4 | class Solution:
def backspaceCompare(self, S, T):
string1 = []
string2 = []
for c in S:
if c == "#" and len(string1) > 0:
string1.pop()
elif c != "#":
string1.append(c)
for c in T:
if c == "#" and len(string2) > 0:
string2.pop()
elif c != "#":
string2.append(c)
return string1 == string2
# 双指针,从后面开始遍历
class Solution:
def backspaceCompare(self, S, T):
i, j = len(S) - 1, len(T) - 1
skipS = skipT = 0
while i >= 0 or j >= 0:
while i >= 0:
if S[i] == "#":
skipS += 1
i -= 1
elif skipS > 0:
skipS -= 1
i -= 1
else:
break
while j >= 0:
if T[j] == "#":
skipT += 1
j -= 1
elif skipT > 0:
skipT -= 1
j -= 1
else:
break
if i >= 0 and j >= 0:
if S[i] != T[j]:
return False
elif i >= 0 or j >= 0:
return False
i -= 1
j -= 1
return True
|
f7f54a72eb680b0aacf404b788ac92d36484563f | JosephThomasOldfield/Python-Challenges | /1passwordcheck.py | 398 | 4.09375 | 4 | '''Create a variable called password.
Check how many letters are in the password,
if there are less than 8 log to the console
that the password is too short. Otherwise log
the password to the console.'''
password = "password"
def passwordChecker(passCheck):
if len(passCheck) >= 8:
print(passCheck)
else:
print("Password is too short")
passwordChecker(password) |
ddaab9e73804961a4d35ed2a72063b9647d0c387 | dakshinap/Classification-without-regularisation | /utils.py | 581 | 3.53125 | 4 | '''
Created on Sep 22, 2017
@author: dakshina
'''
import os
import os.path
def get_corpus(dir, filetype=".wav"):
"""get_corpus(dir, filetype=".wav"
Traverse a directory's subtree picking up all files of correct type
"""
files = []
# Standard traversal with os.walk, see library docs
for dirpath, dirnames, filenames in os.walk(dir):
for filename in [f for f in filenames if f.endswith(filetype)]:
files.append(os.path.join(dirpath, filename))
return files
|
da9fb83594cef858912c7bf21fbdd67cd2f9740b | owlove/StructureProgramming | /Lab1/lb1Numb2.py | 223 | 3.515625 | 4 | import math
y = float(input("Write number (y): "))
r = float(input("Write number (r): "))
t = float(input("Write number (t): "))
w = (4 * math.pow(t,3) + math.log1p(r))/(math.pow(math.e,y + r) + 7.2 * math.sin(r))
print(w) |
e5a7fc842a1b0cddceda001f9f394b82aaba4e97 | usman-tahir/python-automation | /chapter-3/magic-eight-ball/magic_eight_ball.py | 593 | 3.671875 | 4 |
import random
def get_answer(answer_number):
if answer_number == 1:
return 'It is certain'
elif answer_number == 2:
return 'It is decidedly so'
elif answer_number == 3:
return 'Yes'
elif answer_number == 4:
return 'Reply hazy - try again'
elif answer_number == 5:
return 'Ask again later'
elif answer_number == 6:
return 'Concentrate and ask again'
elif answer_number == 7:
return 'My reply is no'
elif answer_number == 8:
return 'Outlook not so good'
elif answer_number == 9:
return 'Very doubtful'
r = random.randint(1, 9)
fortune = get_answer(r)
print(fortune) |
52704306c661e8f1eff945010f3e0424a4c258f0 | reashiny/python. | /python_beginner/vowel or consonant.py | 541 | 3.671875 | 4 | #-------------------------------------------------------------------------------
# Name: module5
# Purpose:
#
# Author: 16CSE024
#
# Created: 27/02/2018
# Copyright: (c) 16CSE024 2018
# Licence: <your licence>
#------------------------------------------------------------------------------
def main():
pass
if __name__ == '__main__':
main()
a=raw_input("enter an alphabet")
if (a=='a'or a=='e' or a=='i'or a=='o' or a=='u'):
print (a,"is a vowel")
else:
print (a,"is an consonant")
|
8f0aff11a1e2c88bdf4e64ec1b2fbd5195b423dd | gulcanTeacher/pythonDersMateryalleri | /oo15matrisOrnegi.py | 822 | 3.609375 | 4 | """
ekrana 3x4 matrisi için aşağıdaki gibi bir çıktı verilecek
Çıktı
* * * *
* * * *
* * * *
"""
# i,j=0,0
# deger=""
# while i<3:
# i+=1
# while j<4:
# j += 1
# deger += "* "
# print(deger)
# deger=""
# j=0
"""
ekrana 4x3 matrisi için aşağıdaki gibi bir çıktı verilecek
Çıktı
* * *
* * *
* * *
* * *
"""
# i,j=0,0
# deger=""
# while i<4:
# i+=1
# while j<3:
# j += 1
# deger += "* "
# print(deger)
# deger=""
# j=0
"""
ekrana 4xi matrisi için aşağıdaki gibi bir çıktı verilecek
Çıktı
* * *
* * *
* * *
* * *
"""
i,j=0,0
deger=""
while i<4:
i+=1
while j<i:
j += 1
deger += "* "
print(deger)
deger=""
j=0 |
4e24ca94a69d3ffd0e5fd33b35d99e3c83ad3e2c | harshal-jain/Python_Core | /3E3-Swap2NumbersWithOut3rdVariable.py | 208 | 3.875 | 4 | a=input("Enter the first number");
b=input("Enter the second number");
a=int(a)
b=int(b)
print("before swapping a="+str(a)+",b="+str(b) )
a=a+b
b=a-b
a=a-b
print("after swapping a="+str(a)+",b="+str(b) )
|
da3b6e9a49ec2ee0cbac5a6b38d7c881b2d605c7 | benlinhuo/algorithmpy | /sort/mergeSortRecursion.py | 2,027 | 4.09375 | 4 | #!/user/bin/python3
'''
归并排序:
归并排序我们采用递归去实现(也可采用迭代的方式去实现)
一般都是将2个已有序的子序列,合并成一个大的有序序列
https://www.cnblogs.com/chengxiao/p/6194356.html
https://www.cnblogs.com/skywang12345/p/3602369.html
'''
import math;
# 将2个已有序的子序列,合并成一个大的有序序列。需要利用一个和合并后一样大小空间的temp
# leftArr 和 rightArr 必须是有序的才可以
def mergeTwoOrderedArr(leftArr, rightArr):
temp = [];
i = 0;
j = 0;
# 两个独立数组,各自有对应游标,进行比较。则把2个比较条件用and作为总的比较条件
while i < len(leftArr) and j < len(rightArr):
if leftArr[i] >= rightArr[j]:
temp.append(rightArr[j])
j += 1;
else:
temp.append(leftArr[i]);
i += 1;
# 游标j到达末尾
for ii in range(i, len(leftArr)):
temp.append(leftArr[ii]);
# 游标i到达末尾
for jj in range(j, len(rightArr)):
temp.append(rightArr[jj]);
return temp;
# 递归写法:分而治之(先逐步拆分至单个元素,再两两合并排序)
def mergeSortWithRecursion(arr, left, right):
if left >= right:
return [arr[left]];
mid = math.floor((left + right) / 2); # 易错点:容易把 math.floor 错写成 round,应该是向下取整,否则造成死循环
# 先拆分
leftArr = mergeSortWithRecursion(arr, left, mid);
rightArr = mergeSortWithRecursion(arr, mid + 1, right);
# 后合并排序
arr = mergeTwoOrderedArr(leftArr, rightArr);
return arr;
def mergeSort(arr):
return mergeSortWithRecursion(arr, 0, len(arr) - 1);
arr2 = [110,100,90,40,80,20,60,10,30,50,70];
retSort2 = mergeSort(arr2);
print(retSort2)
arr = [1, 5, 8, 10, 2, 4, 8, 0];
# arr = [1, 5, 8, 10, 2];
retSort = mergeSort(arr);
print(retSort)
arr1 = [6, 5, 3, 1, 8, 7, 2, 4];
retSort1 = mergeSort(arr1);
print(retSort1)
|
aa2c9a2a646356d06671282ed280cafe992dedb7 | DIVYA-BHARATHI/HackerRank | /Python/Basic Data Types/Finding the Percentage/Solution.py | 523 | 3.5 | 4 | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for name in student_marks.keys():
if name == query_name:
marks = list(student_marks.get(name))
total = 0
for i in marks:
total += i
percentage = total/len(marks)
print ("%.2f" %(percentage))
|
39c40683770d1e9a45a53cd0e375b62b78345444 | ysmintor/leetcode | /python/0189.rotate-array/rotate-array.py | 709 | 3.6875 | 4 | class Solution:
# 解法有很多,从空间 O(n)开始采用同一思路做到 O(1)的话,需要额外设置变量保存,会变得更加复杂,另外这题有比较多的解法,掌握的话非常不错
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(start:int, end:int, s:List[int]):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
n = len(nums) - 1
k = k % len(nums)
reverse(0, n-k, nums)
reverse(n-k+1, n, nums)
reverse(0, n, nums)
return nums |
c277576ecb8055cae51c8a7828030d971c0ea595 | justinm0rgan/python_work | /chp8/sandwhices.py | 732 | 4.3125 | 4 | # Write a function that accepts a list of items a person wants on a sandwhich.
# The function should have one parameter that collects as many items as the function call provides,
# and it should print a summary of the sandwhich that's being ordered.
# Call the function three times, using a different number of agruments each time.
def sandwhich(*sandwhich_toppings):
"""Accepts list ot toppings a person wants on a sandwhich and prints summary"""
print(f"\nHere is a summary of the sandwhich you are ordering:")
for topping in sandwhich_toppings:
print(f"{topping.title()}")
sandwhich('jalepenos', 'olives', 'roasted red peppers')
sandwhich('sprouts', 'tomato','cucumber')
sandwhich('green peppers', 'avocado', 'radish')
|
ec7d3469b319ba9d1170aa79ff07f49124224d5e | hamidehsaadatmanesh/ML-Udemy | /simpleLinearRegression.py | 1,135 | 4.03125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state=1)
lr = LinearRegression()
lr.fit(x_train,y_train)
y_pred = lr.predict(x_test)
plt.scatter(x_train,y_train, color='red')
plt.plot(x_train,lr.predict(x_train), color='blue')
plt.title('salary vs exprience (Training Set)')
plt.xlabel('Years of Exprience')
plt.ylabel('Salary of Exprience')
plt.show()
plt.scatter(x_test,y_test, color='red')
plt.plot(x_train,lr.predict(x_train), color='blue')
plt.title('salary vs exprience (Test Set)')
plt.xlabel('Years of Exprience')
plt.ylabel('Salary of Exprience')
plt.show()
# **Making a single prediction (for example the salary of an employee with 12 years of experience)**
print(lr.predict([[12]]))
# ## Getting the final linear regression equation with the values of the coefficients
print(lr.coef_)
print(lr.intercept_) |
c6bcc5e3ba8ec253d49eebb31bbda92a871792fc | lixiang2017/leetcode | /leetcode-cn/0104.0_Maximum_Depth_of_Binary_Tree.py | 1,244 | 3.84375 | 4 | '''
DFS
执行用时:48 ms, 在所有 Python3 提交中击败了45.03% 的用户
内存消耗:17.3 MB, 在所有 Python3 提交中击败了31.22% 的用户
通过测试用例:39 / 39
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
'''
BFS
执行用时:48 ms, 在所有 Python3 提交中击败了45.03% 的用户
内存消耗:16.3 MB, 在所有 Python3 提交中击败了85.35% 的用户
通过测试用例:39 / 39
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
q, d = [root], 0
while q:
q = [child for node in q for child in (node.left, node.right) if child]
d += 1
return d
|
0816042a2b15d384acf104892f05b837b0ce7907 | vijayjag-repo/LeetCode | /Python/LC_Vertical_Order_Traversal.py | 946 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def verticalTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
ans = []
array = []
def dfs(node,x,y):
if not node:
return
array.append((x,y,node.val))
dfs(node.left,x-1,y+1)
dfs(node.right,x+1,y+1)
dfs(root,0,0)
array = sorted(array,key = lambda x: [x[0],x[1],x[2]])
ans.append([array[0][2]])
for i in range(1,len(array)):
if(array[i][0]==array[i-1][0]):
ans[-1].append(array[i][2])
else:
ans.append([array[i][2]])
return ans
|
0b06ccd5e4a798a50535e578bcc42fba255a1aef | kimmyoo/python_leetcode | /ROLLING_SUM/134_gas_station/solution.py | 603 | 3.546875 | 4 | class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
#totalLeft is used to see if we have used up all gas
gasLeft, startIndex, totalLeft = 0, 0, 0
for i in range(len(gas)):
gasLeft += gas[i] - cost[i]
totalLeft += gas[i] - cost[i]
if gasLeft < 0:
startIndex = i + 1
gasLeft = 0
if totalLeft < 0:
return -1
return startIndex |
e2b4d8b5905a2bca62376db1d4350f51b7dd7290 | poorjanos/Tip-Game | /Utils/data_manipulation.py | 863 | 3.75 | 4 | def score_match(player_tip, match_result):
'''
Compare two tuples and derive scores
'''
player_tip_diff = player_tip[0] - player_tip[1]
match_result_diff = match_result[0] - match_result[1]
# Exact tip
if player_tip == match_result:
score = 3
# Not exact tip
else:
# Got draw right
if player_tip_diff == 0 and match_result_diff == 0:
score = 1
# Wrong with one draw (need to catch this to avoid ZeroDivisionError)
elif not all([player_tip_diff, match_result_diff]):
score = 0
# Got winner right
elif player_tip_diff*1/abs(player_tip_diff) == match_result_diff*1/abs(match_result_diff):
score = 1
# Wrong
else:
score = 0
return score
|
c9bbe4c5436db17e2912ca63fd0f7e65ae48c741 | larmc20/exercicios | /exercicio20.py | 345 | 3.96875 | 4 | """O mesmo professor do desafio 019 quer sortear a ordem de apresentação
de trabalhos dos alunos. Faça um programa que leia o nome dos quatro
alunos e mostre a ordem sorteada."""
#imports
import random
lista = []
for i in range(1,5):
lista.append(str(input(f"Coloque o nome do {i}° aluno: ")))
random.shuffle(lista)
print(lista)
|
57142dd03ef476a273ea480380ae3987db222e25 | zhangqiang1003/python_collect | /LeetCode/two_sum.py | 1,881 | 3.6875 | 4 | # 1. 两数之和
"""
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,
并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
"""
# def two_sum(nums, target):
# # 判断奇偶性
# for data in nums:
# try:
# ret_a = nums.index(data)
# ret_b = nums.index(target - data, ret_a + 1)
# except:
# pass
# else:
# return [ret_a, ret_b]
#
#
# ret = two_sum([50000000, 3, 2, 4, 50000000], 100000000)
# print(ret)
# def two_sum(nums, target):
# length = len(nums)
# for i in range(length):
# num = target - nums[i]
# if (i + 1) < length and num in nums[i + 1::]:
# index = nums.index(num, i+1)
# return [i, index]
# def two_sum(nums, target):
# ret_num = None
# first_key = None
# find_comm = False
# for key, value in enumerate(nums):
# num = target - value
# if ret_num == value:
# return [first_key, key]
# elif num == value:
# if num in nums[key+1::]:
# find_comm = True
# first_key = key
# ret_num = num
# continue
# elif num in nums and not find_comm:
# first_key = key
# ret_num = num
# continue
def two_sum(nums, target):
temp = {}
for i in range(len(nums)):
num = nums[i]
diff = target - num
try:
return [temp[diff], i]
except:
temp[num] = i
# ret = two_sum([50000000, 7, 2, 4, 50000000], 100000000)
# ret = two_sum([50, 3, 2, 4], 5)
# ret = two_sum([2,7,11,15], 9)
ret = two_sum([3,2, 4], 6)
# [2,7,11,15]
# 9
print(ret)
|
64f4160f7cd4a608d9e9347bcbb58c267163a551 | cami-la/python_curso_em_video | /Mundo02:estruturas-de-controle/exercicio-python#043-indice-de-massa-corporal.py | 1,318 | 3.984375 | 4 | from termcolor import colored, cprint
'''
Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu Índice de Massa Corporal (IMC) e mostre seu status, de acordo com a tabela abaixo:
- IMC abaixo de 18,5: Abaixo do Peso
- Entre 18,5 e 25: Peso Ideal
- 25 até 30: Sobrepeso
- 30 até 40: Obesidade
- Acima de 40: Obesidade Mórbida
'''
def play():
exercise()
weight = float(input("Type the weight: (kg) "))
height = float(input("Type the heignt: (m) "))
imc = weight / (height * height)
if (imc < 18.5):
print(f"According with your IMC {imc:.1f}, your are UNDER WEIGHT.")
elif (imc <= 25):
print(f"According with your IMC {imc:.1f}, your are IDEAL WEIGHT.")
elif (imc <= 30):
print(f"According with your IMC {imc:.1f}, your are OVERWEIGHT.")
elif (imc <= 40):
print(f"According with your IMC {imc:.1f}, your are OBESITY.")
else:
print(f"According with your IMC {imc:.1f}, your are MORBID OBESITY.")
def exercise():
cprint("""Develop a logic that reads the weight and height of a person, calculate your IMC and show its status, according with the table below:
- IMC below 18,5: under weight
- between 18,5 and 25: ideal weight
- 25 up to 30: overweight
- 30 up to 40: obesity
- above 40: morbid obesity\n""","green", attrs=["blink"])
|
b62dcf95286f845fb86aad11b79f9d7c52fdbf48 | moxixmx533/RL_for_logistics | /gym_warehouse/envs/warehouse_objects.py | 4,252 | 3.828125 | 4 | """
Classes for objects in the warehouse, i.e. agents, bins, and staging areas.
"""
import copy
import random
NO_ITEM = 0
class WarehouseObject:
"""
Base class for warehouse object: has position and status.
Agents, bins and staging areas are warehouse objects.
Parameters
----------
data : dict
A dictionary containining the information about the object, as it is
stored in the json file. Must have 'position' and 'status' keys.
"""
def __init__(self, data):
self.position = tuple(data['position'])
self.status = data['status']
self.initial_position = copy.copy(self.position)
self.initial_status = copy.copy(self.status)
def reset(self):
"""
Returns this object to its initial state, i.e. its initial position
and status.
"""
self.position = copy.copy(self.initial_position)
self.status = copy.copy(self.initial_status)
def is_empty(self):
"""
Checks whether
"""
return all(item == NO_ITEM for item in self.status)
def free(self, slot):
"""
Checks whether the specified slot is free.
Parameters
----------
slot : int
The slot to check.
Returns
-------
bool
True if there is no item in the slot.
"""
return self.status[slot] == NO_ITEM
def pick(self, slot):
"""
Picks the item from the specified slot. The slot must be non-empty.
After picking, the slot is empty.
Parameters
----------
slot : int
The slot to pick from.
Returns
-------
item : int
The item that was in the slot.
"""
assert self.status[slot] != NO_ITEM
item = self.status[slot]
self.status[slot] = NO_ITEM
return item
def put(self, slot, item):
"""
Puts the item into the specified slot. The slot must be empty.
After putting, the item is in the slot.
Parameters
----------
slot : int
The slot to put into.
item : int
The item to put into the slot.
"""
assert self.status[slot] == NO_ITEM
self.status[slot] = item
class Agent(WarehouseObject):
"""
The agent.
"""
pass
class Bin(WarehouseObject):
"""
A WarehouseObject that additionally has a list of access spots.
Regular bins as well as the staging areas are bins.
Parameters
----------
data : dict
A dictionary containining the information about the object, as it is
stored in the json file. Must have 'position', 'status' and
'access_spots' keys.
"""
def __init__(self, data):
super().__init__(data)
self.access_spots = [tuple(pos) for pos in data['access_spots']]
class Obstacle(WarehouseObject):
"""
An obstacle.
"""
pass
class StagingInArea(Bin):
"""
The staging-in area.
"""
pass
class StagingOutArea(Bin):
"""
The staging-out area.
The status variable doesn't represent the current contents of the bin,
but rather the desired contents of the bin.
"""
def put(self, slot, item):
"""
Putting into the staging-out area works differently than putting into
other containers: you can only put into a slot of the staging-out area
if the item you're trying to put is requested in that slot.
After putting, the slot will be empty.
Parameters
----------
slot : int
The slot to put into.
item : int
The item to put into the slot.
"""
assert self.status[slot] == item
self.status[slot] = NO_ITEM
def requires(self, slot, item):
"""
Checks whether the item is required in the given slot.
Parameters
----------
slot : int
The slot to check.
item : int
The item to check.
Returns
-------
bool :
True if the item is required in the given slot.
"""
return self.status[slot] == item and item != NO_ITEM
|
ddc4b472bd15fe35ff66dc496403e78c599d36fc | bomor/cracking_the_coding_interview-python_sol | /chapter1/q1_8.py | 351 | 4.09375 | 4 | # 1.8 (A method called "is_substring" is given)
def is_rotation(s1, s2):
if len(s1) == len(s2):
con_s2 = s2 + s2
return is_substring(s1, con_s2)
return False
def is_substring(s1, s2):
return s1 in s2
# Tests
def test_is_rotation():
assert is_rotation("apple", "pleap")
assert not is_rotation("apple", "ppale")
|
0be3cef2db05f49d3c7ba5472238432d3fcb2fbc | lilyandcy/python3 | /leetcode/findSecondMinimumValue.py | 1,626 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root.left == None and root.right == None:
return -1
if root.left.val == root.right.val == root.val:
if self.findSecondMinimumValue(root.left) != -1 and self.findSecondMinimumValue(root.right) != -1:
return min(self.findSecondMinimumValue(root.left), self.findSecondMinimumValue(root.right))
elif self.findSecondMinimumValue(root.left) == -1:
return self.findSecondMinimumValue(root.right)
elif self.findSecondMinimumValue(root.right) == -1:
return self.findSecondMinimumValue(root.left)
else:
return -1
else:
if min(root.left.val, root.right.val) != root.val:
return min(root.left.val, root.right.val)
else:
if root.left.val > root.right.val:
rval = self.findSecondMinimumValue(root.right)
if rval == -1:
return root.left.val
else:
return min(root.left.val, rval)
else:
lval = self.findSecondMinimumValue(root.left)
if lval == -1:
return root.right.val
else:
return min(root.right.val, lval) |
01b6cb59c36a70cdc64c67d2cbf1b11a32b801cf | ShashwatVv/Ciphers | /simpleSubEditor.py | 4,832 | 4.28125 | 4 | # Simple Substitution Cipher Editor, http://inventwithpython.com/hacking (BSD Licensed)
import textwrap, string, pyperclip
myMessage = ''
SYMBOLS = ''
def main(useText=None, useMapping=None):
print('Simple Substitution Cipher Editor')
while True:
# Get the text to start editing:
if useText == None:
# start editing a new cipher
print('Enter the cipher text you want to decrypt (or "quit"):')
# Handle if the user wants to quit:
ciphertext = input('> ').upper()
if ciphertext == 'QUIT':
return
else:
ciphertext = useText
if useMapping == None:
mapping = getBlankMapping() # start with a new, blank mapping.
else:
mapping = useMapping
while True:
# On each iteration of this loop, display the current translation
# and let the user type in a command to perform.
# Display the current translation:
print('\n\n\n')
printMessage(ciphertext, mapping)
printMapping(mapping)
print('COMMANDS: Enter ciphertext letter to substitute, or "quit", "clear",')
print('"copy message", "copy key", "enter key", or "new":')
# Get a command from the user and perform it:
command = input('> ').upper()
if command == 'QUIT':
return
elif command == 'CLEAR':
# reset the mapping to a new, blank mapping
mapping = getBlankMapping()
elif command == 'NEW':
print('\n' * 25) # print a huge gap
break # break out of the inner loop
elif command == 'COPY MESSAGE':
pyperclip.copy(getTranslation(ciphertext, mapping))
print('Copied the translated text to the clipboard.')
elif command == 'COPY KEY':
key = ''
for letter in string.ascii_uppercase:
key += mapping[letter]
pyperclip.copy(key)
print('Copied the key to the clipboard.')
elif command == 'ENTER KEY':
pass # TODO
else:
# Assume the user is trying to suggest a ciphertext replacement:
# get the ciphertext letter
if len(command) != 1 or command not in string.ascii_uppercase:
print('Invalid character. Please specify a single letter.')
continue
# get the letter that will replace this ciphertext letter
print('Enter letter that %s should map to:' % command)
mapToLetter = input('> ').upper()
if mapToLetter == '':
# entering nothing means the user wants to reset that ciphertext letter
mapToLetter = '_'
if len(mapToLetter) != 1 or mapToLetter not in string.ascii_uppercase + '_':
print('Invalid character. Please specify a single letter.')
continue
# add this replacement letter to the current mapping
mapping[command] = mapToLetter.lower()
def getTranslation(ciphertext, mapping):
# Returns a string of the translation of ciphertext. Each character
# in ciphertext is used as a key in mapping, and the returned
# string uses the character that is the value for that key.
result = ''
for letter in ciphertext:
if letter not in string.ascii_uppercase:
result += letter
else:
result += mapping[letter]
return result
def getBlankMapping():
# Returns a dict with keys of the uppercase letters and values of
# the string '_'.
mapping = {}
for letter in string.ascii_uppercase:
mapping[letter] = '_'
return mapping
def printMessage(ciphertext, mapping):
# Print the cipher text, along with the translation according to the
# current mapping. The text will never go past 80 characters in length
# per line.
# Split up the cipher text into lines of at most 80 characters in length,
# and then put them in a list of these lines.
wrappedText = textwrap.fill(ciphertext)
lines = wrappedText.split('\n')
for line in lines:
# Print each line of ciphertext, followed by its translation.
print(line)
print(getTranslation(line, mapping))
print()
def printMapping(mapping):
# Print the mapping in a user-friendly format.
print('Current Key:')
print(' ' + ' '.join(list(string.ascii_uppercase)))
print(' ', end='')
for letter in string.ascii_uppercase:
print(mapping[letter] + ' ', end='')
print()
if __name__ == '__main__':
main()
|
9da2b9371e601608cb869d9f53d5530b69473be0 | greenfox-zerda-lasers/SzaboRichard | /week-07-home-alone/gyak/exam1.py | 602 | 4.3125 | 4 | # Create a function that takes a list as a parameter,
# and returns a new list with every second element from the orignal list
# It should raise an error if the parameter is not a list
# example: [1, 2, 3, 4, 5] should produce [2, 4]
def evry_second_item_from_alist(data_list):
try:
new_returned_list = []
for i in data_list:
if i % 2 == 0:
new_returned_list.append(i)
return new_returned_list
except TypeError as param:
print("{0}, is not a list".format(param))
example= [1, 2, 3, 4, 5]
print(evry_second_item_from_alist(example))
|
b4c170e55d456ff8247100a9dc520f2edebd03a0 | n-wbrown/psbeam | /psbeam/contouring.py | 5,603 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Low to mid level functions and classes that mostly involve contouring. For more
info on how they work, visit OpenCV's documentation on contours:
http://docs.opencv.org/trunk/d3/d05/tutorial_py_table_of_contents_contours.html
"""
############
# Standard #
############
import logging
###############
# Third Party #
###############
import cv2
import numpy as np
##########
# Module #
##########
from .images.templates import circle
from .beamexceptions import (NoContoursPresent, InputError)
logger = logging.getLogger(__name__)
def get_contours(image, factor=3):
"""
Returns the contours of an image according to a mean-threshold.
Parameters
----------
image : np.ndarray
Image to extract the contours from.
factor : int, optional
Number of times to multiply the std by before adding to the mean for
thresholding.
Returns
-------
contours : list
A list of the contours found in the image.
"""
_, image_thresh = cv2.threshold(
image, image.mean() + image.std()*factor, 255, cv2.THRESH_TOZERO)
_, contours, _ = cv2.findContours(image_thresh, 1, 2)
return contours
def get_largest_contour(image=None, contours=None, factor=3):
"""
Returns largest contour of the contour list. Either an image or a contour
must be passed.
Function is making an implicit assumption that there will only be one
(large) contour in the image.
Parameters
----------
image : np.ndarray, optional
Image to extract the contours from.
contours : np.ndarray, optional
Contours found on an image.
factor : int, optional
Number of times to multiply the std by before adding to the mean for
thresholding.
Returns
-------
np.ndarray
Contour that encloses the largest area.
"""
# Check if contours were inputted
if contours is None:
contours = get_contours(image, factor=factor)
# Check if contours is empty
if not contours:
raise NoContoursPresent
# Get area of all the contours found
area = [cv2.contourArea(cnt) for cnt in contours]
# Return argmax and max
return contours[np.argmax(np.array(area))], np.array(area).max()
def get_moments(image=None, contour=None):
"""
Returns the moments of an image.
Attempts to find the moments using an inputted contours first, but if it
isn't inputted it will compute the contours of the image then compute
the moments.
Parameters
----------
image : np.ndarray
Image to calculate moments from.
contour : np.ndarray
Beam contour.
Returns
-------
list
List of zero, first and second image moments for x and y.
"""
try:
return cv2.moments(contour)
except TypeError:
contour, _ = get_largest_contour(image)
return cv2.moments(contour)
def get_centroid(M):
"""
Returns the centroid using the inputted image moments.
Centroid is computed as being the first moment in x and y divided by the
zeroth moment.
Parameters
----------
M : list
List of image moments.
Returns
-------
tuple
Centroid of the image moments.
"""
return int(M['m10']/M['m00']), int(M['m01']/M['m00'])
def get_bounding_box(inp_array, image=True, factor=1):
"""
Finds the up-right bounding box that contains the inputted contour. Either
an image or contours have to be passed.
Parameters
----------
inp_array : np.ndarray
Array that can be the image contour or the image.
image : bool
Argument specifying that the inputted array is actually an image.
Returns
-------
tuple
Contains x, y, width, height of bounding box.
It should be noted that the x and y coordinates are for the bottom left
corner of the bounding box. Use matplotlib.patches.Rectangle to plot.
"""
if not image:
return cv2.boundingRect(inp_array)
else:
contour, _ = get_largest_contour(image=inp_array, factor=factor)
return cv2.boundingRect(contour)
def get_contour_size(inp_array, image=False, factor=1):
"""
Returns the length and width of the contour, or the contour of the image
inputted.
Parameters
----------
inp_array : np.ndarray
Array that can be the image contour or the image.
image : bool
Argument specifying that the inputted array is actually an image.
Returns
-------
tuple
Length and width of the inputted contour.
"""
_, _, w, l = get_bounding_box(inp_array, image=image, factor=factor)
return l, w
# Define circle_contour as a global
_circle_contour, _ = get_largest_contour(circle, factor=0)
def get_circularity(contour, method=1):
"""
Returns a score of how circular a contour is by comparing it to the
contour of the template image, "circle.png." in the template_images
directory.
Parameters
----------
contour : np.ndarray
Contour to be compared with the circle contour
method : int, optional
Matches the contours according to an enumeration from 0 to 2. To see
the methods in detail, go to:
http://docs.opencv.org/3.1.0/df/d4e/group__imgproc__c.html#gacd971ae682604ff73cdb88645725968d
Returns
-------
float
Value ranging from 0.0 to 1.0 where 0.0 is perfectly similar to a
circle.
"""
return cv2.matchShapes(_circle_contour, contour, method, 0)
|
876ee3a679787d6fa10d306e31a9067245e71d71 | rongqingpin/RSI_python | /Lecture3_5_stack.py | 485 | 3.90625 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
a = Stack()
a.isEmpty()
a.push(1)
a.push(2)
a
a.peek()
b = 'apple'
c = list(b)
c
c.reverse()
c
d = ''
for i in c: d += i
d
|
8c4520d00ff071ec73c19d18e84ce275ef7ffeca | coda-nsit/languages | /python/mapFilterReduce.py | 191 | 3.859375 | 4 | # map(function, iterable): returns a
def incrementer(elem):
return elem + 1
x = [2, 3, 4, 5, 6]
print(x)
y = map(incrementer, x)
print(list(y))
z = map(lambda i: i + 1, x)
print(list(z)) |
34077ebdb52af7e601c11993309c547e37f57060 | wbq9224/Leetcode_Python | /Leetcode/21_MergeTwoLists.py | 1,533 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from Leetcode.OtherAlgorithm.ListNode import *
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# 方法一:递归
# if not l1:
# return l2
# if not l2:
# return l1
#
# p = ListNode(None)
# if l1.data < l2.data:
# p = l1
# p.next = self.mergeTwoLists(l1.next, l2)
# else:
# p = l2
# p.next = self.mergeTwoLists(l1, l2.next)
# return p
# 方法二:循环
p_head = p = ListNode(0)
while l1 and l2:
if l1.data < l2.data:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
p.next = l1 or l2
return p_head.next
if __name__ == '__main__':
head1 = ListNode(None)
head2 = ListNode(None)
for i in range(0, 10, 2):
node = ListNode(i)
add_node(head1, node)
for i in range(1, 11, 2):
node = ListNode(i)
add_node(head2, node)
print_list(head1)
print_list(head2)
print('-----------------')
p = Solution().mergeTwoLists(head1.next, head2.next)
new_head = ListNode(None)
new_head.next = p
print_list(new_head)
|
f1c30ffe64721a6ff221ef8a7bd7183eb5200220 | lemy12/python_shorts | /guessing_game_one.py | 515 | 4.09375 | 4 | import random
number = random.randint(1,9)
number_of_guesses = 0
while True:
number_of_guesses += 1
guess = int(input("Enter your guess: "))
if(guess > number):
print ("Your guess was too high")
elif(guess < number):
print ("Your guess was too low")
else:
print ("You have guessed the number")
if(number_of_guesses == 1):
print("It took you 1 guess, nice")
else:
print ("It took you %i guesses" % number_of_guesses)
break
|
ec71dfe4ef34c5af61f3ca4bf16391d438bec57e | ZY1N/Pythonforinfomatics | /ch2/2_3.py | 282 | 4.0625 | 4 | #Exercise 2.3 Write a program to prompt the user for hours and rate per hour to
#compute gross pay.
#Enter Hours: 35
#Enter Rate: 2.75
#Pay: 96.25
hours = raw_input('Enter Hours:')
rate = raw_input('Enter Rate:')
hours = float (hours)
rate = float(rate)
print 'Pay:', hours * rate
|
d3d084c470918b9000dc1ac6b6fc81c5e0ec7aa3 | saifeemustafaq/alaTest | /test.py | 3,598 | 3.875 | 4 | dict_A = {}
dict_B = {}
the_Numbers, the_Pure_Num = [],[]
def inputs():
print("How many prefix do you want to give for |OPERATOR A| :")
count_A = int(input())
print("Please input a total of ",count_A," prefix and prices separated by space")
for x in range(0, count_A):
data = input().split(' ')
dict_A[data[0]] = float(data[1])
print("How many prefix do you want to give for |OPERATOR B| :")
count_B = int(input())
print("Please input a total of ",count_B," prefix and prices separated by space")
for y in range(0, count_B):
data = input().split(' ')
dict_B[data[0]] = float(data[1])
## Here we will find the highest key
list_keys_A = list(dict_A.keys())
list_keys_B = list(dict_B.keys())
list_value_A = list(dict_A.values())
list_value_B = list(dict_B.values())
temp_list = list_keys_A + list_keys_B
longest_prefix = len(str(max(temp_list, key = len)))
#print(longest_prefix)
print("How many numbers do you want to calculate the prices for: ")
total_Number = int(input())
print("Please input the numbers followed by the enter key:")
for x in range(0, total_Number):
numbers = input()
the_Numbers.append(numbers)
for y in the_Numbers:
pure_num = ''.join(filter(str.isalnum, y))
the_Pure_Num.append(pure_num)
# print (the_Pure_Num)
# print(list_keys_A)
# print(list_keys_B)
for j in range (0, len(the_Pure_Num)):
number(the_Pure_Num[j], longest_prefix, list_keys_A, list_keys_B, temp_list, list_value_A, list_value_B)
def number(mainNum, longest_prefix, list_keys_A, list_keys_B, templist, list_value_A, list_value_B):
opNum = mainNum[:longest_prefix]
for i in range(0,longest_prefix):
if len(opNum) == 1 and opNum not in templist:
print("No Operator Found for number", mainNum)
if opNum in templist:
if opNum in list_keys_A and opNum in list_keys_B:
# print("The ", opNum,"is provided by both OP")
index1 = list_keys_A.index(opNum)
comp1 = list_value_A[index1]
index2 = list_keys_B.index(opNum)
comp2 = list_value_B[index2]
if comp1 > comp2:
print("The Code of the num *",mainNum, "* is +",opNum,"provided by Operator A the cheaper cost of *",comp1, "*")
if comp1 < comp2:
print("The Code of the num *",mainNum, "* is +",opNum,"provided by Operator A the cheaper cost of *",comp2, "*")
if comp1 == comp2:
print("The Code of the num *",mainNum, "* is +",opNum,"provided by both operators at the same cost of *",comp2, "*")
break
if opNum in list_keys_A and opNum not in list_keys_B:
# print("The ",opNum," is provided by OP A")
index = list_keys_A.index(opNum)
print("The Code of the num *",mainNum, "* is +",opNum,"provided only by Operator A at cost *",list_value_A[index], "*")
break
if opNum in list_keys_B and opNum not in list_keys_A:
# print("The",opNum," is provided by OP B")
index = list_keys_B.index(opNum)
print("The Code of the num *",mainNum, "* is +",opNum,"provided only by Operator B at cost *",list_value_B[index], "*")
break
elif len(opNum) != 0:
opNum = opNum[:-1]
# print("Done for the number ", mainNum)ś
inputs()
|
5745b4a76b259708f09930cdd16daaecb75c1a4a | notfounnd/robot-framework-reportportal | /robot/hello/hello.py | 440 | 3.953125 | 4 | #
# Exemplo de comando para executar o código Python:
#
# Por arquivo: python app.py
#
# Comando 'def' utilizado para criar um método em Python
def welcome(name):
return "Olá " + name + ", bem vindo ao projeto exemplo de Robot Framework!"
# Atribuir retorno do metodo welcome() à variável 'result'
result = welcome("C-3PO")
# Comando 'print()' utilizado para imprimir no console o texto da variável 'result'
print(result)
|
85eda8ec23e734ae2a1cd57bb126e9b7fd66fb96 | jesus-rod/algorithms-python | /trees/path_with_given_sequence.py | 1,459 | 4.0625 | 4 | # Path With Given Sequence (medium)
# Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.
# Sequence: [1, 0, 7] Output: false Explanation: The tree does not have a path 1 -> 0 -> 7.
# Sequence: [1, 1, 6] Output: true Explanation: The tree has a path 1 -> 1 -> 6.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_path(root, sequence):
return find_path_helper(root, sequence, [])
def find_path_helper(current_node, target_sequence, current_path):
if current_node is None:
return False
current_path.append(current_node.val)
is_leaf = current_node.left is None and current_node.right is None
if is_leaf and current_path == target_sequence:
return True
left_path = find_path_helper(
current_node.left, target_sequence, current_path)
right_path = find_path_helper(
current_node.right, target_sequence, current_path)
del current_path[-1]
return left_path or right_path
def main():
root = TreeNode(1)
root.left = TreeNode(0)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.right.left = TreeNode(6)
root.right.right = TreeNode(5)
print("Tree has path sequence: " + str(find_path(root, [1, 0, 7])))
print("Tree has path sequence: " + str(find_path(root, [1, 1, 6])))
main()
|
6aebbba24a473058099622a53f35032e600a1ec7 | 2018hsridhar/Leetcode_Solutions | /leetcode_2451.py | 1,311 | 3.828125 | 4 | '''
URL = https://leetcode.com/problems/odd-string-difference/
2451. Odd String Difference
Complexity
Let W := # words in words
Let K := len(max_word)
Time = O(WK)
Space = O(1) ( IMP ) O() ( EXP )
'''
# TBH, we could make concatenate strings instead ( simplifies problem massively)
# well . . . do append a "-" to help out too!
def getStringifiedDifferenceArrayOfWord(word: str) -> str:
differenceList = ""
for idx in range(len(word) - 1):
delta = str(ord(word[idx+1]) - ord(word[idx]))
differenceList = differenceList + delta + '-'
return differenceList
class Solution:
def oddString(self, words: List[str]) -> str:
myOddString = ""
freqDifferenceArrays = {}
for word in words:
serializedWordDifferenceArray = getStringifiedDifferenceArrayOfWord(word)
if(serializedWordDifferenceArray not in freqDifferenceArrays):
freqDifferenceArrays[serializedWordDifferenceArray] = 0
freqDifferenceArrays[serializedWordDifferenceArray] += 1
for word in words:
serializedWordDifferenceArray = getStringifiedDifferenceArrayOfWord(word)
if(freqDifferenceArrays[serializedWordDifferenceArray] == 1):
myOddString = word
break
return myOddString
|
d5eba27bd4afc5f3bd66a566b5a480ba09ed6528 | chenlanlan/leetcode | /Sudoku Solver2 .py | 1,336 | 3.546875 | 4 | class Solution:
# @param {character[][]} board
# @return {void} Do not return anything, modify board in-place instead.
def solveSudoku(self, board):
def isValid(x,y):
tmp=board[x][y]; board[x]= board[x][:y] + 'D' + board[x][y + 1:]
for i in range(9):
if board[i][y]==tmp: return False
for i in range(9):
if board[x][i]==tmp: return False
for i in range(3):
for j in range(3):
if board[(x//3)*3+i][(y//3)*3+j]==tmp: return False
board[x]= board[x][:y] + tmp + board[x][y + 1:]
return True
def dfs(board):
for i in range(9):
for j in range(9):
if board[i][j]=='.':
for k in '123456789':
board[i] = board[i][:j] + k + board[i][j + 1:]
if isValid(i,j) and dfs(board):
return True
board[i] = board[i][:j] + '.' + board[i][j + 1:]
return False
return True
dfs(board)
return board
test = Solution()
print(test.solveSudoku(["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."]))
|
fad7292248291f0c8e727c6e4c7328dc0268ce7d | daidai21/read_source_code | /curio/hello2.py | 1,415 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# #############################################################################
# File Name : hello2.py
# Author : DaiDai
# Mail : daidai4269@aliyun.com
# Created Time: 一 3/29 23:46:33 2021
# #############################################################################
import curio
async def countdown(n):
while n > 0:
print('T-minus', n)
await curio.sleep(1)
n -= 1
async def kid(x, y):
try:
print('Getting around to doing my homework')
await curio.sleep(1000)
return x * y
except curio.CancelledError: # 取消任务的时候抛错
print("No go diggy die!")
raise
async def parent():
kid_task = await curio.spawn(kid, 37, 42) # spawn: 生产
count_task = await curio.spawn(countdown, 10) # curio.spawn() 启动并发任务
await count_task.join() # .join() 等待任务结束
print("Are you done yet?")
try:
result = await curio.timeout_after(5, kid_task.join) # 5s后就timeout
print("Result:", result)
except curio.TaskTimeout as e: # 捕捉timeout,取消任务
print("We've got to go!")
await kid_task.cancel()
if __name__ == '__main__':
# 创建新窗口
# > python3 -m curio.monitor
# > ps # 可以看到线程状态
# > w 4 # 查看堆栈跟踪
curio.run(parent, with_monitor=True)
|
a7de96249deb0c0831469f119df44104d6d376a0 | dane-piper/ELements-of-Computing-Projects | /CircularList.py | 2,886 | 3.96875 | 4 | import os
class Link(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class CircularList(object):
# Constructor
def __init__(self):
self.first = None
# Insert an element (value) in the list
def insert(self, data):
new_link = Link(data)
if self.first is None:
self.first = new_link
self.first.next = self.first
else:
current = self.first
while current.next != self.first:
current = current.next
current.next = new_link
new_link.next = self.first
# Find the link with the given data (value)
def find(self, data):
current = self.first
while current.next != self.first:
if current.data == data:
return current
current = current.next
if current.data == data:
return current
else:
return None
# Delete a link with a given data (value)
def delete(self, data):
previous = self.first
current = self.first
while current.next != self.first:
current = current.next
last = current
current = self.first
if (current == None):
return None
while (current.data != data):
if (current.next == self.first):
return None
else:
previous = current
current = current.next
if current == self.first:
self.first = self.first.next
last.next = self.first
else:
previous.next = current.next
return current.data
# Delete the nth link starting from the Link start
# Return the next link from the deleted Link
def delete_after(self, start, n):
current = self.find(start)
for x in range(n - 1):
current = current.next
next = current.next
print(current.data)
self.delete(current.data)
return next.data
# Return a string representation of a Circular List
def __str__(self):
current = self.first
string = ''
while current.next != self.first:
string +=str(current.data) + ' '
current = current.next
string += str(current.data) + ' '
print(string)
def main():
soldiers = 12
start = 1
count = 3
soldiersleft = CircularList()
for num in range(1, soldiers + 1):
soldiersleft.insert(num)
soldiersleft.__str__()
while soldiersleft.first.next != soldiersleft.first:
soldiersleft.__str__()
start = soldiersleft.delete_after(start, count)
print(soldiersleft.first.data)
# add code here
main() |
1721273ee26acd5efc5b6e084f073f876eb7691c | kevicao/python | /146. LRU Cache 138 Copy List with Random Pointer.py | 2,681 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[25]:
#https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237
# HashMap will hold the keys and address of the Nodes of Doubly LinkedList .
#And Doubly LinkedList will hold the values of keys.
# In[ ]: in this solution, head and tail is always dummy so we do not need check whehter node is tail or head
class Node:
def __init__(self, key, data):
self.value = data
self.key = key
self.next = None
self.previous = None
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.h = {}
self.head = Node(None, None) #most used
self.tail = Node(None, None) #least used
self.head.next = self.tail
self.tail.previous = self.head
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.h:
self.h[key].previous.next = self.h[key].next
self.h[key].next.previous = self.h[key].previous
self.h[key].next = self.head.next
self.head.next.previous = self.h[key]
self.h[key].previous = self.head
self.head.next = self.h[key]
return self.h[key].value
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key in self.h:
self.h[key].value = value
self.h[key].previous.next = self.h[key].next
self.h[key].next.previous = self.h[key].previous
self.h[key].next = self.head.next
self.head.next.previous = self.h[key]
self.h[key].previous = self.head
self.head.next = self.h[key]
else:
if len(self.h) == self.capacity:
#remove least used
del self.h[self.tail.previous.key]
self.tail.previous = self.tail.previous.previous
self.tail.previous.next = self.tail
self.h[key] = Node(key, value)
self.h[key].next = self.head.next
self.head.next.previous = self.h[key]
self.h[key].previous = self.head
self.head.next = self.h[key]
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
# In[ ]:
|
d8cea2541557ef2e14d3da306e067fe5ddaefc54 | rsokl/plymi_mod6 | /plymi_mod6/homography.py | 3,850 | 3.546875 | 4 | from typing import Tuple
import numpy as np
__all__ = ["transform_corners"]
def _get_cartesian_to_homogeneous_transform(
p1: Tuple[float, float],
p2: Tuple[float, float],
p3: Tuple[float, float],
p4: Tuple[float, float],
) -> np.ndarray:
"""
Given a set of four 2D cartesian coordinates, produces
the transformation matrix that maps the following basis
to homogeneous coordinates:
(1, 0, 0) -> Z(x1, y1, 1)
(0, 1, 0) -> Z(x2, y2, 1)
(0, 0, 1) -> Z(x3, y3, 1)
(1, 1, 1) -> Z(x4, y4, 1)
Where Z is a real-valued constant
Parameters
----------
p1 : Tuple[float, float]
An ordered pair (x1, y1)
p2 : Tuple[float, float]
An ordered pair (x2, y2)
p3 : Tuple[float, float]
An ordered pair (x3, y3)
p4 : Tuple[float, float]
An ordered pair (x4, y4)
Returns
-------
np.ndarray, shape=(3, 3)
The transformation matrix
"""
(x1, y1) = p1
(x2, y2) = p2
(x3, y3) = p3
(x4, y4) = p4
system = np.array(
[[x1, x2, x3, x4], [y1, y2, y3, y4], [1, 1, 1, 1]], dtype=np.float64
)
A = system[:, :3]
b = system[:, 3]
return A * np.linalg.solve(A, b)
def transform_corners(
points: np.ndarray, *, source_corners: np.ndarray, dest_corners: np.ndarray
) -> np.ndarray:
""" Perform a projective transform on a sequence of 2D points,
given four corners of a plane in the source coordinate system,
and the corresponding corners in the coordinate system.
Parameters
----------
points : array_like, shape=(N, 2)
A sequence of ordered pairs to undergo the projective transform.
source_corners : array_like, shape=(4, 2)
The ordered pairs for the four corners of the original coordinate system.
dest_corners : array_like, shape=(4, 2)
The corresponding ordered pairs for the four corners of the destination
coordinate system.
Returns
-------
numpy.ndarray, shape=(N, 2)
The array of N projected points.
Examples
--------
>>> import numpy as np
>>> original_coords = np.array([[0., 0.], [1., 0.], [1., 1.], [0., 1.]])
>>> # all distances dilated by 2x and all x-coordinates shifted by +1
>>> new_coords = 2. * original_coords + np.array([1., 0])
>>> points = np.array([[0.5, 0.5]]) # center of original corners
>>> transform_corners(points, source_corners=original_coords, dest_corners=new_coords)
array([[2., 1.]])
"""
points = np.asarray(points, dtype=np.float64)
if not (points.ndim == 2 and points.shape[1] == 2):
raise ValueError(
"`points` must be array-like with shape-(N, 2), got shape {}".format(
points.shape
)
)
source_corners = np.asarray(source_corners)
# convert points to latitude/longitude
A = _get_cartesian_to_homogeneous_transform(
source_corners[0], source_corners[1], source_corners[2], source_corners[3]
)
A_inv = np.linalg.inv(A)
B = _get_cartesian_to_homogeneous_transform(
dest_corners[0], dest_corners[1], dest_corners[2], dest_corners[3]
)
# maps: new-corners (homogeneous-basis) <- cartesian-basis <- old-corners
C = np.matmul(B, A_inv)
# source_pts:
# [[px1, px2, ...]
# [py1, py2, ...],
# [ 1, 1, ...]]
num_pts = points.shape[0]
source_pts = np.hstack([points, np.ones((num_pts, 1))]).T
# homogeneous_pts:
# [[x1', y1', z1'],
# [x2', y2', z2'],
# ...]
homogeneous_pts = np.matmul(C, source_pts).T
# destination: (x'', y''), where
# x'' = x'/z'
# y'' = y'/z'
z = homogeneous_pts[:, (2,)] # shape-(N, 1)
return homogeneous_pts[:, :2] / z
|
24daeb37ad5207617e8ee7c88a88087bf279365e | qollomcbizzy/pythonintroduction | /functions.py | 987 | 3.765625 | 4 | def greet_user():
print("Hi User")
print("welcome")
print("start")
greet_user()
print("finish")
# with parameters
def greet_user_with_param(name):
print("Hi", name)
print("welcome")
print("start")
greet_user_with_param("John")
print("finish")
# with more parameters and keyword arguments
# keyword arguments should be after positional arguments
def greet_user_with_two_param(first_name, last_name):
print("Hi", first_name, last_name)
print("welcome")
print("start")
greet_user_with_two_param(last_name='denis', first_name='john')
print("finish")
# return keyword
def square(number):
return number * number;
print(square(5))
# reuse application
# function
def emoji_converter(message):
words = message.split(" ")
emojis = {
"sad": ":)",
"happy": ":(",
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
message = input(">")
print(emoji_converter(message))
|
eaa5477f12692ef799360faf224ae90bae0b1903 | chanzer/leetcode | /389_findheDifference.py | 956 | 3.671875 | 4 | """
Find the Difference
题目描述:
Given two strings s and t which consist of only
lowercase letters.
String t is generated by random shuffling string s
and then add one more letter at a random position.
Find the letter that was added in t.
Example :
Input: s = "abcd"
t = "abcde"
Output:e
Explanation:'e' is the letter that was added.
"""
# 方法一:
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
sum_s,sum_t = 0,0
for i in s:
sum_s += ord(i)
for j in t:
sum_t += ord(j)
return chr(abs(sum_s - sum_t))
# 方法二:异或的神奇操作!!!
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res = 0
for i in s+t:
res = res ^ ord(i)
return chr(res)
|
b3fa98cb406627a86f78af84f352472af9dad86c | daisyzl/program-exercise-python | /TwoDimension/xuanzhuanjuzhen.py | 1,597 | 3.921875 | 4 | #-*-coding:utf-8-*-
'''
螺旋矩阵
题目:https://leetcode-cn.com/explore/learn/card/array-and-string/199/introduction-to-2d-array/775/
先定位两个点,分别是左上x1,y1和右下x2,y2
答案:https://github.com/luliyucoordinate/Leetcode/blob/master/src/0054-Spiral-Matrix/0054.py
思想:https://blog.csdn.net/qq_17550379/article/details/83148050
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
'''
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return
result = []
#注意这里定义二维数组
m, n = len(matrix), len(matrix[0])
x1, y1, x2, y2 = 0, 0, m-1, n-1
#注意m-1, n-1 下面方便好计算
while x1 <= x2 and y1 <= y2:
for i in range(x1,x2):
result.append(matrix[y1][i])
for j in range(y1+1,y2+1):
result.append(matrix[j][x2])
if x1 < x2 and y1< y2:
for i in range(x2-1, x1, -1):
result.append(matrix[y2][i])
for j in range(y2, y1, -1):
result.append(matrix[j][x1])
x1 +=1
y1 +=1
x2 -=1
y2 -=1
return result
|
396728e33c425fe614564cabf57eed74eed4c727 | YQ-369/Learn-Python | /text.py | 1,252 | 3.875 | 4 | #!/usr/bin/env Python
# coding=utf-8
"""
统计考试成绩
"""
from __future__ import division
def average_score(scores):
"""
统计平均分.
"""
score_values = scores.values()
sum_scores = sum(score_values)
average = sum_scores/len(score_values)
return average
def sorted_score(scores):
"""
对成绩从高到低排队.
"""
score_lst = [(scores[k],k) for k in scores]
sort_lst = sorted(score_lst, reverse=True)
return [(i[1], i[0]) for i in sort_lst]
def max_score(scores):
"""
成绩最高的姓名和分数.
"""
lst = sorted_score(scores) #引用分数排序的函数 sorted_score
max_score = lst[0][1]
return [(i[0],i[1]) for i in lst if i[1]==max_score]
def min_score(scores):
"""
成绩最低的姓名和分数.
"""
lst = sorted_score(scores)
min_score = lst[len(lst)-1][1]
return [(i[0],i[1]) for i in lst if i[1]==min_score]
if __name__ == "__main__":
examine_scores = {"google":98, "facebook":99, "baidu":52, "alibaba":80, "yahoo":49, "IBM":70, "android":76, "apple":99, "amazon":99}
ave = average_score(examine_scores)
print ("the average score is:",ave) #平均分
|
f74def97ccce9fc4b900703ca07bc5ca0e7ac235 | Soundarya0/30-Days-of-Code | /Day 25/Running Time and Complexity.py | 501 | 3.9375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
import sys
def isPrime(n):
if n <= 1:
return False
sqrt_n =math.sqrt(n)
if sqrt_n.is_integer():
return False
for i in range(2, int(sqrt_n) + 1):
if n % i == 0:
return False
return True
no_of_cases = int(input())
for i in range(no_of_cases):
n = int(input())
if isPrime(n):
print('Prime')
else:
print('Not prime')
|
df05c981f52fc195310f34e4ab8bedfdd48911ef | LahiLuk/pdsnd_github | /bikeshare.py | 7,991 | 4.1875 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
city = input('\nWould you like to see data for Chicago, New York City or Washington?\n').lower()
if city in ['chicago', 'new york city', 'washington']:
break
else:
print('\nInvalid input. Please try again.')
# get user input for month (all, january, february, ... , june)
while True:
month = input('\nWould you like to see data for January, February, March, April, May, June, or for all months?\n').lower()
if month in ['january', 'february', 'march', 'april', 'may', 'june', 'all']:
break
else:
print('\nInvalid input. Please try again.')
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input('\nWould you like to see data for Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, or for all days?\n').lower()
if day in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'all']:
break
else:
print('\nInvalid input. Please try again.')
print()
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['Month'] = df['Start Time'].dt.month_name()
df['Day of Week'] = df['Start Time'].dt.day_name()
if month != 'all':
df = df[df['Month'] == month.title()]
if day != 'all':
df = df[df['Day of Week'] == day.title()]
return df
def time_stats(df, month, day):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...')
start_time = time.time()
# display the most common month
if month == 'all':
print('\nThe most common month was:')
print(df.mode()['Month'][0])
# display the most common day of week
if day == 'all':
print('\nThe most common day of the week was:')
print(df.mode()['Day of Week'][0])
# display the most common start hour
df['Start Hour'] = df['Start Time'].dt.hour
print('\nThe most common start hour was:')
print(str(int(df.mode()['Start Hour'][0])) + ':00')
print("\nThis took %s seconds.\n" % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...')
start_time = time.time()
# display most commonly used start station
print('\nThe most commonly used start station was:')
print(df.mode()['Start Station'][0])
# display most commonly used end station
print('\nThe most commonly used end station was:')
print(df.mode()['End Station'][0])
# display most frequent combination of start station and end station trip
df['Trip'] = df['Start Station'] + ' to ' + df['End Station']
print('\nThe most frequent trip was:')
print(df.mode()['Trip'][0])
print('\nThis took %s seconds.\n' % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...')
start_time = time.time()
# display total travel time
df['End Time'] = pd.to_datetime(df['End Time'])
df['Travel Time'] = df['End Time'] - df['Start Time']
ttt = df['Travel Time'].sum()
print('\nTotal travel time was:')
print('{} day(s), {} hour(s), {} minute(s) and {} second(s)'.format(ttt.components.days, ttt.components.hours, ttt.components.minutes, ttt.components.seconds))
# display mean travel time
mtt = df['Travel Time'].mean()
print('\nMean travel time was:')
print('{} day(s), {} hour(s), {} minute(s) and {} second(s)'.format(mtt.components.days, mtt.components.hours, mtt.components.minutes, mtt.components.seconds))
print("\nThis took %s seconds.\n" % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
try:
data = df['User Type']
except KeyError:
print('\nThere is no data for user type.')
else:
if df['User Type'].isnull().any():
df['User Type'].fillna('Unknown', inplace=True)
user_types = df['User Type'].value_counts()
print("\nDisplaying counts of user types:")
for index, value in user_types.items():
print('{}: {}'.format(index, value))
# Display counts of gender
try:
data = df['Gender']
except KeyError:
print('\nThere is no data for gender.')
else:
if df['Gender'].isnull().any():
df['Gender'].fillna('Unknown', inplace=True)
genders = df['Gender'].value_counts()
print("\nDisplaying counts of gender:")
for index, value in genders.items():
print('{}: {}'.format(index, value))
# Display earliest, most recent, and most common year of birth
try:
data = df['Birth Year']
except KeyError:
print('\nThere is no data for birth year.')
else:
print("\nThe earliest year of birth was:")
print(str(int(df['Birth Year'].min())) + '.')
print("\nThe most recent year of birth was:")
print(str(int(df['Birth Year'].max())) + '.')
print("\nThe most common year of birth was:")
print(str(int(df.mode()['Birth Year'][0])) + '.')
print("\nThis took %s seconds.\n" % (time.time() - start_time))
print('-'*40)
def main():
print('\nHello! Let\'s explore some US bikeshare data!')
condition = True
while condition == True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df, month, day)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
# request user input (for raw data display)
i = 0
while True:
display = input("\nWould you like to see (the next) 5 lines of raw data? Enter 'yes' or 'no'.\n").lower()
if display == 'no':
break
elif display == 'yes':
print(df.iloc[i: i+5])
i += 5
else:
print('\nInvalid input. Please try again.')
# request user input (for restart)
while True:
restart = input("\nWould you like to restart? Enter 'yes' or 'no'.\n").lower()
if restart == 'no':
condition = False
print('\nThanks for your time and have a nice day! :)')
break
elif restart == 'yes':
break
else:
print('\nInvalid input. Please try again.')
if __name__ == "__main__":
main()
|
5493f390a298bd865134612dd6645474f533f3fd | iramgee/PracticingPython | /urllinks2.py | 641 | 3.5 | 4 | import urllib
from BeautifulSoup import *
def get_url_string():
count = 0
url = raw_input('Enter - ')
while count < 7:
print 'Successfully retrieved: ',url, '\n\n'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('a')
lst = list()
count = count + 1
for tag in tags:
name = tag.get('href', None)
lst.append(name)
# print count
url = lst[17] # grabbing url in 18th position
print 'Retrieving: ',url
print 'Successfully retrieved ',url
get_url_string()
|
40180c9daef0b4aa661f9a5b9db31b411423c6dc | Cristopher-12/POO-1719110585 | /Semana_8/alumnos.py | 1,512 | 3.921875 | 4 | answer="S" #variable para ayudar al ciclo while
datos = [] #arreglo para ayudar a almacenar los datos
class Alumnos: #creamos una clase
def __init__(self): #metodo constrcutor
pass
def datos(self): #creamos un metodo para perdir datos
name=input("Inseta el nombre del alumno: ") #Pide el nombre del alumno
año=int(input("Año de nacimeinto del alumno: ")) #pide el año de nacimiento del alumno tipo entero
grupo=input("Inserta el grupo del alumno: ") #pide el grupo del alumno
años_total=2020-año #calcula la edad restando el año actual con el año de nacimiento
datos.append("Nombre:"+str(name)+" Edad:"+str(años_total)+" Grupo:"+str(grupo)) #agrega los datos
#al arreglo datos
def Print(self): #creamos metodo para imprimir los datos capturados
for leer in datos: #leera el arreglo datos
print(leer) #imprimira en pantalla los datos capturados por indice
while answer=="s" or answer=="S" or answer=="Si" or answer=="si": #mientras que la repuesta sea S
objecto_Almuno=Alumnos() #creamos el objeto
objecto_Almuno.datos()#se estara llamando al metodo para la captura de datos
answer=input("¿Desea leer mas datos de alumnos? S/N ") #pregunta si deseas hacer mas capturas de alumnos
if answer=="N" or answer=="n" or answer=="No" or answer=="no": #si la respuesta es "N" o "n"
objecto_Almuno.Print() #llama al metodo que permitira imprimir
break #termina el ciclo del programa |
2d763717dacf558805d9d11b671c19a547e5652a | theshevon/A1-COMP30024 | /AStar/helperFunctions.py | 553 | 3.65625 | 4 | #Helper functions
def createBoardSet():
ran = range(-3, +3+1)
CoordSet = set()
for qr in [(q,r) for q in ran for r in ran if -q-r in ran]:
CoordSet.add(qr)
return CoordSet
def AdjacentTiles(coord):
adjacent = []
for p in [-1, 1]:
for r in [-1, 1]:
if(withinBoard(coord[0] +p , coord[1]+r)):
adjacent.append(coord[0] +p , coord[1]+r)
return adjacent
def exitCoords(colour):
exits = {
"red" : [(3, -3), (3, -2), (3,-1), (3,0)] ,
"blue" : [(-3, 0), (-2, -1), (-1,-2), (0,-3)],
"green" : [(-3, 3), (-2, 3), (-1,3), (0,3)]
} |
3bca47db97c71d3708676ac1feae81597bc9e756 | nathanbeddes/Project-Euler | /Python/Problem4.py | 1,376 | 4.375 | 4 | #! /usr/local/bin/python3.1
def isPalindrome (candidate):
"""
Determines if the number candidate is a "palindrome" or not.
e.g. 808
"""
strCandidate = str(candidate)
left = 0
right = len(strCandidate) - 1
while (left < right):
if (strCandidate[left] != strCandidate[right]):
return False
left += 1
right -= 1
return True
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 * 99.
#
# Find the largest palindrome made from the product of two 3-digit numbers.
#
# Answer:
# 993*913 = 906609
def Problem4 ():
products = 0
left = 999
largestRight = 100
largestCandidate = 0
while left > 0:
right = left
while right > largestRight:
candidate = left*right
products += 1
if isPalindrome(candidate):
if (candidate < largestCandidate):
print(largestCandidate, "is a palindrome resulting from", left, "*", right)
print(products, "products checked")
return
else:
largestCandidate = candidate
largestRight = right
else:
right -= 1
left -= 1
#print(products, "products checked")
Problem4()
|
bb7d1aab4408caa4096a8822d1b8cab5e0aad832 | smartFox-Rohan-Kulkarni/Python_hacker_rank | /Alphabet Rangoli.py | 1,039 | 3.625 | 4 | import string
from collections import defaultdict
def print_rangoli(size):
# your code goes here
dict_default= defaultdict(list)
num = size
alph = list(string.ascii_lowercase)
for i in range(1, (2 * num - 1) + 1):
for j in range(1, (2 * (2 * num - 1) - 1) + 1):
dict_default[i].append('-')
k = (len(dict_default) * 2) // 2
temp = (len(dict_default) // 2)
for i in range(1, len(dict_default) + 1):
if i <= (len(dict_default) + 1) // 2:
index = num
middle = (len(dict_default[i]) + 1) // 2
for j in range(k, k + 4 * i - 3, 2):
dict_default[i][j - 1] = alph[index - 1]
if j >= middle:
index = index + 1
else:
index = index - 1
k = k - 2
else:
dict_default[i] = dict_default[temp]
temp = temp - 1
for i in range(1, len(dict_default) + 1):
print(''.join(dict_default[i]))
if __name__ == '__main__':
|
898c900f3b5a42eb33a75395ff4dd5b459a3ca65 | CianOSull/Group_Project_2019-2020 | /MediAI/Heart/HeartDiseaseDLN.py | 906 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 12:29:08 2019
@author: Cian
"""
# first neural network with keras tutorial
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
# load the dataset
dataset = loadtxt('heartDataset.csv', delimiter=',')
# split into input (X) and output (y) variables
X = dataset[:,0:13]
y = dataset[:,13]
# define the keras model
model = Sequential()
model.add(Dense(12, input_dim=13, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the keras model on the dataset
model.fit(X, y, epochs=150, batch_size=80)
# evaluate the keras model
_, accuracy = model.evaluate(X, y)
print('Accuracy: %.2f' % (accuracy*100))
model.save("heart_model.h5")
print("Saved model to disk") |
c772003df01a1d5ae30cd5eaeac4a3f1348a3339 | R3mmurd/fractals | /game_of_life.py | 1,837 | 3.75 | 4 | """
This module contains an implemetation of the Conway's Game of Life.
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
"""
import sys
import time
import random
from tkinter import Tk, Canvas
GRID_SIZE = 5
SCREEN_SIZE = 1000
NUM_CELLS = SCREEN_SIZE // GRID_SIZE
root = Tk()
canvas = Canvas(root, width=SCREEN_SIZE, height=SCREEN_SIZE)
def draw_automaton(automaton):
canvas.delete('all')
for i in range(NUM_CELLS):
for j in range(NUM_CELLS):
if automaton[i][j] == 1:
x = GRID_SIZE * j
y = GRID_SIZE * i
canvas.create_rectangle(
x, y, x + GRID_SIZE, y + GRID_SIZE, fill='black'
)
canvas.update()
def evolve(automaton):
next_state = [[0 for _ in range(NUM_CELLS)] for _ in range(NUM_CELLS)]
for i in range(NUM_CELLS):
for j in range(NUM_CELLS):
lives = 0
for ii in range(i - 1, i + 2):
for jj in range(j - 1, j + 2):
if jj != j or ii != i:
lives += automaton[ii % NUM_CELLS][jj % NUM_CELLS]
if automaton[i][j] == 1:
if lives in (2, 3):
next_state[i][j] = 1
else:
if lives == 3:
next_state[i][j] = 1
return next_state
if __name__ == '__main__':
generations = 100 if len(sys.argv) < 2 else int(sys.argv[1])
automaton = [[0 for _ in range(NUM_CELLS)] for _ in range(NUM_CELLS)]
canvas.delete('all')
canvas.pack()
for i in range(NUM_CELLS):
for j in range(NUM_CELLS):
automaton[i][j] = random.randint(0, 1)
for _ in range(generations):
time.sleep(0.1)
automaton = evolve(automaton)
draw_automaton(automaton)
root.mainloop()
|
6cbde17028ff5f43c411686f35264d7b69a555dd | sanjibm/PyDS | /unique-chars.py | 614 | 4.125 | 4 | # Check if a String is composed of all unique characters
# OPTION 4: Array/list way
# Time: O(n) Space: O(1) but influenced by the list of length 96
def unique_characters_list(input_string):
if len(input_string)>96: # 96 = number of printable chars
return False
chars_list = [False] * 96
for char in input_string:
# take list position by taking ascii position - 32 (amount of control characters)
idx = ord(char)-32
if chars_list[idx]:
return False
chars_list[idx] = True
return True
# driver
str = 'abede'
print(unique_characters_list(str))
|
14835d7c36fb17113d2ab81505a215cc8e5ac684 | mohanrajanr/CodePrep | /we227/5673.py | 808 | 3.84375 | 4 | def maximumScore(a: int, b: int, c: int) -> int:
turns = 0
while not (((a == 0) and (b == 0)) or ((b == 0) and (c == 0)) or ((a == 0) and (c == 0))):
print(a, b, c, turns)
if a % b == 0:
a -= b
b = 0
turns += a
elif a % b == 0:
b -= a
a = 0
turns += b
elif b % c == 0:
b -= c
b = 0
turns += b
elif c % b == 0:
c -= b
c = 0
turns += c
elif c % a == 0:
c -= a
a = 0
turns += c
elif a % c == 0:
a -= c
c = 0
turns += a
return turns
print(maximumScore(2, 4, 6))
print(maximumScore(4, 4, 6))
print(maximumScore(1, 8, 8)) |
5a8c9067842ce46ce5ba79bcc97c0c52f2e72438 | riceb53/data-analysis | /prac.py | 781 | 3.734375 | 4 | # with open("/Users/Apprentice/documents/new-york-city-current-job-postings/nyc-jobs.csv") as f:
# # print(f.size())
# index = 0
# for line in f:
# print()
# print(line)
# index += 1
# print(index)
import csv
with open('/Users/Apprentice/documents/new-york-city-current-job-postings/nyc-jobs.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
highest_salary = 0
firstline = True
for row in readCSV:
if firstline:
firstline = False
continue
print()
# print(int(row[11]))
# print(row[10])
if highest_salary < float(row[11]):
highest_salary = float(row[11])
# print(row[12])
# print(row[0],row[1],row[2],)
print(highest_salary)
|
2594ed8e24e50fe68fe651bb2e512cc64bca2643 | BenRauzi/159.172 | /Exam/4.py | 326 | 3.71875 | 4 | count = 0
def sequential_search(the_list, item):
global count
count += 1
if the_list == []:
return False
elif the_list[0] == item:
return True
else:
return sequential_search(the_list[1:], item)
test = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
sequential_search(test, 16)
print(count) |
9de9245080c2cca7ada777d567d4e723d197e595 | jay6413682/Leetcode | /Palindrome_Linked_List_234.py | 4,449 | 4 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x, nxt=None):
self.val = x
self.next = nxt
class Solution1:
def isPalindrome(self, head: ListNode) -> bool:
""" 双指针,快慢指针,链表反转 similar to https://leetcode-cn.com/problems/palindrome-linked-list/solution/wo-de-kuai-man-zhi-zhen-du-cong-tou-kai-shi-gan-ju/
杨昆 comment
time: O(n), space: O(1)
"""
if not head:
return
slow = head
fast = head
curr = head
nxt = curr.next
prev = None
# 快慢指针,并同时反转链表前半部分
while fast and fast.next:
# print(slow.val, fast.val)
curr = slow
fast = fast.next.next
slow = slow.next
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
nxt = curr.next
# print(slow.val, fast, prev.val, curr.val, nxt.val)
if fast:
right_head = nxt
left_head = prev
else:
if prev.val != curr.val:
return False
right_head = nxt
left_head = prev.next
# 比较值
while left_head:
if left_head.val != right_head.val:
return False
left_head = left_head.next
right_head = right_head.next
return True
class Solution:
def reverse_linked_list(self, head: ListNode) -> ListNode:
pointer = head
while pointer is not None and pointer.next is not None:
nxt = pointer.next
nxt_nxt = pointer.next.next
nxt.next = head
head = nxt
pointer.next = nxt_nxt
return head
def isPalindrome(self, head: ListNode) -> bool:
""" https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/ """
# 找到前半部分链表的尾节点。
dummpy_node = ListNode(None)
dummpy_node.next = head
slow_pointer = dummpy_node
fast_pointer = dummpy_node
while fast_pointer is not None and fast_pointer.next is not None:
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next.next
# reverse right half linked list
right_half_head = slow_pointer.next
reversed_right_half_head = self.reverse_linked_list(right_half_head)
# 判断是否回文。
right_pointer = reversed_right_half_head
left_pointer = head
while right_pointer is not None:
if left_pointer.val != right_pointer.val:
# reverse back right half linked list
slow_pointer.next = right_half_head = self.reverse_linked_list(reversed_right_half_head)
return False
right_pointer = right_pointer.next
left_pointer = left_pointer.next
# reverse back right half linked list
slow_pointer.next = right_half_head = self.reverse_linked_list(reversed_right_half_head)
return True
def isPalindrome2(self, head: ListNode) -> bool:
""" https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-by-leetcode-solution/
时间复杂度:O(n)O(n)
空间复杂度:O(n)O(n)
"""
lst = []
while head is not None:
lst.append(head.val)
head = head.next
return lst == lst[::-1]
class Solution2:
def isPalindrome(self, head: ListNode) -> bool:
""" This solution (my own) has o(1) space but o(n^2) time complexity; it timesout """
if not head:
return
counter = 0
pointer = head
while pointer:
counter += 1
pointer = pointer.next
steps = 0
while steps <= counter - 1 - steps:
# steps = 0, counter - steps - 1 = 4
pointer = head
# print(steps)
temp = steps
while temp > 0:
pointer = pointer.next
temp -= 1
val_a = pointer.val
temp = counter - steps * 2 - 1
while temp > 0:
pointer = pointer.next
temp -= 1
val_b = pointer.val
if val_a != val_b:
return False
steps += 1
return True
|
6b4eb254466310dcc279694ba6757de1ed0ebb4e | ash1215/ANPR | /Code/VehicleInfo.py | 1,145 | 3.59375 | 4 | import pandas as pd
# vehicle class
class Vehicle:
# constructor
def __init__(self, number):
self.VehicleNumber = number
self.Manufacturer = "Unknown"
self.Owner = "Unknown"
self.Model = "Unknown"
def setManufacturer(self, companyName):
self.Manufacturer = companyName
def setOwner(self, ownderName):
self.Owner = ownderName
def setModel(self, modelName):
self.Model = modelName
def getManufacturer(self):
return self.Manufacturer
def getOwner(self):
return self.Owner
def getModel(self):
return self.Model
def getVehicleNumber(self):
return self.VehicleNumber
# end constructor
# end class
def GetVehicle(vehicleNumber):
# reading csv file
df = pd.read_csv("VehicleDetails.csv")
vehicle = Vehicle(vehicleNumber)
for i in range(len(df)):
if df["Vehicle Number"][i] == vehicleNumber:
vehicle.setManufacturer(df["Manufacturer"][i])
vehicle.setModel(df["Model"][i])
vehicle.setOwner(df["Owner"][i])
return vehicle
return vehicle
|
3cd10ed2ed1362b321e7680a619001e458734d9c | erichrathkamp/BusProblem | /NP Files/output_combiner.py | 1,469 | 3.5 | 4 | import os
import pickle
import sys
class InputError(Exception):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, message):
self.message = message
def main():
arguments = sys.argv[1:]
if(len(arguments) <= 1):
raise Exception("should pass at least 2 outputs")
print("Starting combiner")
output_paths = []
for arg in arguments:
output_paths.append(arg)
outputs = []
for output_path in output_paths:
#print(output_path)
with open(str(output_path), 'rb') as handle:
handle.seek(0)
output = pickle.load(handle)
outputs.append(output)
outputs_length = len(list(outputs[0].keys()))
if not all([len(list(output.keys())) == outputs_length for output in outputs]):
raise ValueError("Some output files are incomplete")
combined = {}
print("Comparing solutions from all files")
for key in outputs[0].keys():
solutions = [output[key] for output in outputs]
best_solution = max(solutions, key = lambda x: x[0])
combined[key] = best_solution
print("Writing best outputs to combinedPartitions.pkl")
with open('combinedPartitions.pkl', 'wb') as handle:
pickle.dump(combined, handle, protocol=pickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
main() |
fc2b63ec948254d4c66e08ac634cd12e93da7432 | Joost-Robat/PythonAchievements | /test2.py | 175 | 3.734375 | 4 | #A = input("Wat wil je bij elkaar optellen?\n")
#print(A.format)
#B = input("+\n")
#print(A, "+\n")
#A += B
#print("Het antwoord is:", A)
x = 100
y = 100
x += y
print(x) |
c7739593536ff819851c58af470968eb4bec5ad5 | mcsquared2/peopleSorting | /quickSort.py | 2,154 | 4.15625 | 4 | import random
from debug import *
def quickSort(lst):
# call the recursive quicksort function passing in the the first and last indecies in the list
quickSortR(lst,0,len(lst))
def quickSortR(lst, startIndex, stopIndex):
# if you are only looking at one item in the list, return
if stopIndex-startIndex <= 0:
return
# swap first and middle items in range to keep time to 0(n*Ln(n))
midpoint = (startIndex + stopIndex) // 2
# print("start:, ", startIndex, " end: ", stopIndex)
# print ("midpoint: ", midpoint)
lst[startIndex], lst[midpoint] = lst[midpoint], lst[startIndex]
# start the swap point as the index after the start index
swappoint = startIndex + 1
for i in range(swappoint, stopIndex):
# if current item is less than item at startIndex,
# then swap it with the item at swappoint's location
# and increment swappoint
# else, continue
if lst[i] < lst[startIndex]:
lst[swappoint], lst[i] = lst[i], lst[swappoint]
swappoint += 1
# since swappoint is now the first location where the item
# is greater than or equal to the item at the startIndex, swap
# the item at startIndex and the one at swappoint -1
sortedPoint = swappoint - 1
lst[startIndex], lst[sortedPoint] = lst[sortedPoint], lst[startIndex]
# call quicksort on the indecies left of sortedPoint and the indecies to the right of sortedPoint
quickSortR(lst, startIndex, sortedPoint)
quickSortR(lst, sortedPoint + 1, stopIndex)
if __name__ == "__main__":
j = 8
while j < 20:
lst =[]
length = j
for k in range(length):
lst.append(random.randint(0,length-1))
cpy = lst[:]
Debug("unshuffled lst: " + str(lst))
# for i in range(len(lst)):
# r = random.randint(0,len(lst)-1)
# lst[i], lst[r] = lst[r], lst[i]
Debug("unshuffled lst: " + str(lst))
quickSort(lst)
print ("my sort: ", lst)
print ("pythons sort: ", sorted(lst))
if (lst != sorted(lst)):
print("Quicksort didn't work!!")
print ("my sort: ", lst)
print ("pythons sort: ", sorted(lst))
print()
print()
else:
pass
# print (j, ": success!\n\n")
j*=2
|
7573f70f8e0b0145a5f7fce60baa63654751a4df | FireAmpersand/231PythonProjects | /doublesum.py | 230 | 4.03125 | 4 | a = int(input("Enter a number: "))
b = int(input("Enter a second number: "))
if a==b:
sum = 2 * (a+b)
print("The numbers Are the same so here is 2 * the sum: " + str(sum))
else:
sum = a + b
print("The sum is: " + str(sum))
|
33c75df14e8e5469608b04c64dacc77e1a7a8eaa | Hellofafar/Leetcode | /Medium/368.py | 1,879 | 3.921875 | 4 | # ------------------------------
# 368. Largest Divisible Subset
#
# Description:
# Given a set of distinct positive integers, find the largest subset such that every pair
# (Si, Sj) of elements in this subset satisfies:
#
# Si % Sj = 0 or Sj % Si = 0.
#
# If there are multiple solutions, return any subset is fine.
#
# Example 1:
# Input: [1,2,3]
# Output: [1,2] (of course, [1,3] will also be ok)
#
# Example 2:
# Input: [1,2,4,8]
# Output: [1,2,4,8]
#
# Version: 1.0
# 09/28/19 by Jianfa
# ------------------------------
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
n = len(nums)
count = [1 for _ in range(n)] # size of largest subset in which ith number is largest number
pre = [-1 for _ in range(n)] # index of largest divisor of ith number in the subset
nums.sort()
maxSize = 0
index = -1
for i in range(n):
for j in range(i)[::-1]:
if nums[i] % nums[j] == 0: # Check if it's a divisor
if count[j] + 1 > count[i]:
count[i] = count[j] + 1
pre[i] = j # record the index of divisor
if count[i] > maxSize:
maxSize = count[i]
index = i
ret = []
while index != -1:
ret.append(nums[index])
index = pre[index]
return ret
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from: https://leetcode.com/problems/largest-divisible-subset/discuss/84006/Classic-DP-solution-similar-to-LIS-O(n2)
# Main idea is dp solution, from smaller number, build the subset containing the number and count the size of subset.
# Traverse all the number less than it and check if it's divisor. |
9869dfb4a98bfbc7fde79ef045dc21c0fae75738 | mandonuno/phonebook-widget | /frontend.py | 5,427 | 3.953125 | 4 | """
A program that creates a Desktop Application widget
that stores contact information inside database
"""
import tkinter as tk
from backend import Database
database = Database("contacts.db")
class Window:
"""Window class that creates the PhoneBook Widget, formats the display
and calls the instance methods when buttons are clicked
"""
def __init__(self, window):
"""Initializer / Instance Attributes"""
self.window = window
self.window.wm_title("PhoneBook Widget")
first = tk.Label(window, text="First")
first.grid(row=0, column=0)
last = tk.Label(window, text="Last")
last.grid(row=0, column=2)
cell = tk.Label(window, text="Cell")
cell.grid(row=1, column=0)
email = tk.Label(window, text="Email")
email.grid(row=1, column=2)
self.first_text = tk.StringVar()
self.first_entry = tk.Entry(window, textvariable=self.first_text)
self.first_entry.grid(row=0, column=1)
self.last_text = tk.StringVar()
self.last_entry = tk.Entry(window, textvariable=self.last_text)
self.last_entry.grid(row=0, column=3)
self.cell_text = tk.StringVar()
self.cell_entry = tk.Entry(window, textvariable=self.cell_text)
self.cell_entry.grid(row=1, column=1)
self.email_text = tk.StringVar()
self.email_entry = tk.Entry(window, textvariable=self.email_text)
self.email_entry.grid(row=1, column=3)
self.list_box = tk.Listbox(window, height=6, width=40)
self.list_box.grid(row=2, column=0, rowspan=6, columnspan=2)
scroll = tk.Scrollbar(window)
scroll.grid(row=2, column=2, rowspan=10)
self.list_box.configure(yscrollcommand=scroll.set)
scroll.configure(command=self.list_box.yview)
self.list_box.bind('<<ListboxSelect>>', self.get_selected_row)
view_button = tk.Button(window,
text="View all",
width=12,
comman=self.view_command)
view_button.grid(row=2, column=3)
search_button = tk.Button(window,
text="Search",
width=12,
command=self.search_command)
search_button.grid(row=3, column=3)
add_button = tk.Button(window,
text="Add",
width=12,
command=self.add_command)
add_button.grid(row=4, column=3)
update_button = tk.Button(window,
text="Update",
width=12,
command=self.update_command)
update_button.grid(row=5, column=3)
delete_button = tk.Button(window,
text="Delete",
width=12,
command=self.delete_command)
delete_button.grid(row=6, column=3)
close_button = tk.Button(window,
text="Close",
width=12,
command=window.destroy)
close_button.grid(row=7, column=3)
def view_command(self):
self.list_box.delete(0, tk.END)
for row in database.view():
self.list_box.insert(tk.END, row)
def search_command(self):
self.list_box.delete(0, tk.END)
for row in database.search(self.first_text.get(),
self.last_text.get(),
self.cell_text.get(),
self.email_text.get()):
self.list_box.insert(tk.END, row)
def add_command(self):
database.insert(self.first_text.get(),
self.last_text.get(),
self.cell_text.get(),
self.email_text.get())
self.list_box.delete(0, tk.END)
self.list_box.insert(tk.END, (self.first_text.get(),
self.last_text.get(),
self.cell_text.get(),
self.email_text.get()))
def update_command(self):
database.update(self.selected_row[0],
self.first_text.get(),
self.last_text.get(),
self.cell_text.get(),
self.email_text.get())
def delete_command(self):
database.delete(self.selected_row[0])
def get_selected_row(self, event):
"""Get list of items from FIRST to LAST and prints seleted row"""
try:
index = self.list_box.curselection()[0]
self.selected_row = self.list_box.get(index)
self.first_entry.delete(0, tk.END)
self.first_entry.insert(tk.END, self.selected_row[1])
self.last_entry.delete(0, tk.END)
self.last_entry.insert(tk.END, self.selected_row[2])
self.cell_entry.delete(0, tk.END)
self.cell_entry.insert(tk.END, self.selected_row[3])
self.email_entry.delete(0, tk.END)
self.email_entry.insert(tk.END, self.selected_row[4])
except IndexError:
pass
window = tk.Tk()
Window(window)
window.mainloop()
|
4a1523769eb5231e2ca84a56f739682ec2266fa5 | kurumiwj/PAT-Advanced-Python | /1136.py | 549 | 3.8125 | 4 | def isPalindromic(s,start,end):
while start<=end:
if s[start]!=s[end]:
return False
start+=1
end-=1
return True
n=input()
cnt=0
flag=True
while not isPalindromic(n,0,len(n)-1):
cnt+=1
n=list(n)
n_reverse=reversed(n)
num1=int(''.join(n))
num2=int(''.join(n_reverse))
n=str(num1+num2)
print(num1,'+',num2,'=',n)
if cnt==10:
flag=False
print("Not found in 10 iterations.")
break
if flag:
print(n,"is a palindromic number.") |
93813a8e5c6a2551fdebf2804b5232045f5529e7 | AnupSrujan/git-github | /sort.py | 599 | 3.859375 | 4 | ex_array = [1,2,4,9,14,81,100]
integer = 5
def insertion_integer(ex_array, integer):
array = []
if integer < ex_array[0]:
array.append(integer)
array += ex_array
elif integer > ex_array[-1]:
array += ex_array
array.append(integer)
else:
for i in range(len(ex_array)):
array.append(ex_array[i])
if integer < ex_array[i+1] and integer > ex_array[i]:
array.append(integer)
array += (ex_array[i+1:])
break
return array
print(insertion_integer(ex_array, integer))
|
090030a7fdb2498e2355a6c8088b0325ed15f850 | juanfdg/JuanFreireCES22 | /Aula3/Problem14_11_1_a.py | 577 | 4.125 | 4 | def merge(xs, ys):
""" merge common elements of sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
# If one of the lists is finished, merge is over
if xi >= len(xs) or yi >= len(ys):
return result
# Both lists still have items, copy smaller item to result.
if xs[xi] < ys[yi]:
xi += 1
elif xs[xi] > ys[yi]:
yi += 1
else:
result.append(xs[xi])
xi += 1
yi += 1
print(merge([1,2,5,7], [1,3,5,6]))
|
f6841b23defb2b28da299d3a3a1f8f0422a6e1ef | tinkle1129/Leetcode_Solution | /Greedy/435. Non-overlapping Intervals.py | 1,619 | 4.21875 | 4 | # - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Non-overlapping Intervals.py
# Creation Time: 2017/10/12
###########################################
'''
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
'''
import sys
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
if intervals == []:
return 0
minint = sys.maxint
intervals = sorted(intervals,key=lambda x:x.start)
cnt = 0
for e in intervals:
if minint>e.start:
cnt +=1
minint = min(minint,e.end)
else:
minint = e.end
return cnt-1 |
b3e2f8494a038a8dc9d77f480bbd7416bd6e4c9b | sammitjain/GUI_python | /Tkinter3.py | 336 | 4.0625 | 4 | # Part 3: Basics with Tkinter GUI in Python
# Working with Labels and organizing them
from tkinter import *
root = Tk()
l1 = Label(root,text='L1',bg='red',fg='white')
l1.pack()
l2 = Label(root,text='L2',bg='green',fg='black')
l2.pack(fill=X)
l3 = Label(root,text='L3',bg='white',fg='blue')
l3.pack(side=LEFT,fill=Y)
root.mainloop()
|
5fa8e392ba492595db568221c6f5573f312742ac | asdrewq123/learning | /hungry.py | 326 | 4.09375 | 4 | hungry=input("are you hugry")
if hungry=="yes":
print("eat samosa")
print("eat pizza")
print("burger")
print("fries")
else:
<<<<<<< HEAD
print("do your homework")
=======
thirsty=input("are you thirsty")
if thirsty=="yes":
print("drink water")
print("or drik soda")
>>>>>>> thirsty
|
24dae625ac9031a8e56138dc510ad132febccfc1 | VadimSadriev/PythonLearning | /Webapp/files.py | 1,068 | 4.25 | 4 |
# 'r' = opens file for reading, also 'r' is default value so u allowed not to pass it
# 'r' doesnt create file with given name if not exists, other modes create if file with given name dont exist
# 'w' open file for writing, if file have data then data is deleted
# 'a' opens file to append data, does not delete existing data.
# 'x' open new file for writing, Error in case file with given name already exists
# by default interpretator awaits text data(for example asci or utf-8)
# in case file have images, videos or something not text we have to say open file as a binary
# by appending 'b' to any mode. ('ab', 'wb' etc)
# by adding something like 'x+b' or 'a+b', 'r+a' in file mode u say that u want to read and write into file
# or write into binary file
todos = open('todos.txt', 'a')
print('feed the cat', file=todos)
print('kappa', file = todos)
todos.close()
tasks = open('todos.txt')
for chore in tasks:
#print(chore)
print(chore, end='')
tasks.close()
with open('todos.txt') as tasks:
for chore in tasks:
print(chore, end='')
|
49d22768a25992e2608ca9378587f85d9756754e | liuxiang0/turtle_tutorial | /Lesson-6 Speed Change.py | 1,195 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Lesson 6 : 给定速度画螺线图
"""
import turtle
wn = turtle.Screen()
monkey = turtle.Pen() # 初始化乌龟程序,调出图形框,准备好画笔
'''
monkey.shape("turtle") # 改变画笔形状为一只乌龟,缺省是箭头arrow,
# 还可以为 'circle'-圆, 'square'-正方形, 'triangle'-三角形, 'classic'.
wn.bgcolor("red") # lightgreen
monkey.pensize(3) # 改变画笔线宽度
monkey.color("yellow") # 改变画笔颜色,还有green,blue,black,white,pink,...,或者(r,g,b)
#monkey.speed(5) # 0,或者1~10, 1最慢slowest,10最快fastest
for i in range(5):
monkey.speed(2*i) # 画的速度变化
monkey.stamp() # 留痕迹
monkey.fd(200)
monkey.lt(144) # 五角星的内角为36°
'''
wn.bgcolor('orange')
monkey.color("white") # 改变画笔颜色
monkey.speed(7)
monkey.pensize(1)
# 画类似螺线或蜘蛛网
monkey.shape('triangle')
for size in range(5, 173, 2): # start with size = 5 and grow by 2
monkey.stamp() # leave an impression on the canvas
monkey.forward(size) # move turtle along
monkey.right(24) # and turn her
wn.exitonclick() # 鼠标点击就退出 |
1e42186eaee5b3c7c64e38bea9896114fe4b6712 | tomviner/raspy-lego | /car.py | 1,897 | 3.625 | 4 | import time
import contextlib
from pin import Pin, ExclusivePin
from utils import sleep
class Car(object):
"""
Control of our lego buggy via left, right and gas pins
"""
def __init__(self):
self.left = ExclusivePin(17, None)
self.right = ExclusivePin(14, self.left)
self.gas = Pin(0)
self.left.xpin = self.left
def turn(self, s, is_left, angle=0.05):
first = self.left if is_left else self.right
second = self.right if is_left else self.left
first.drive(angle)
end = time.time() + s
while time.time() < end:
sleep(0.25)
first.drive(angle/10)
second.drive(angle)
def turn_left(self, s):
self.turn(s, True)
def turn_right(self, s):
self.turn(s, False)
def rev(self, s=0.4):
self.gas.drive(s)
def start(self, wait=None):
self.gas.on()
if wait:
sleep(wait)
def pause(self, s):
self.stop()
sleep(s)
self.start()
def stop(self):
self.gas.off()
def all_stop(self):
self.stop()
self.left.off()
self.right.off()
@contextlib.contextmanager
def safe_car():
"""
Make sure the car (ie code) doesn't crash with the
accelerator (or steering) stuck on
"""
car = Car()
try:
yield car
finally:
car.all_stop()
def loop():
"""
Do a little loop round the table
"""
with safe_car() as car:
car.start(0.2)
car.pause(1)
car.turn_right(2.75)
car.pause(1)
car.start(0.3)
def wiggle(s=0.1):
"""
Drive across the table with a little wiggle in yo ass
"""
with safe_car() as car:
car.start(s)
car.turn_left(s)
sleep(s)
car.turn_right(s)
sleep(s)
loop()
|
f048b50b6474b03be18b6559c753badd081f6cfd | JoshFlack/Tees | /Week_1/wk1 pt2 q1.py | 321 | 4.0625 | 4 | #josh flack 8/7/2020
#which is bigger
#collect to numbers form user
x = int, input("enter first number: ")
y = int, input("enter second number:")
#compare/else if statements
if x > y:
print (x, "is bigger than", y)
elif y > x:
print (y, "is bigger than", x)
else:
print ("both are equil")
|
54427709cfa28ab3ddeb9daf9e02dbcab99612b3 | aciorra83/CCBC_Python | /python_practice/Lesson9_Error_Handling.py/How_to_Raise_Exceptions.py | 1,101 | 4.25 | 4 | # as a programmer you can raise errors with the 'raise' keyword
def raise_an_error(error):
raise error
raise_an_error(ValueError)
# import error
import nonexistentmodule
# key error
person = {
'name': 'Rich Brown',
'age': 56
}
print(person["gender"]) # a non-existent key in our dictionary
# type error: occurs if you attemot an operation on a value or object of the incorrect type
# example 1: adding a string to an int:
'string' + 10
# type errors happen when passing wrong args as well:
a = 6
for index, value in enumerate(a):
print(value) # 'int' object is not iterable, resulting in a type error
# attribute error: rasieed when assigning or referencing an attribute fails:
a = [1,2,3]
a.push(4)
# index error: raised when attempting to access an index in a list that doesn't exist
a = [1,2,3]
print(a[5])
# name error: raised when a specified name can't be found locally or globally
print(age)
# filenotfounderror: raised when attempting to read or write and the file is not found:
with open('input.txt', 'r') as myinputfile:
for line in myinputfile:
print(line) |
90c78a28c6aa2afa3a0389141528408d0cc9acda | SoniaChevli/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py~ | 1,501 | 3.609375 | 4 | #!/usr/bin/python3
from models.rectangle import Rectangle
class Square(Rectangle):
""" Square Class """
def __init__(self, size, x=0, y=0, id=None):
"""
initation of square class
Args:
size (int): size of square
x (int): x number of spaces
y (int): y number of newlines before square
id (int): number identifier for square
Return:
Nothing
"""
super().__init__(size, size, x, y, id)
def __str__(self):
""" overload str method """
return '[Square] ({:d}) {:d}/{:d} - {:d}'.format(self.id, self.x, self.y, self.width)
@property
def size(self):
""" size getter"""
return self.width
@size.setter
def size(self, value):
""" size setter"""
self.width = value
self.height = value
def update(self, *args, **kwargs):
""" update the attributes
Args:
*args: list of arguments to change attributes to
**kwargs: dicyionary to keyword arguments
Return:
Nothing
"""
argnum = len(args)
if argnum != 0:
if argnum >= 1:
self.id = args[0]
if argnum >= 2:
self.__size = args[1]
if argnum >= 3:
self.__x = args[2]
if argnum >= 4:
self.__y = args[3]
else:
for key, value in kwargs.item():
setattr(self, key, value)
|
85f1635d0b5696babef6eac4cc567eebeb365c12 | kylem314/p3-web-error-project | /python/battleshipMain.py | 2,369 | 3.90625 | 4 | from random import randint
import os
#Ship Class
class Ship:
def __init__(self, size, orientation, location):
self.size = size
if orientation == 'horizontal' or orientation == 'vertical':
self.orientation = orientation
else:
raise ValueError("Value must be 'horizontal' or 'vertical'.")
if orientation == 'horizontal':
if location['row'] in range(row_size):
self.coordinates = []
for index in range(size):
if location['col'] + index in range(col_size):
self.coordinates.append({'row': location['row'], 'col': location['col'] + index})
else:
raise IndexError("Column is out of range.")
else:
raise IndexError("Row is out of range.")
elif orientation == 'vertical':
if location['col'] in range(col_size):
self.coordinates = []
for index in range(size):
if location['row'] + index in range(row_size):
self.coordinates.append({'row': location['row'] + index, 'col': location['col']})
else:
raise IndexError("Row is out of range.")
else:
raise IndexError("Column is out of range.")
if self.filled():
print_board(board)
print(" ".join(str(coords) for coords in self.coordinates))
raise IndexError("A ship already occupies that space.")
else:
self.fillBoard()
def filled(self):
for coords in self.coordinates:
if board[coords['row']][coords['col']] == 1:
return True
return False
def fillBoard(self):
for coords in self.coordinates:
board[coords['row']][coords['col']] = 1
def contains(self, location):
for coords in self.coordinates:
if coords == location:
return True
return False
def destroyed(self):
for coords in self.coordinates:
if board_display[coords['row']][coords['col']] == 'O':
return False
elif board_display[coords['row']][coords['col']] == '*':
raise RuntimeError("Board display inaccurate")
return True
|
fa6f53497e15c48a7316867d6a2c0b3b5a56dc06 | zuobing1995/tiantianguoyuan | /第一阶段/day11/day10_exercise/pow_sum.py | 282 | 3.921875 | 4 | # 2. 给出一个数n,写一个函数计算:
# 1 + 2**2 + 3**3 + 4**4 + .... n**n的和
def f(n):
# 方法2
return sum(map(lambda x: x ** x, range(1, n + 1)))
# 方法1
# s = 0
# for i in range(1, n + 1):
# s += i ** i
# return s
print(f(3))
|
56b7bd9ef1c9e09f93d083377c5a1b4255d4221a | Vivi-yd/Python-Codes | /Intro_CS_MIT/problem_set_1/problem_set_1.py | 2,036 | 4.40625 | 4 | # Problem Set 1 [Paying off Credit Card Debt] from MIT Intro to CS 6.00
# Name:Vivian D
# Time Spent: 45 mins
#Problem 1, Paying the Minimum
"""
Use raw_input() to ask for the following three floating point numbers:
1.
the outstanding balance on the credit card
2.
annual interest rate
3.
minimum monthly payment rate
For each month, print the minimum monthly payment, remaining balance,
principle paid in the format shown in the test cases below.
All numbers should be rounded to the nearest penny. Finally, print the result,
which should include the total amount paid that year and the remaining balance.
format:
Enter the outstanding balance on your credit card: 4800
Enter the annual credit card interest rate as a decimal: .2
Enter the minimum monthly payment rate as a decimal: .02
Month: 1
Minimum monthly payment: $96.0
Principle paid: $16.0
Remaining balance: $4784.0
Month: 2
Minimum monthly payment: $95.68
Principle paid: $15.95
Remaining balance: $4768.05
"""
# Taking inputs from users
balance = float(raw_input("Please enter the outstanding balance on your credit card: "))
annual_int_rate = float(raw_input("Please enter the annual credit card interest rate as a decimal: "))
min_pay_rate = float(raw_input("Please enter the minimum monthly payment rate as a decimal: "))
# defining initial value
month = 0
tot_paid = 0
# computation of the payments for a calendar year
for itr in range(1, 13):
month += 1
min_payment = min_pay_rate * balance
interest_paid = (annual_int_rate/12.0 * balance)
principle_paid = min_payment - interest_paid
balance -= principle_paid
tot_paid += principle_paid + interest_paid
print "Month: " + str(month)
print "mininum monthly payment: " + "$" + str(round(min_payment, 2))
print "Principle paid: " + "$" + str(round(principle_paid, 2))
print "Your remaining balance: " + "$" + str(round(balance, 2))
print "RESULT: "
print "Total Amount Paid: " + "$" + str(round(tot_paid, 2))
print "Your Remaining Balance: " + "$" + str(round(balance, 2))
|
2433fe4f8c6fedfbc7a7c2798d1ae6e63da76ddf | kotsky/programming-exercises | /Math/Numbers Of Length N And Value Less Than K.py | 1,359 | 3.84375 | 4 | '''
Given a set of digits (A) in sorted order, find how many numbers of length B are possible whose value is less than number C.
NOTE: All numbers can only have digits from the given set.
Examples:
Input:
0 1 5
1
2
Output:
2 (0 and 1 are possible)
Input:
0 1 2 5
2
21
Output:
5 (10, 11, 12, 15, 20 are possible)
Constraints:
1 <= B <= 9, 0 <= C <= 1e9 & 0 <= A[i] <= 9
'''
class Solution:
def count(self, A, B, b, i):
if i >= len(b) or B==0:
return 1
c_max = int(b[i])
rt = 0
for x in A:
if i == 0 and x ==0 and B!=1:
continue
if x > c_max:
continue
if x == c_max:
if i >= len(b) -1:
continue
rt = rt + self.count(A, B-1, b, i+1)
else:
rt = rt + len(A)**(B-1)
return rt
def solve(self, A, B, C):
c = str(C)
if len(c) < B:
return 0
ind = 0
if len(c) == B:
return self.count(A, B, c, 0)
rt = 0
for x in A:
if x == 0 and B!=1:
continue
if x==0 and x < C:
rt +=1
else:
rt = rt + len(A)**(B-1)
return rt
|
4aff92d60d79203a62c26cd19be53d552cb1551e | gabempayne/file-folder-organizer | /testmkdirv2.py | 1,272 | 4.0625 | 4 | # this program asks which type of files you will be moving #
# it then checks if a directory with that respective name exists #
# if directory does not exist, it then creates said directory #
# and moves all files of that type to that directory #
import os
from os import listdir
from os.path import isfile, join
import shutil
mypath = os.path.join(os.path.expanduser('~'), 'Desktop') # you can substitute 'Desktop' with whatever folder files are in after user folder
new_path = input('Hello, please choose extension type to \nmove (py, exe, jpg, png, zip, etc.):')
# check for file path
if os.path.exists(new_path):
# creates variable from all files from path's directory
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for files in onlyfiles:
if files.endswith(new_path):
print('These files were moved: ', files)
shutil.move(files, new_path)
# creates directory and moves files
else:
os.mkdir(mypath + '\\' + new_path)
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for files in onlyfiles:
if files.endswith(new_path):
print('These files were moved: ', files)
shutil.move(files, new_path)
|
e469a4d428f14279bdba1874876582b420a5e137 | AnanduR32/PythonProgrammingBasics | /union of lists.py | 623 | 3.796875 | 4 | list1,list2,dup=[],[],[]
Nlist1=int(input("Enter the total number of items in list 1"))
Nlist2=int(input("Enter the total number of items in list 2"))
print("Enter the elements of list 1")
for i in range(0,Nlist1):
item=input()
list1.append(item)
print("Enter the elements of list 2")
for i in range(0,Nlist2):
item=input()
list2.append(item)
for i in range(0,len(list1)):
key=list1[i]
for j in range(0,len(list2)):
value=list2[j]
if(key==value):
dup.append(list2[j])
for i in range(0,len(dup)):
list1.remove(dup[i])
print(list1+list2)
input()
|
a4b7009ca7fe2924e915fed84979af08bd52529e | Emanuelvss13/ifpi-ads-algoritimos2020 | /fabio_2a/Q5_Fa_ordem_crescente.py | 779 | 3.984375 | 4 | def main():
n1 = int(input('Digite o 1º número: '))
n2 = int(input('Digite o 2º número: '))
n3 = int(input('Digite o 3º número: '))
resultado = crescente(n1, n2, n3)
print(resultado)
def crescente(n1, n2, n3):
if n1 < n2 < n3:
return f'A ordem crescente é {n1}, {n2}, {n3}.'
elif n1 < n3 < n2:
return f'A ordem crescente é {n1}, {n3}, {n2}.'
elif n2 < n1 < n3:
return f'A ordem crescente é {n2}, {n1}, {n3}.'
elif n2 < n3 < n1:
return f'A ordem crescente é {n2}, {n3}, {n1}.'
elif n3 < n1 < n2:
return f'A ordem crescente é {n3}, {n1}, {n2}.'
else:
return f'A ordem crescente é {n3}, {n2}, {n1}.'
main()
|
9a95d95b90b7986be0fd2b1880f83f91bbb69aa1 | clui951/cs168_student | /projects/proj1_chat/basic_client.py | 710 | 3.71875 | 4 | import socket
import sys
from utils import *
ip_arg = sys.argv[1]
port_arg = sys.argv[2]
client_socket = socket.socket()
client_socket.connect((ip_arg, int(port_arg)))
data = raw_input('--> ')
client_socket.send(data)
client_socket.close()
class BasicClient(object):
def __init__(self, address, port):
self.address = address
self.port = int(port)
self.socket = socket.socket()
def send(self, message):
self.socket.connect((self.address, self.port))
self.socket.send(message)
args = sys.argv
if len(args) != 3:
print "Please supply a server address and port."
sys.exit()
client = BasicClient(args[1], args[2])
msg = raw_input()
client.send(msg)
|
a59ac6a3e8ce06b5e42f7625adf8e7f730111300 | ConnorMattson/Misc-Scripts-and-Challenge-Solutions | /challengeSolutions/NZPC/2010/nzpc2010h.py | 664 | 3.625 | 4 | # Problem H 2010 - Connor Mattson
n = int(input("Enter the number of pairs: "))
scenario = 1
while n != 0:
people = []
groups = []
for i in range(n):
pair = input("Enter pair {}: ".format(i+1)).split(' ')
people.extend([person for person in pair if person not in people])
groups.append(pair)
for person in people:
first = None
for group in [group for group in groups]:
if person in group:
if first:
first.extend([person for person in group if person not in first])
groups.remove(group)
else: first = group
print("Scenario {} has {} loops.".format(scenario, len(groups)))
n = int(input("Enter the number of pairs: "))
scenario += 1 |
cbe5f99c9a95a4e3c2ed8ef05b7fbfff8a52380a | Yuhsuant1994/leetcode_history | /solutions/1_linkedlist.py | 2,252 | 3.5625 | 4 | class ListNode(object):
def __init__(self, val=0, next=None):
self.val=val
self.next=next
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
level, current_max=0,0
check_later=list()
if root:
level+=1 #if it's not an empty tree
else:
return level
#if (not root.left) & (not root.right) then stop
#level==1 meaning only the first entrence
#len(check_later)>0 meaning the loop to check is there
if (not root.left) & ( not root.right ): return level #level 1
while (len(check_later)>0)|(level==1):
if level!=1: #check loop
check_ref=check_later.pop()
level=check_ref[0]
root=check_ref[1]
while (root.left is not None) | (root.right is not None):
level+=1
if not root.left:
root=root.right
elif not root.right:
root=root.left
else:
check_later+=[[level,root.right]]
root=root.left
if level>current_max: current_max=level
return current_max
p5=ListNode(5)
p4=ListNode(4,p5)
p21=ListNode(2,p4)
p22=ListNode(2,p4)
headB=ListNode(1,p21)
headA=ListNode(1,p22)
#head
# Second thought: store value
if not headA or not headB:
print( None)
# Second thought: store value
listA, listB, inter = list(), list(), list()
pointA, pointB = headA, headB
i = 1
while pointA:
listA = listA + [pointA.val]
pointA = pointA.next
while pointB:
listB = listB + [pointB.val]
pointB = pointB.next
while i < min(len(listA), len(listB)):
if listA[-i:] == listB[-i:]:
i = i + 1
else:
i = i - 1
break
if i == 0:
print( None)
skipA = len(listA) - i
skipB = len(listB) - i
pointA, pointB = headA, headB
for s in range(skipA):
pointA = pointA.next
for s in range(skipB):
pointB = pointB.next
while pointA and pointB:
if pointA == pointB:
print( pointA)
else:
pointA = pointA.next
pointB = pointB.next
print( None) |
397d1bb2766ce470ca59c9e131a151ddbdb17099 | anjaligr05/TechInterviews | /review/trees/inOSucc.py | 635 | 3.53125 | 4 | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inOSucc(root, node):
if root==None:
return
print 'root = ', root.val, 'node = ', node.val
if node.right != None:
mn = node.right
while mn:
mnv = mn.val
mn = mn.left
return mnv
else:
succ = None
while root:
if root.val<=node.val:
root = root.right
else:
succ = root.val
root = root.left
return succ
print 'succ = ', succ
root = TreeNode(8)
root.left = TreeNode(6)
root.left.right = TreeNode(7)
root.left.left = TreeNode(5)
root.right = TreeNode(20)
print inOSucc(root, root.left.right)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.