blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
4918d7b880824b5d9f8d99eb20b6b94124f3bb82 | Barbariansyah/pyjudge | /test/segiempat/segiempat_7.py | 438 | 3.53125 | 4 | def segiempat_7(n):
ret = ''
c1 = '*'
c2 = '#'
if (n==1):
ret = c1
elif (n==2):
ret = c1+c1+c1+c1
elif (n>2):
for i in range(n):
ret += c1
ret += '\n'
for j in range(n-2):
ret += c1
for k in range(n-2):
ret += c2
ret += c1
ret += '\n'
for i in range(n):
ret += c1
return ret |
129f133b4d7c7ac05c0dfd37a020fafe203a5f4b | An-ling-TS/LeetCode | /字符串中的单词数.py | 665 | 3.875 | 4 | '''
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
'''
import re
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
if __name__=='__main__':
so=Solution()
print(so.countSegments("Hello, my name is John"))
print(so.countSegments(""))
print(so.countSegments(" "))
|
7738d85187b631563aa1801185850aeca18c86b6 | liu1002324991/- | /2048.py | 5,514 | 3.703125 | 4 | import random
class Game:
def __init__(self):
self.board_list = [
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
]
self.score = 0
#判断空位 坐标 行列
self.board_empty = []
def start(self):
self.restart()
while True:
self.print_board()
code = input('请输入指令>>>>')
if code == 'w':
self.move_up()
elif code == 'a':
self.move_left()
elif code == 's':
self.move_down()
elif code == 'd':
self.move_right()
elif code == 'r':
self.restart()
continue
elif code == 'q':
exit('退出')
else :
print('你的输入有误,请重新输入')
continue
if self.is_win():
# 判断游戏是否win
print('you win')
break
if self.gameOver():
# 判断是否game over
print('geme over')
break
self.add_piece()
# 在空白地方随机添加2或者4
# 打印棋盘
def print_board(self):
print("""
score:{}
+-----+-----+-----+-----+
|{:^5}+{:^5}+{:^5}+{:^5}+
+-----+-----+-----+-----+
|{:^5}+{:^5}+{:^5}+{:^5}+
+-----+-----+-----+-----+
|{:^5}+{:^5}+{:^5}+{:^5}+
+-----+-----+-----+-----+
|{:^5}+{:^5}+{:^5}+{:^5}+
+-----+-----+-----+-----+
w(up), s(down), a(left), d(right)
q(quit), r(restart)
""".format(self.score, *self.board_list[0],
*self.board_list[1],
*self.board_list[2],
*self.board_list[3]))
def is_win(self):
# 判断游戏是否win
#判断空位
self.board_empty = []
for i in range(len(self.board_list)):
for j in range(len(self.board_list[i])):
if self.board_list[i][j] == 2048:
return True
if self.board_list[i][j] == '':
self.board_empty.append((i, j))
return False
def gameOver(self):
#判断游戏是否game over
if not self.board_empty:
#判断每行每列没有相邻的相等的元素
#判断每一行
for i in range(len(self.board_list)):
for j in range(len(self.board_list[i])-1):
if self.board_list[i][j] == self.board_list[i][j+1]:
return False
self.turn_right()
for i in range(len(self.board_list)):
for j in range(len(self.board_list[i])-1):
if self.board_list[i][j] == self.board_list[i][j+1]:
self.turn_left()
return False
return True
return False
def add_piece(self):
#在空白的位置添加棋子(2, 4)
#先随机位置,再随机数字
if self.board_empty:
p = self.board_empty.pop(random.randrange(len(self.board_empty)))
self.board_list[p[0]][p[1]] = random.randrange(2, 5, 2)
def restart(self):
#初始化棋盘
self.board_list = [
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
['', '', '', ''],
]
#随机两个位置
while True:
t1 = (random.randrange(len(self.board_list)), random.randrange(len(self.board_list[0])))
t2 = (random.randrange(len(self.board_list)), random.randrange(len(self.board_list[0])))
if t1 != t2:
break
#随机两个值
self.board_list[t1[0]][t1[1]] = random.randrange(2, 5, 2)
self.board_list[t2[0]][t2[1]] = random.randrange(2, 5, 2)
def move_up(self):
self.turn_left()
self.move_left()
self.turn_right()
def move_left(self):
for i in range(len(self.board_list)):
self.board_list[i] = self.row_left_oper(self.board_list[i])
def move_down(self):
self.turn_right()
self.move_left()
self.turn_left()
def move_right(self):
self.turn_left()
self.move_up()
self.turn_right()
def row_left_oper(self, row):
# l1 = [2, 4, 2, 4] # =>[2, 2]=>[4] =>[4,'','','']
# 先挤到一起
temp = []
for item in row:
if item != '':
temp.append(item)
new_row = []
# 合并同类项
flag = True
for i in range(len(temp)):
if flag:
if i + 1 < len(temp) and temp[i] == temp[i + 1]:
new_row.append(temp[i] * 2)
flag = False
else:
new_row.append(temp[i])
else:
flag = True
# 补齐
n = len(row)
for i in range(n - len(new_row)):
new_row.append('')
return new_row
def turn_right(self):
self.board_list = [list(x[::-1]) for x in zip(*self.board_list)]
def turn_left(self):
for i in range(3):
self.turn_right()
if __name__ == '__main__':
game = Game()
game.start()
|
7b68ddc7078535eec76ff8db3bda1760324c8bb1 | SemsYapar/Basic-HTTP-and-Message-Server | /Server.py | 4,233 | 3.515625 | 4 | #Sems Code
#Server
import socket
class TCPServer:
def __init__(self, host):
self.host = host
def start(self):
while True:
self.port =input("HTTPServer için ""80"", EchoServer için ""8888"" port numarasını girin ")
self.port = int(self.port)
#HTTP Server' a geçiş..
if self.port == 80:
httpserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
httpserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
httpserver.bind((self.host, self.port))
httpserver.listen(5)
print(f"Listening at {httpserver.getsockname()} ")
while True:
conn, addr = httpserver.accept()
print("Connected by", addr)
data = conn.recv(1024).decode("utf-8")
response = self.handle_request(data)
conn.sendall(bytes(response,"utf-8"))
conn.close()
#Basit server-client mesajlaşma serverına geçiş..
if self.port == 8888:
DISCONNECT="exit()"
tcpserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpserver.bind((self.host, self.port))
tcpserver.listen(5)
print("Listening at", tcpserver.getsockname())
while True:
conn, addr = tcpserver.accept()
print("Connected by", addr)
conn.send(bytes("""Sems Server'a Hoşgeldin! Bana istediğini yazabilirsin\n
NOT: Serverdan çıkmak için ""exit()"" yazınız..""","utf-8"))
while True:
client_msg_size = conn.recv(8).decode("utf-8")
client_msg_size = int(client_msg_size)
msg = conn.recv(client_msg_size).decode("utf-8")
print("Client message: ", msg)
if msg == DISCONNECT:
msg = conn.recv(64).decode("utf-8")
print(msg)
conn.close()
break
response =input("=>.. ")
server_resp_size = str(len(response.encode("utf-8")))
conn.send(bytes(server_resp_size,"utf-8"))
conn.send(bytes(response,"utf-8"))
else:
print("Geçersiz bir port verdiniz, nütfen tekrar deneyin..")
def handle_request(self, data):
"""Handles incoming data and returns a response.
Override this in subclass.
"""
return data
class HTTPServer(TCPServer):
def handle_request(self,data):
#HTTP başlığı ve mesajı hazırlama fonksiyonu..
headers={
"Server": "Sems Server",
"Content-Type": "text/html",
}
status_code={
"200": "OK",
"404": "Not Found",
}
response_line = self.response_line(status_code="200")
response_headers = self.response_headers()
blank_line = "\r\n"
response_body = """
<html>
<body>
<h1>Hi Man Whats Up</h1>
</body>
</html>
"""
return response_line+blank_line+response_headers+response_body
def response_line(self, status_code):
reason = self.status_code[status_code]
return f"HTTP/1.1 {status_code} {reason}"
def response_headers(self, extra_headers=None):
headers_copy = self.headers.copy()
if extra_headers:
headers_copy.update(extra_headers)
headers = ""
for h in self.headers:
headers += f"{h}: {self.headers[h]}\n"
return headers
if __name__ == '__main__':
#Bilgisiyarınız local ip adresini giriniz..
server = HTTPServer("192.168.1.34")
server.start()
|
9074a1b18336a11139a9a07e6951f5145e3caab6 | TheSundar/euler | /problem41.py | 349 | 3.5 | 4 | import math
import itertools
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in xrange(3, int(math.sqrt(n)) + 1, 2))
str='987654321'
for n in range(9,-1,-1):
c=itertools.permutations(str[len(str)-n:], n)
for i in c:
if is_prime(int("".join(i))):
print i
break
|
21f553ca47ab6a8c5ce00f4ebbe39b4f57c38d46 | sazedul-h/college-python | /chapter7_programs/line_read.py | 397 | 3.796875 | 4 | # this prgram reads and displays the contents
# of the philosophers.txt file one line at a time.
def main():
# open a file named philosophers.txt
infile = open('philosophers.txt', 'r')
# read the file's contents
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
infile.close()
print(line1)
print(line2)
print(line3)
main()
|
f9fe5bf6dbb1839d5aa32c3dab35b6549c6a5448 | Isonzo/100-day-python-challenge | /Day 2/Day 2.2 Exercise.py | 762 | 4.34375 | 4 | height = input("Please enter your height in m: ")
weight = input("Please enter your weight in kg: ")
#Code above can't be changed
calculating_bmi = float(weight) / float(height)**2
bmi = str(round(calculating_bmi, 2))
#Under weight is 18.5, normal is 18.5 to 25, Overweight is 25 to 30, Obese is more than 30
if calculating_bmi < 18.5:
print("Your BMI is " + bmi + ", I'm guessing you're mostly skin and bones.")
elif 18.5 < calculating_bmi < 25:
print("Your BMI is " + bmi + ", nothing noteworthy about you.")
elif 25 < calculating_bmi < 30:
print("Your BMI is " + bmi + ", you're either a chubster or building muscle.")
else:
print("Your BMI is " + bmi + ", if you're not a body builder, you're just a fat fuck.")
|
c19a7ebe1f7c194db64931631fe680b042052f6c | vitorpfr/cs50ai | /0-search/degrees/shortest-path-old.py | 1,360 | 4 | 4 | def shortest_path(source, target):
"""
Returns the shortest list of (movie_id, person_id) pairs
that connect the source to the target.
If no possible path, returns None.
"""
# Set goal
goal = target
# Initialize frontier to just the starting position
start = Node(state = source, parent=None, action=None)
frontier = QueueFrontier()
frontier.add(start)
# Initialize an empty explored set
explored = set()
# Keep looping until solution found
while True:
# If nothing left in frontier, then no path
if frontier.empty():
return None
# Choose a node from the frontier
node = frontier.remove()
# If node is the goal, then we have a solution
if node.state == goal:
path = []
while node.parent is not None:
path.append((node.action, node.state))
node = node.parent
path.reverse()
return path
# Mark node as explored
explored.add(node.state)
# Add neighbors to frontier
for action, state in neighbors_for_person(node.state):
if not frontier.contains_state(state) and state not in explored:
child = Node(state=state, parent=node, action=action)
frontier.add(child)
return None |
e24d6f1be4c7ae204cf800b64c15ab6185c14035 | CatmanIta/x-PlantForm-IGA | /iga/communication/httpclient.py | 2,210 | 3.5625 | 4 | """
@author: Michele Pirovano
@copyright: 2013-2015
"""
import urllib2
import urllib
class HttpClient:
"""
Handles communication through http to the web server
"""
OK = True
KO = False
def __init__(self, hostName):
self.hostName = hostName
def destroy(self):
pass
def performCommand(self, commandName, params = {}):
try:
postData = urllib.urlencode(params)
url = self.hostName + "cmd_" + commandName + ".php"
print("Posting URL: " + str(url) + " with data " + str(postData))
response = urllib2.urlopen(url,postData)
#print response.info()
response_result = response.read()
if response_result[0:2] != "OK": raise Exception("Wrong response: '" + str(response_result) + "'")
response.close()
except Exception, e:
print("EXCEPTION: " + str(e))
return self.KO
return response_result
def performCommandAndGetResponse(self, commandName, params = {}):
try:
response_result = self.performCommand(commandName,params)
if response_result == self.KO: raise Exception("Wrong response: '" + str(response_result) + "'")
tokens = self.handleResult(response_result)
return tokens
except Exception, e:
print("EXCEPTION: " + str(e))
return self.KO
def handleResult(self,result):
result_choice = result[0:2]
if result_choice == self.KO: raise Exception("Bad result obtained!")
params = result[2:len(result)] # Remove the OK
tokens = params.split("<br>") # Each token is separated by this string
del tokens[0] # First element is an empty string
return tokens
if __name__ == "__main__":
print("Start testing HttpClient")
print ("\nTEST - connection")
httpClient = HttpClient('http://localhost/plantforms/')
print ("TEST - OK")
print ("\nTEST - command")
httpClient.performCommand("selectInstances")
print ("TEST - OK")
print ("\nTEST - destroy")
httpClient.destroy()
print ("TEST - OK")
print("Finish testing HttpClient")
|
8c57665054b52c2fca65c6488d5f98feccefb4e8 | fatimasalmanmirza/arrays_practice | /pinterest-easy.py | 2,100 | 3.828125 | 4 | def longestCommonPrefix(strs):
"""Write a function to find the longest common
prefix string amongst an array of strings.
If there is no common prefix, return an empty string"""
if not strs:
return ""
min_l = min(len(S) for S in strs)
for i in range(min_l):
s = set()
for x in strs:
s.add(x[i])
if len(s) > 1:
min_l = i
break
return strs[0][:min_l]
# print(longestCommonPrefix(["flower","flow","flight"]))
# print(longestCommonPrefix(["dog","racecar","car"]))
########################################################
def subdomainVisits(cpdomains):
"""We are given a list cpdomains of count-paired
domains. We would like a list of count-paired domains,
(in the same format as the input, and in any order),
that explicitly counts the number of visits to each
subdomain."""
from collections import Counter
domain_dict = Counter()
result = []
for domain in cpdomains:
count, domain = domain.split(" ")
count = int(count)
d = domain.split(".")
for k in range(1, len(d)+1):
domain_dict[".".join(d[-k:])]+=count
for keys, values in domain_dict.items():
result.append(str(values) + " " +str(keys))
return result
# print(subdomainVisits(["9001 discuss.leetcode.com"]))
# print(subdomainVisits(["900 google.mail.com", "50 yahoo.com",
# "1 intel.mail.com", "5 wiki.org"]))
#########################################################
def split_square_digits(n):
s = 0
while n >= 1:
a = n // 10
b = n % 10
n = a
s += b*b
return s
def ishappy(n):
# """Write an algorithm to determine if a number is "happy"."""
seen = set()
while n > 1:
seen.add(n)
n = split_square_digits(n)
if n in seen:
return False
return True
#########################################################
def longest_word(words):
words.sort()
words_set = set([""])
result = ''
for word in words:
if word[:-1] in words_set:
words_set.add(word)
if len(word) > len(result):
result = word
return result
print(longest_word(["w","wo","wor","worl", "world"]))
print(longest_word(["a", "banana", "app", "appl", "ap", "apply", "apple"]))
|
21416a65f9fa6a262e34f6ff4d49f4ac82fdcc5c | 9a24f0/USTH | /AS/generator.py | 333 | 3.984375 | 4 | #!/usr/bin/env python3
group = []
i = 0
g = int(input("Enter generator: "))
base = int(input("Enter base: "))
while True:
if str(pow(g, i, base)) not in group:
group += str(pow(g, i, base))
i += 1
else:
break
# Sort for better visualization
group.sort()
print("Your cyclic group is:", group) |
bd2b4f80a6d4cc966219113f239cd6af255bbdce | yasssshhhhhh/DataStructuresAndAlgo | /arrays/minimizeTheHeight.py | 330 | 3.78125 | 4 | # def Average(lst):
# return sum(nums) / len(nums)
# nums = [2, 6, 3, 4, 7,2,10,3,2,1]
# nums.sort()
# print(nums)
# average = Average(nums)
# k = 5
# for i in range(len(nums)):
# if nums[i] < average:
# nums[i]+=k
# if nums[i] > average:
# nums[i]-=k
# if nums[i] == average:
# nums[i]-=k
|
4f183ba19e2aaaa3dff9208d9be59fb145760aad | oftensmile/thunder | /python/thunder/viz/colorize.py | 4,175 | 3.65625 | 4 | from numpy import arctan2, sqrt, pi, array, size, shape, ones, abs, dstack, clip, transpose, zeros
import colorsys
from matplotlib import colors, cm
class Colorize(object):
"""Class for turning numerical data into colors
Can operate over either points or images
Parameters
----------
totype : string, optional, default = Pastel1
The color to convert to
scale : float, optional, default = 1
How to scale amplitude during color conversion, controls brighthness
"""
def __init__(self, totype='Pastel1', scale=1):
self.totype = totype
self.scale = scale
def points(self, pts):
"""Colorize a set of points or a single points. Input must have
either one dimension (a single point) or two dimensions (a list or
array of points).
Parameters
----------
pts : array
The point or points to colorize. Must be of shape (n, c) or (c,) where
c is the dimension containing the information for colorizing.
Returns
-------
out : array
Color assignments for each point, either (n, 3) or (3,)
"""
pts = array(pts)
n = len(pts[0])
self.checkargs(n)
if pts.ndim > 2:
raise Exception("points must have 1 or 2 dimensions")
if pts.ndim == 1:
out = clip(self.get(pts), 0, 1)
else:
out = map(lambda line: clip(self.get(line), 0, 1), pts)
return out
def image(self, img):
"""Colorize an image. Input can either be a single image or a stack of images.
In either case, the first dimension must be the quantity to be used for colorizing.
Parameters
----------
img : array
The image to colorize. Must be of shape (c, x, y, z) or (c, x, y), where
c is the dimension containing the information for colorizing.
Returns
-------
out : array
Color assignments for images, either (x, y, z, 3) or (x, y, 3)
"""
d = shape(img)
self.checkargs(d[0])
if img.ndim > 4 or img.ndim < 3:
raise Exception("image data must have 3 or 4 dimensions, first is for coloring, remainder are xy(z)")
if (self.totype == 'rgb') or (self.totype == 'hsv'):
out = abs(img) * self.scale
if img.ndim == 4:
out = transpose(out, (1, 2, 3, 0))
if img.ndim == 3:
out = transpose(out, (1, 2, 0))
elif self.totype == 'polar':
theta = ((arctan2(-img[0], -img[1]) + pi/2) % (pi*2)) / (2 * pi)
rho = sqrt(img[0]**2 + img[1]**2)
if img.ndim == 4:
saturation = ones((d[1],d[2]))
out = zeros((d[1], d[2], d[3], 3))
for i in range(0, d[3]):
out[:, :, i, :] = colors.hsv_to_rgb(dstack((theta[:, :, i], saturation, self.scale*rho[:, :, i])))
if img.ndim == 3:
saturation = ones((d[1], d[2]))
out = colors.hsv_to_rgb(dstack((theta, saturation, self.scale*rho)))
else:
out = cm.get_cmap(self.totype, 256)(img[0] * self.scale)
if img.ndim == 4:
out = out[:, :, :, 0:3]
if img.ndim == 3:
out = out[:, :, 0:3]
return clip(out, 0, 1)
def get(self, line):
if (self.totype == 'rgb') or (self.totype == 'hsv'):
return abs(line) * self.scale
if self.totype == 'polar':
theta = ((arctan2(-line[0], -line[1]) + pi/2) % (pi*2)) / (2 * pi)
rho = sqrt(line[0]**2 + line[1]**2)
return colorsys.hsv_to_rgb(theta, 1, rho * self.scale)
else:
return cm.get_cmap(self.totype, 256)(line[0] * self.scale)[0:3]
def checkargs(self, n):
if (self.totype == 'rgb' or self.totype == 'hsv') and n < 3:
raise Exception("must have 3 values per record for rgb or hsv")
elif self.totype == 'polar' and n < 1:
raise Exception("must have at least 2 values per record for polar")
|
1ea7c254b61751247b8bcee26832806ac3909e6c | Guruscode/getting-started-with-python | /data-types/basics.py | 3,757 | 4.40625 | 4 |
# in python, everything is an object
a, b, c = 1, 1.0, 'Hello World!'
print( type(a), type(b), isinstance( c, str ) )
#---------------------------------------#
'''
https://medium.com/@larmalade/python-everything-is-an-object-and-some-objects-are-mutable-4f55eb2b468b
# https://stackoverflow.com/a/27460468
# https://stackoverflow.com/a/38189759
Python has mutable and immutable data types.
We can not modify the value of immutable data type.
For example, string even being a slice, can not be modified using value assignment of an index.
class immutable
int Yes
float Yes
bool Yes
tuble Yes
frozenset Yes
set No
list No
dictionary No
'''
# id() returns the unique identifier of an object
# id doesn't necessarily returns memory address of an object => https://stackoverflow.com/questions/27460234/two-variables-with-the-same-list-have-different-ids-why-is-that/27460468#27460468
a = 1
print( 'id of a', id(a) )
# in python, a variable is like a label assigned to a given value (obecj)
# for optimization, python can assign multiple labels to the same immutable data types
a, b = 1, 1
c, d = 'Hi', 'Hi'
print( "id(a) - id(b)", id(a), ' - ' , id(b) )
print( "id(c) - id(d)", id(c), ' - ' , id(d) )
# use `is` keyword, to check if object in memory represented two labels are the same
a, b = 1, 1
print( 'a is b', a is b )
# this does not work with mutable data types, python will always create new object for it
a, b = [1], [1]
print( "id(a) - id(b)", id(a), ' - ' , id(b) )
print( 'a is b', a is b )
# when it comes to storing large data, python will also create distinct object
a, b = 1000, 1000
print( "id(a) - id(b)", id(a), ' - ' , id(b) )
print( 'a is b', a is b )
# python will automatically create new value when a label points to same object in memory
a, b = 1, 1
print( "before: id(a) - id(b)", id(a), ' - ' , id(b) )
print( 'before: a is b', a is b )
b = 2
print( "after: id(a) - id(b)", id(a), ' - ' , id(b) )
print( 'after: a is b', a is b )
# python will throw error when an immutable data type is forcefully tried to change
a = 'Hello World!' # immutable # same for a tuple
print('before: id(a)', id(a))
# a[0] = 'B' # change the value
a = 'How are you?' # create new object and assign this label, recycle old value
print('after: id(a)', id(a))
# for both mutable and immutable data type, new value is created
a = b = 1 # same as a = 1 and b = a
c = d = [1]
print('before: a is b / c is d', a is b, '/', c is d)
b = 2
d = [2]
print('after: a is b / c is d', a is b, '/', c is d)
# mutable data type persist changes
a = [1,2,3]
b = a # points to the same value
b[0] = 10
print('a - b', a, b)
# a immutable data type can contain immutable data type
# hence a true immutibity is with individual element reference, not their values
a = (1, [2, 20], 3)
# a[0] = 10 # fails, trying to change the immutable data type
# a[1] = [2, 20, 200] also fails
a[1][1] = 200 # works
print('a', a)
# immutable data type is referenced
a = [2, 20]
b = (1, a, 3)
b[1][1] = 200 # works
print('b', b)
# mutable data type are copied by value
a = 2
b = (1, a, 3)
print('before: a is b[1] => ', a is b[1])
print( 'before: a, b => ', a, ',', b )
a = 3 # a points to different object now
print('after: a is b[1] => ', a is b[1])
print( 'after: a, b => ', a, ',', b )
# None in python
# None is a global singleton object in python that signifies empty object
# A variable can point to None just to say that it holds null value
# https://stackoverflow.com/questions/19473185/what-is-a-none-value
a = 1
print('before a =>', a)
a = None # this does not delete the variable
print('after a =>', a) # used for statement 'a is not None'
|
cb386aa037f21e994068e0bb508837fcf7d407b6 | hwang018/Leetcode | /339. Nested List Weight Sum/.ipynb_checkpoints/solution-checkpoint.py | 426 | 3.5 | 4 | class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def dfs(nestedList, depth):
total = 0
for element in nestedList:
if element.isInteger():
total += (element.getInteger() * depth)
else:
total += dfs(element.getList(), depth + 1)
return total
return dfs(nestedList, 1) |
512ae24981a90f8832ba58e329c0e9c2460c1cf5 | SarmenSinanian/Intro-Python-II | /src/adv.py | 3,619 | 3.96875 | 4 | from room import Room
from player import Player
# Declare all the rooms
room = {
'outside': Room("Outside Cave Entrance",
"North of you, the cave mount beckons"),
'foyer': Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),
'narrow': Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),
'treasure': Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south."""),
}
# Link rooms together
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']
print(room['outside'].n_to)
player = Player(input('What is your name?'), room['outside'])
print(f'Hello, {player.name}.\n\n{player.current_room}')
#
# Main
#
# Make a new player object that is currently in the 'outside' room.
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
# Second Iteration
# BELOW IS BASICALLY A 'CONTROLLER' AND A 'VIEW'
# FAT MODELS (AS MUCH CODE AS POSSIBLE IN THE MODEL LAYER); SKINNY CONTROLLERS (
# NOT AS MUCH IN THE CONTROLLER)
print(player.current_room)
while True:
cmd = input('->').lower() # THE STUFF TO THE LEFT IS THE 'CONTROLLER LAYER'
if cmd in ['n', 's', 'e', 'w']:
# Move to that room
player.travel(cmd) # THE STUFF TO THE LEFT IS THE 'MODEL LAYER'
elif cmd == 'q':
print('Goodbye!')
exit()
else:
print('I did not understand that command.')
# First Iteration
# while True:
# print(Player.current_room)
# cmd = input('->')
# if cmd in ['n','s','e','w']:
# # Move to that room
# print('Move' + cmd)
# if cmd == 'n':
# if player.current_room.n_to is not None:
# player.current_room = player.current_room.n_to
# else:
# print('You cannot move in that direction')
# if cmd == 'n':
# if player.current_room.s_to is not None:
# player.current_room = player.current_room.s_to
# else:
# print('You cannot move in that direction')
# if cmd == 'n':
# if player.current_room.e_to is not None:
# player.current_room = player.current_room.e_to
# else:
# print('You cannot move in that direction')
# if cmd == 'n':
# if player.current_room.w_to is not None:
# player.current_room = player.current_room.w_to
# else:
# print('You cannot move in that direction')
# elif cmd == 'q':
# exit()
# else:
# print('I did not understand that command.')
|
bb22b6adbf00fedd5940ebc60313b5aba2de0696 | tsushiy/competitive-programming-submissions | /AOJ/AOJ vol.28/aoj2881.py | 185 | 3.578125 | 4 | while True:
s = input()
if s=="#":
break
g, y, m, d = s.split()
y, m, d = int(y), int(m), int(d)
if y>=32 or (y==31 and m>=5):
g = "?"
y -= 30
print(g, y, m, d) |
5fc14c440079923decd9c052539542135ce9180e | xmhGit/exercise_python_summer_school | /python/ex2_earth.py | 1,275 | 4.15625 | 4 | import numpy as np
from sys import argv
def cal_cir(r):
cir = 2*np.pi*r*10**3
return cir
# script,r = argv
# r = float(r) # argv's method also input the type of string
# pi=3.14 # constant pi
# r=6378 # the radius of the earth's equator, unit: km\
# r = float(raw_input("Input the radius of the earth(unit:km):\n"))
# force to invert the string to float
# when using raw_input() and argv simultaneously, it also can work. But the
# second raw_input() will replace the first argv.
# c=2*pi*r*10**3 # consistence of the earth's equator
# c_p=2*np.pi*r*10**3 # another method to get pi
earth_r = float(raw_input("Input the radius of the Earth(unit:km):\n"))
earth_cir = cal_cir(earth_r)
print "The circumference of the earth's equator is %r." % earth_cir
Mar_r = float(raw_input("Input the radius of the Martian(unit:km):\n"))
Mar_cir = cal_cir(Mar_r)
print "The circumference of the Mar's equator is %r." % Mar_cir
# surface_area = 4*np.pi*r**2*10**6 # unit:m**2
# print("Earth Information:")
# print("The circumference of the earth's equator is %.1f m" % c)
# print("\tThe circumference of the earth's equator is\n\t %.3f m" % c_p)
# print("\tThe surface area of the earth is\n\t %.3f m^2" % surface_area)
# print "\n"
# print 7/4
# print 7/4.0
|
cba5f6f13b55032eb738895058b7fe9ecc994c22 | spencerdispenced/Snake | /Images/draw_image.py | 660 | 3.609375 | 4 |
""" Script to draw background images """
import pygame
def draw_background():
""" Draw image of certain color, in checkered pattern """
surface = pygame.display.set_mode((480, 480))
for y in range(0, 480):
for x in range(0, 480):
if (x + y) % 2 == 0: # every even square
r = pygame.Rect((x * 20, y * 20), (20, 20))
pygame.draw.rect(surface, (44, 190, 36), r)
else:
rr = pygame.Rect((x * 20, y * 20), (20, 20))
pygame.draw.rect(surface, (204, 185, 90), rr)
pygame.image.save(surface, "game_board2.bmp")
draw_background()
|
d6f5ea2ffb331a0746b3a8cb7669716379aeac73 | tmnik/Python_HSE | /round_rus.py | 216 | 3.5625 | 4 | #округление по русским правилам
from math import floor, ceil
n = float(input())
r = n - int(n)
a = float('{0:.1}'.format(0.5))
if r >= a:
print(ceil(n))
elif r < a:
print(floor(n))
|
70c5d6d671ead348a8dd858e4efaf87699a7efcc | HenryBalthier/Python-Learning | /Leetcode_easy/hash/242.py | 325 | 3.5625 | 4 | class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
l1 = sorted(s)
l2 = sorted(t)
return l1 == l2
if __name__ == '__main__':
s = Solution()
s2 = "anagram"
t = "nagaram"
print(s.isAnagram(s2, t)) |
33ed8bf54750f59ef0d407f682845cf2b13be458 | Sildinho/PPBA2021_AndreIacono | /ppybaAndreIacono_79.py | 975 | 4.5 | 4 | # -- coding utf-8 --
""" Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 10: OOP (Python Object-Oriented Programming) - Aula: 79 """
# 79. Criando Construtores
# classes
# utilizamos para criar objetos (instances)
# objetos sao partes dentro de uma class (instancias)
# classes sao utilizadas para agrupas dados e funções, podendo reutilizar
# class: frutas
# objects: abacate, banana, ...
# criando uma classe
class Funcionarios:
# funções
def __init__(self, nome, sobrenome, data_nascimento):
self.nome = nome
self.sobrenome = sobrenome
self.data_nascimento = data_nascimento
# criando um objeto com parametros
usuario1 = Funcionarios('Elena', 'cabral', '12/01/1999')
usuario2 = Funcionarios('Carol', 'Silva', '17/11/1996')
usuario3 = Funcionarios('André', 'Iacono', '17/11/1977')
# impressões
print(usuario1.nome)
print(usuario2.nome)
print(usuario3.sobrenome)
|
257211fd157a6ed74ceb4be2a9d7991ab346f209 | ngocdang1999/project_euler | /bai-20.py | 157 | 3.5 | 4 | a=0
b=1
for i in range (100):
if i>1:
b=b*i
print b
str1=len(str(b))
str2=str(b)
for i in range (1, str1+1):
a=a+int (str2 [i-1])
print a
|
8b5e87ff30d31335a16f84dba140e713ef9b401d | medasuryatej/infix_to_postfix | /infix_to_postfix.py | 5,448 | 3.609375 | 4 | # Need the below package for printing the output in a tabular format
try:
import sys
from prettytable import PrettyTable
except ImportError as e:
print (f"Missing Python package for {e}")
print ("pip install prettytable")
sys.exit()
__author__ = "Meda Sai Krishna Pavan Suryatej"
__contact__ = "[email protected]"
x = PrettyTable()
x.field_names = ["Symbol", "Stack", "PostFix"]
mathOperations = ["*", "/", "+", "-", "^"]
parenthesis = ["(", ")"]
OPEN_PARANTHESIS = 0
CLOSED_PARANTHESIS = 1
OPERAND = 2
OPERATION = 3
PRECEDENCE = ["^", "/", "*", "+", "-"]
PRECEDENCE = {"(" : -1, ")" : -1 , "^" : 2, "/": 1, "*": 1, "+": 0, "-": 0, "EOS": -2}
ASSOCIVITY = {"L-R": 0, "R_L": 1}
# Note Paranthesis have higher precedence than all other operations, but for code purpose
# their precedence is taken as -1
def associvity(operation):
if operation == "^":
return ASSOCIVITY["R-L"]
else:
return ASSOCIVITY["L-R"]
class Stack:
stack = []
def push(self, value):
if value is None:
# print ("Invalid Value")
return None
self.stack.append(str(value))
def pop(self):
if len(self.stack) < 1:
# print ("Stack is Empty")
return None
poppedValue = self.stack.pop()
# print (f"Popped-{poppedValue}")
return poppedValue
def size(self):
return (len(self.stack))
def print(self):
if self.size() == 0:
# print ("Empty Stack")
return None
else:
return "".join(self.stack)
def peak(self):
if self.size() is 0:
return "EOS"
return self.stack[-1]
def operation(character):
if character.isalnum():
# character in [A-z0-9]
return OPERAND
elif character in mathOperations:
# character in [+ - * / ^]
return OPERATION
elif character in parenthesis:
# character in [ (, )]
return parenthesis.index(character)
else:
# Unknow Character
return None
def uniformExpression(input_expression):
input_expression = input_expression.replace("[", "(")
input_expression = input_expression.replace("]", ")")
input_expression = input_expression.replace("{", "(")
input_expression = input_expression.replace("}", ")")
return input_expression
# input_expression = "K+L-M*N+(O^P)*W/U/V*T+Q"
input_expression = input("Enter your expression: ")
input_expression = uniformExpression(input_expression)
stack = Stack()
symbol = ""
stackvar = ""
postfix = ""
"""
Pseudo Code:
1. Parse the infix expression Left to Right once
2. if the character is
OPERAND
- add it to the POSTFIX expression
OPERATOR
- if the precedence of incoming operator is greater than top of stack Push it to stack
- if the precedence of incoming operator is equal to the top of stack and associvity is R to L push the incoming operator
to the stack
- if the precedence of incoming operator is less than or equal top of stack recursively pop stack and
add them to postfix expression untill precedence of incoming operator is greater than top of stack
LEFT PARANTHESIS
- Push it to stack
RIGHT PARANTHESIS
- recursively pop the values from stack and add to postfix expression until you encounter LEFT paranthesis
- pop left paranthesis
"""
for everyCharacter in input_expression:
symbol = everyCharacter
wtd = operation(everyCharacter)
if wtd == OPERAND:
stackvar = stack.print()
postfix += symbol
x.add_row([symbol, stackvar, postfix])
elif wtd == OPEN_PARANTHESIS:
stack.push('(')
stackvar = stack.print()
x.add_row([symbol, stackvar, postfix])
elif wtd == CLOSED_PARANTHESIS:
while stack.peak() != "(":
stackvalue = stack.pop()
if stackvalue is not None:
postfix += stackvalue
# one more pop for removing ( from stack
stack.pop()
stackvar = stack.print()
x.add_row([symbol, stackvar, postfix])
elif wtd == OPERATION:
incomingOperator = PRECEDENCE[everyCharacter]
if incomingOperator > PRECEDENCE[stack.peak()]:
stack.push(everyCharacter)
stackvar = stack.print()
x.add_row([symbol, stackvar, postfix])
continue
while PRECEDENCE[stack.peak()] >= incomingOperator:
if (PRECEDENCE[stack.peak()] == incomingOperator):
if associvity(everyCharacter):
stack.push(everyCharacter)
else:
stackValue = stack.pop()
if stackValue is not None:
postfix += stackValue
else:
stackValue = stack.pop()
if stackValue is not None:
postfix += stackValue
stack.push(everyCharacter)
stackvar = stack.print()
x.add_row([symbol, stackvar, postfix])
else:
pass
while stack.size() > 0:
stackValue = stack.pop()
if stackValue is not None:
postfix += stackValue
x.add_row([None, None, " ".join(postfix)])
print(f"Infix Expression: {input_expression}")
print(x)
print(f"Postfix Expression: {postfix}") |
2750c59ce5fc52652913b4809de3ed5e893ec779 | faroit/audiomate | /audiomate/utils/jsonfile.py | 655 | 3.984375 | 4 | """ This module contains functions for reading and writing json files. """
import json
def write_json_to_file(path, data):
"""
Writes data as json to file.
Parameters:
path (str): Path to write to
data (dict, list): Data
"""
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f)
def read_json_file(path):
"""
Reads and return the data from the json file at the given path.
Parameters:
path (str): Path to read
Returns:
dict,list: The read json as dict/list.
"""
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
return data
|
fae11c8f87362de031fb1235bd5494d9ad433005 | JayWelborn/ChooseYourOwnAdventure | /ChooseYourOwnAdventure/story_fragment/story_fragment.py | 1,771 | 3.703125 | 4 | from string import ascii_uppercase
import sys
from typing import Mapping, List
from .choice import Choice
from prompt_reader.prompt_reader import PromptReader
class StoryFragment:
"""Class to represent one fragment of a Choose Your Own Adventure Story.
StoryFragments are composed of one Prompt, and an array of Choices.
Constants:
Properties:
Methods:
"""
CHOICE_NOT_ALLOWED = "That is not one of your options. Please choose from the following:"
prompt: str = ''
choices: List[Choice] = []
pr: PromptReader = PromptReader()
def __init__(self, prompt: str, choices: List[Mapping[str, str]]):
self.prompt = prompt
self.choices = list(
map(
lambda choice : Choice(choice['prompt'], choice['next_fragment']),
choices
)
)
def play_fragment(self):
self.pr.play_message(self.prompt)
def play_choices(self):
choice_prompts = [f'{index + 1}) {choice.prompt}' for index, choice in enumerate(self.choices)];
self.pr.play_messages(choice_prompts);
def get_next_fragment_from_choices(self):
self.play_fragment()
self.play_choices()
choice = sys.maxsize
count = 0
while count < 10:
choice = int(self.get_input()) - 1
if 0 <= choice < len(self.choices):
break
self.pr.play_message(self.CHOICE_NOT_ALLOWED)
count += 1
if count >= 10:
raise IOError('User entered too many invalid choices')
return self.choices[choice].next_fragment
def get_input(self):
"""
Wrapper for getting user input to mock during tests
"""
return input().strip()
|
8f3bda04e66dfd3e6cab6ae96ab5eb22713f7a35 | GGRMR/python-study | /homework/stack_functions.py | 493 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
stack_functions
함수와 리스트를 이용해서 스택 구현하기
@author: Park Jieun
"""
def pop(stack = []): #== def pop(stack)
stack.pop()
return stack
def push(stack = []):
value = input("PUSH: ")
stack.insert(len(stack)+1, value)
return stack
def stack_list(stack = []):
print("stack = ",stack)
myList = [1, "fruit", 3, 5, 8, "Jieun"]
stack_list(myList)
pop(myList)
stack_list(myList)
push(myList)
stack_list(myList)
|
cea57511f74a87fe06cd42d03a3b716ba0389424 | Rahul0506/Python | /Worksheet2/13.py | 586 | 3.890625 | 4 | number = int(input("Please enter a positive integer: "));
a = 2;
def checkPrimeRec(number, current):
if current > (number**0.5 + 1):
return True;
elif number == 1:
return False;
elif (number % current) == 0:
return False;
else:
current += 1;
return checkPrimeRec(number, current);
def checkPrimeIter(number):
if number == 1:
return False;
for i in range(2,round( number**0.5)+1):
if i == number:
return False;
elif (number % i) == 0:
return False;
return True;
print(checkPrimeRec(number, a));
print(checkPrimeIter(number)); |
4b4d16930ed4947a4149f009c2518f700ac050dc | digant0705/Algorithm | /LeetCode/Python/158 Read N Characters Given Read4 II.py | 1,563 | 3.71875 | 4 | # -*- coding: utf-8 -*-
'''
Read N Characters Given Read4 II - Call multiple times
======================================================
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it
returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that
reads n characters from the file.
Note:
The read function may be called multiple times.
'''
class Solution(object):
'''算法思路:
要将上次 read4 读取后剩余的保存起来
'''
def __init__(self):
self.left = []
def read(self, buf, n):
count, reads = 0, [''] * 4
if self.left:
while count < min(n, len(self.left)):
buf[count] = self.left[count]
count += 1
self.left = self.left[count:]
while count < n:
size = read4(reads)
if not size:
break
length = min(n - count, size)
self.left = reads[length : size]
for i in xrange(length):
buf[count] = reads[i]
count += 1
return count
index = 0
string = 'abcdefg'
def read4(reads):
global index
count = 0
while count < 4 and index < len(string):
reads[count] = string[index]
count += 1
index += 1
return count
s = Solution()
buf = [0] * 100
print s.read(buf, 3)
print s.read(buf, 4)
print s.read(buf, 3)
|
cbf37c978635e2b81e716c5543e461d8f6c80496 | Shraddhasaini/Project-Euler | /x014.py | 352 | 3.5625 | 4 | def collatz(n):
lst = []
while n > 1:
lst.append(n)
if (n % 2 == 0):
n = n//2
else:
n = 3*n +1
lst.append(1)
return lst
def number():
dict = {}
for i in range(1,1000000):
x = len(collatz(i))
dict.update({i : x} )
return max(dict,key=dict.get)
print(number())
|
f898f78a6d479b0971b2dc58d9c837a46ef4db5a | FeHeap/PythonPractice | /basic/ShoppingCart.py | 1,159 | 4.15625 | 4 | # -*- coding = utf-8 -*-
# @Time: 2021/7/9 上午 05:07
# @Software: PyCharm
products = [["iphone",6888],["MacPro",14800],["Mi6",2499],["Coffee",31],["Book",60],["Nike",699]]
print("----- product list -----")
for index,product in enumerate(products):
if(len(product[0]) < 6):
print("%d %s\t\t%d"%(index,product[0],product[1]))
else:
print("%d %s\t%d"%(index, product[0], product[1]))
print("-"*24)
shoppingCart = [0,0,0,0,0,0]
choose = ""
while choose != "q":
choose = input("What do you want to buy now?\ninput(0~5):")
if not (choose.isdigit() or choose == "q"):
print("input error!")
elif choose.isdigit():
if(int(choose) >= 0 and int(choose) <= 5):
shoppingCart[int(choose)] += 1;
else:
print("input error!")
sum = 0
print("----- shopping list -----")
for product in products:
if (len(product[0]) < 4):
print("%s\t\t%d"%(product[0], shoppingCart[products.index(product)]))
else:
print("%s\t%d"%(product[0], shoppingCart[products.index(product)]))
sum += product[1] * shoppingCart[products.index(product)]
print("price =",sum)
print("-"*25) |
8c9824e79adaffc0d82b70faf2fbf5cd8b5fc11e | keerthz/luminardjango | /Luminarpython/collections/listdemo/pattern.py | 170 | 3.65625 | 4 | lst=[3,5,8]#output[13,11,8]
#3+5+8=16
#16-3=13
#16-5=11
#16-8=8
output=[]
total=sum(lst)
for item in lst:
num=total-item#16-3=13
output.append(num)
print(output)
|
be4573d83712bac861c3f3f64ff4595396e9ce8c | SamGoodin/c200-Assignments | /LectureCoding/11-2.py | 909 | 3.546875 | 4 | #Stack LIFO (Last In, First Out)
#s = stack()
#Queue
#s.push(23) [23]
#s.push(45) [45, 23]
#s.push(67) [67, 45, 23]
#s.pop() = 67 [45, 23]
#s.empty() True if stack is empty, False if not.
class MyStack:
def __init__(self):
self.stack = []
def push(self, x):
self.stack.insert(0, x)
def pop(self):
if not self.empty():
g = self.stack[0]
self.stack.remove(g)
return g
else:
return self
def empty(self):
return len(self.stack) == 0
def __str__(self):
return str(self.stack)
s = "(()(()))"
def balanced(x):
s = MyStack()
for i in range(len(x)):
if x[i] == "(":
s.push("(")
elif x[i] == ")":
s.pop()
return s.empty()
print(balanced(s))
s = MyStack()
s.push(5)
s.push(10)
s.push(12)
print(s.pop())
print(s) |
abcbd91b0f00d035f7a20de6fa1abdd89f0e2eeb | jemappellesami/INFOH410 | /TP_S/src/tp_s_template.py | 1,842 | 4.03125 | 4 | #!/usr/bin/python3
import queue
import heapq
from collections import deque
def q1():
print("Q1:")
# using a stack:
d = []
# ...
# using a queue
# ...
# using a PrioQueue or heapq
# ...
def q3():
"""the graph can be stored using a adjency list or an adjency matrix.
Usually, the matrix is easier to use but uses more memory, here we use
an adjency list.
We store states as indexes in the list, where S->0, A->1, B->2 etc.
each sublist represents the list all states to which state i is
connected, with associated cost."""
print("Q2:")
graph = [
[(2, 7), (1, 3)], # S
[(4, 6), (3, 1)], # A
[(7, 9), (5, 1)], # B
[(0, 2), (4, 4)], # C
[(6, 6), (2, 3)], # D
[(7, 5)], # E
[(3, 2)], # G1
[(2, 8)], # G2
]
weights = [10, 5, 8, 3, 2, 4, 0, 0]
# your search:
# ...
def q4():
"""
We represent the state by a tuple of 3 values,
(x,y,z) where x is the number of missionaries at the left
y is the number of cannibals at the left and z is the position
of the boat. The initial state is (3,3,1).
"""
print("Q3:")
s = (3, 3, 1)
# ...
def q5():
"""
We want to find the shortest path between A and B, we are using A*.
in A*, f = g+h is the function to minimize where g is the value of
smallest known path and h in the heuristic.
"""
print("Q5:")
grid = [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
]
start = (3, 1)
goal = (3, 4)
# Your search:
# ...
def manhattan(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
if __name__ == "__main__":
q1()
q3()
q4()
q5()
|
dda61d3335ef8d2c05d9b6a52edc3f0992b05a08 | TomNguyen-0/Artificial-Intelligence | /checkers/src/abstractstrategy.py | 3,656 | 3.921875 | 4 | '''
Created on Mar 1, 2015
@author: mroch
'''
import checkerboard
class Strategy:
""""Abstract strategy for playing a two player game.
Abstract class from which specific strategies should be derived
"""
def __init__(self, player, game, maxplies):
""""Initialize a strategy
player is the player represented by this strategy
game is a class or instance that supports the class or instance method
game.other_player(player) which finds the name
of the other player
maxplies is the maximum number of plies before a cutoff is applied
"""
# Useful for initializing any constant values or structures
# used to evaluate the utility of a board
self.maxplayer = player#me
self.minplayer = game.other_player(player)#other player
self.maxplies = maxplies
self.starting_holder=True
def utility(self, board):
"Return the utility of the specified board"
#find the distance
#find the number of pieces pawns and kings
#eating moves
#to improve ai you can add in edge as being a better move because they are safe
on_the_board_pieces = self.how_many_pieces_on_the_board(board)#number of pieces on the board
on_the_board_distance = self.how_far_is_everything(board)
on_the_board_moves = self.the_winning_move(board)
answer = on_the_board_pieces+on_the_board_distance+on_the_board_moves
return answer
def player_pieces(self,board):
you=board.playeridx(self.minplayer)
me=board.playeridx(self.maxplayer)
my_pawns = board.get_pawnsN()[me]
my_kings = board.get_kingsN()[me]
your_pawns = board.get_pawnsN()[you]
your_kings = board.get_kingsN()[you]
return [[my_pawns,my_kings],[your_pawns,your_kings]]
def how_many_pieces_on_the_board(self,board):
piece = self.player_pieces(board)
pawn_value = piece[0][0] - piece[1][0]#my_pawns - your_pawns
king_value = piece[0][1] - piece[1][1]#my_kings - your_kings
real_value = pawn_value + (2*king_value)#king is worth twice the pawn
return real_value
def how_far_is_everything(self,board):
me=board.playeridx(self.maxplayer)#me = 0, you = 1
distance=0
for row,col,item in board: #row = 0, col =1 , item =b
identify_piece = board.identifypiece(item)
playeridx = identify_piece[0]# returns 1
kingpred = identify_piece[1] #return True or False
if not kingpred:#check to see if it is a king
if playeridx is me:
distance = distance + board.disttoking(item,row)#my piece from the throne
else:#the other player piece to the throne
distance = distance - board.disttoking(item,row)
return distance
def the_winning_move(self,board):
if self.starting_holder:
self.start = self.player_pieces(board)
self.later = self.start
self.starting_holder=False
self.now = self.later
self.later = self.player_pieces(board)
my_score= (self.now[0][0]+self.now[0][1])-(self.later[0][0]+self.later[0][1])
your_score = (self.now[1][0]+self.now[1][1])-(self.later[1][0]+self.later[1][1])
if my_score > your_score:#I lost more pieces than you
return -(my_score-your_score)#bad move
else:#better move
return my_score-your_score
'''
def play(self, board):
located in ai.
'''
|
8110fe506f72becfbc1b44d453af8950adbab328 | ColeAnderson7278/Daily_Practice | /practice_5-03/prac.py | 914 | 3.890625 | 4 | def find_streak(arr):
longest_streak = []
current_streak = []
for n in arr:
if len(current_streak) == 0 or n in current_streak:
current_streak.append(n)
if len(current_streak) > len(longest_streak):
longest_streak = current_streak
elif len(current_streak) > len(longest_streak):
longest_streak = current_streak
current_streak = []
current_streak.append(n)
else:
current_streak = []
current_streak.append(n)
print(format_streak(longest_streak))
def format_streak(arr):
formatted = []
if len(arr) > 0:
formatted.append(arr[0])
formatted.append(len(arr))
return formatted
def main():
# arr = [1, 2, 1, 1, 1, 2, 2, 2, 2]
# arr = []
# arr = [1, 2]
arr = [2, 2, 2, 1, 2]
find_streak(arr)
if __name__ == "__main__":
main()
|
b084fe23a8094f9fe76d383817ae38090df9b0d4 | Alb4tr02/holbertonschool-machine_learning | /math/0x00-linear_algebra/5-across_the_planes.py | 474 | 4.0625 | 4 | #!/usr/bin/env python3
"""function def def add_matrices2D(mat1, mat2): adds two 2D matrices:"""
def add_matrices2D(mat1, mat2):
"""INPUT: two arrays
OUTPUT: two arrays element-wise added:
"""
if len(mat1) != len(mat2) or len(mat1[0]) != len(mat2[0]):
return None
result_matrix = []
for i in range(len(mat1)):
row = [mat1[i][j] + mat2[i][j] for j in range(len(mat1[i]))]
result_matrix.append(row)
return result_matrix
|
c92ac0e263ad9cc2f42dba650618f3e8d025c0e4 | taritro98/DSA_Prac | /thirdlargest.py | 316 | 4.15625 | 4 | def thirdLargest(arr):
x = max(arr)
arr.pop(arr.index(x))
maxval = 0
for a in arr:
if a>maxval:
maxval = a
arr.pop(arr.index(maxval))
maxval = 0
for a in arr:
if a>maxval:
maxval = a
return maxval
print(thirdLargest([2,4,1,3,5])) |
75d63e5f856162cb843e4c1081e301b544a761ea | pandyakavi/Data-Structure | /Stack_Class.py | 407 | 3.75 | 4 | # Peek, Pop, isEmpty, Push, size()
class Stack_Class:
def __init__(self):
self.items = []
def Peek(self):
return self.items[-1]
def Pop(self):
#k = self.items[-1]
#self.items.remove(k)
return self.items.pop()#k
def isEmpty(self):
return self.items == []
def Push(self,val):
self.items.append(val)
def size(self):
return len(self.items)
def Print(self):
print(self.items)
|
6e48785ebb7cba78c490bfccb5856b410e795ef0 | willreadscott/Convex-Hulls | /grahamscan_t.py | 4,514 | 4 | 4 | """
Graham-scan Algorithm Tester
Author: William Scott
Date: 01/06/2015
Student Number: 11876177
"""
import sys
import operator
import math
def file_to_points():
"""Converts file into usable points"""
points = []
file = open(sys.argv[1])
# First line not needed for how .dat file is read into array, read to get out of way
file.readline()
for line in file:
line = line.strip('\n').split()
line = (int(line[0]), int(line[1]))
points.append(line)
return points
def is_ccw(point_a, point_b, point_c):
"""Returns if a line is Counter-clockwise or not"""
return is_on_line(point_a, point_b, point_c) > 0
def is_on_line(point_a, point_b, point_c):
"""Used to determine which side of the directed line made by point_a and point_b, that point_c lays.
If it returns 0, the point is on the line
If it returns >0 the point is counter-clockwise
If it returns <0 the point is clockwise
"""
return (point_b[0] - point_a[0]) * (point_c[1] - point_a[1]) - (point_b[1] - point_a[1]) * (point_c[0] - point_a[0])
def theta(point_a, point_b):
"""Computes an approximation of the angle between
the line AB and a horizontal line through A."""
dx = point_b[0] - point_a[0]
dy = point_b[1] - point_a[1]
if abs(dx) < 1.e-6 and abs(dy) < 1.e-6:
return 360
else:
t = dy/(abs(dx) + abs(dy))
if dx < 0:
t = 2 - t
elif dy < 0:
t += 4
if t == 0:
return 360
return t*90
def graham_scan(points):
"""Computes convex hull of a set of points, beginning with the lowest-rightmost point
and selecting the next point if it makes a left turn when compared to the last two elements
in the the working convex hull."""
smallest_point_index = find_min_point(points)
angle_list = create_angle_list(points, smallest_point_index)
angle_list = [i[0] for i in angle_list]
stack = [angle_list[0], angle_list[1], angle_list[2]]
del angle_list[:3]
while is_on_line(stack[0], stack[1], stack[2]) == 0:
try:
if distance(stack[0], stack[1]) > distance(stack[0], stack[2]):
del stack[2]
else:
del stack[1]
stack.append(angle_list[0])
del angle_list[0]
except IndexError:
return stack
for i in range(len(angle_list)):
while not (is_ccw(stack[-2], stack[-1], angle_list[i])) and (len(stack) >= 3):
stack.pop()
stack.append(angle_list[i])
# Special case if last 2 points are collinear
if is_on_line(stack[0], stack[-1], stack[-2]) == 0 and len(stack) > 3:
del stack[-1]
return stack
def distance(point_a, point_b):
"""Computes and returns the distance between two points"""
a_to_b = math.hypot(point_b[0] - point_a[0], point_b[1] - point_a[1])
return a_to_b
def create_angle_list(points, smallest_point_index):
"""Returns a list containing tuples with the point and angle of that point when compared to
the horizontal line through the point with the lowest point index."""
angle_dict = {}
for i in range(len(points)):
angle_dict[points[i]] = theta(points[smallest_point_index], points[i])
angle_dict[points[smallest_point_index]] = 0
angle_list = sorted(angle_dict.items(), key=operator.itemgetter(1))
return angle_list
def find_min_point(points):
"""Finds the lowest, rightmost point from a set of data, then returns its index"""
smallest_point_index = 0
for i in range(1, len(points)):
if points[i][1] < points[smallest_point_index][1]:
smallest_point_index = i
elif points[i][0] > points[smallest_point_index][0] and points[i][1] == points[smallest_point_index][1]:
smallest_point_index = i
return smallest_point_index
def points_to_index(points, points_dict):
"""Returns a convex hull back as a list containing the points original index locations"""
index_locations = ''
for point in points:
index_locations += str(points_dict[point]) + ' '
return index_locations
def go():
points = file_to_points()
points_dict = {points[i]: i for i in range(len(points))}
points = graham_scan(points)
index_locations = points_to_index(points, points_dict)
print(index_locations)
if __name__ == '__main__':
go()
|
dd406bbda6c56415beb0e1594cd8043b6590c269 | chyavan-mc/My-Solutions-to-Leetcode-problems-using-Python-3 | /Palindrome Linked List.py | 980 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
lis = []
ptr = head
while(ptr!=None):
lis.append(ptr.val)
ptr=ptr.next
ptr = self.reverseList(head)
i=0
while(ptr!=None):
if(lis[i]!=ptr.val):
return False
i+=1
ptr=ptr.next
return True
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None:
return head
cpt,ptr=head,head
ptr=ptr.next
head.next = None
while(ptr!=None):
head=ptr
ptr=ptr.next
head.next=cpt
cpt=head
return head |
d9c57a52b0e16c410d5012a5b9ca3f08a6e6d950 | somuchpancakes/Py_Expense_template | /expense.py | 1,452 | 3.609375 | 4 | import os
import csv
from PyInquirer import prompt
expense_questions = [
{
"type":"input",
"name":"amount",
"message":"New Expense - Amount: ",
},
{
"type":"input",
"name":"label",
"message":"New Expense - Label: ",
},
{
"type":"list",
"name":"spender",
"message":"Who is the spender ?",
"choices": []
},
{
'type': 'checkbox',
'name': 'involved_users',
'message': 'Select the involved users :',
'choices': []
},
]
def get_users():
with open('users.csv', newline='') as csvfile:
users_list_csv = csv.reader(csvfile, delimiter=',')
for row in users_list_csv :
expense_questions[2]["choices"].append( "".join(row) )
expense_questions[3]["choices"].append( {'name' : "".join(row)} )
def new_expense(*args):
if (os. stat("users.csv").st_size == 0):
print("You must define at least one user !")
return False
get_users() #Load the users.csv
infos = prompt(expense_questions)
with open('expense_report.csv', 'a', newline='') as csvfile:
fieldnames = ['amount', 'label', 'spender', 'involved_users']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow(infos) # Writing the informations on external file ¯\_(ツ)_/¯
print("Expense Added !")
return True |
7ddaaaf78b7d6941276c049a2f3f032df83a39ae | razorRun/ud036_StarterCode | /media.py | 439 | 3.640625 | 4 | class Movie():
def __init__(self, title, year, trailerUrl, boxUrl, screenWriter):
"""This class can be used to create instence of movies,
consttructor can be called using Movies(title, year, trailerUrl,
boxUrl, screenWriter)"""
self.title = title
self.year = year
self.trailer_youtube_url = trailerUrl
self.poster_image_url = boxUrl
self.screenWriter = screenWriter
|
46c1b23eddf9d2243d1a9bbc4b47422a4277690c | YannCedric/Machine-Learning | /Main.py | 4,368 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from graphics import *
from random import randint
import math
# init pop
def create_person():
num = randint(0,4)
return num
def _init(pop_size, dna_size):
poputation = []
for i in range(pop_size):
new_dna = []
for j in range(dna_size):
new_person = create_person()
new_dna.append(new_person)
poputation.append(new_dna)
return poputation
# compute fitness
# dna,goal => fitness
def is_dna_valid(dna, goal):
if len(dna) != len(goal):
return False
else :
return True
def _fitness(dna, goal):
if(is_dna_valid(dna, goal)):
score = 0.0
for i in range(len(goal)):
if dna[i] == goal[i]:
score = score + 1
return (score/len(goal) * 100)
else:
return -1
# select the better ones
# population => best maybe (parents)
def add_or_not(fitness, maxFitness):
num = randint(0,maxFitness)
return num <= fitness
def fitness(person,goal):
count = 0.0
for i in range(len(person)):
if person[i] == goal[i]:
count = count+1
fitness_score = math.floor(count/len(goal) * 100)
return fitness_score
def compute_fitnesses(population, goal):
best_fitness = 0
population_with_fitness = []
for person in population:
fit = fitness(person,goal)
population_with_fitness.append([person,fit])
if best_fitness < fit:
best_fitness = fit
return population_with_fitness,best_fitness
def _selection(population_with_fitness, maxFitness):
next_parents = []
for person in population_with_fitness:
fit = person[1]
if add_or_not(fit, maxFitness):
next_parents.append(person[0])
return next_parents
# crossover
# parents => offsprings
def _crossover(parents):
next_generation = []
for index in range(len(parents)/2):
parent1 = parents[index]
parent2 = parents[-index-1]
new_child1 = []
new_child2 = []
for i in range(len(parent1)):
if i%2 == 0:
new_child1.append(parent1[i])
new_child2.append(parent2[i])
else:
new_child1.append(parent2[i])
new_child2.append(parent1[i])
next_generation.append(new_child1)
next_generation.append(new_child2)
if len(next_generation) >= len(parents):
return next_generation
return next_generation
# mutate new population
def mutate(person, mutation_rate):
mutated = 0
mutant = []
for i in person:
if randint(0,100) < mutation_rate:
mutated = mutated + 1
mutant.append(create_person())
else:
mutant.append(i)
if mutated != 0:
print "Mutation: ", person , "-->", mutant
return mutant
def _mutate_all(offsprings, rate):
mutants = []
for offspring in offsprings:
mutants.append(mutate(offspring, rate))
return mutants
# Graph
def arr_to_string(arr):
return ",".join(map(str,arr))
win = GraphWin("Learner",500,300)
## START
GOAL = [2,2,2,2,2,2,2,2,2,2,2]
MUTATION_RATE = 0.1
#graph
goal_text = Text(Point(250,100), arr_to_string(GOAL) )
goal_text.setSize(20)
goal_text.draw(win)
fittest_text = Text(Point(250,200), arr_to_string([]) )
fittest_text.setSize(20)
fittest_text.draw(win)
poputation = _init(6,(len(GOAL)))
max_fitness = 0
counter = 0
fittest = []
fittest_text.setText(arr_to_string(fittest))
while max_fitness <= 90:
counter = counter + 1
population_with_fitness , max_fitness = compute_fitnesses(poputation, GOAL)
selected = _selection(population_with_fitness, max_fitness)
#print "Selected - - > ",selected
offsprings = _crossover(selected)
#print "OffSpring" ,offsprings
mutants = _mutate_all(offsprings, MUTATION_RATE)
new_population = selected + mutants
print "Generation ", counter ,"->",poputation
print "Max fitness : " , max_fitness
print "New population : ", new_population
poputation = new_population
for person in population_with_fitness:
if person[1] == max_fitness:
fittest = person[0]
fittest_text.setText(arr_to_string(fittest))
print "Done"
print "Fittest : ", fittest
win.getMouse()
win.close()
|
d70ea3fc9401f2f7244093d7edbf14bd2e39f400 | sravi97/I210_Information_Infrastructure1 | /Lecture/Lecture 18/selection_starter.py | 1,233 | 4.46875 | 4 | #import the tools file so we can use swap
from tools import *
#define a function called selection_sort that takes a list of items
def selection_sort(items):
# make a copy of the list so we don't destroy the original data
# because lists (like items) pass by reference
ordered = items.copy()
# sort the copy using the Selection Sort algorithm
# YOUR CODE GOES HERE
#walk through the list
for i in range(len(ordered)):
#store a current smallest position (index value)
smallest = -1
#walk through the unsorted portion
for j in range(i, len(ordered)):
if ordered[j] < ordered[smallest]:
smallest = j;
swap(ordered, smallest, i)
#is there anything smaller than our current smallest thing
#update the value of current smallest
#swap out the elements
return ordered
#main
print(selection_sort([3,1,7,2,6,5,0,4]))
# NOTE TO STUDENTS
# If you're having a trouble understanding the algorithm, check out this link:
# https://www.tutorialspoint.com/data_structures_algorithms/selection_sort_algorithm.htm
# You need to implement the solution yourself, however.
|
aac625c0417676c6f4f501612dbb16933453dfb9 | AcubeK/LeDoMaiHanh-Fundamental-C4E23 | /Season 4/D4/ex_2.py | 534 | 3.640625 | 4 |
p = [
{
"Name": "Huy",
"Hours": 30,
"MPH":50,
},
{
"Name": "Quan",
"Hours":20,
"MPH": 40,
},
{"Name": "Duc",
"Hours": 15,
"MPH": 35,
}
]
print("Numbers of hours of each person:")
for q in p:
print(q["Name"], q["Hours"], sep = ": ")
print()
print("Wage of each person (thousands VND):")
for q in p:
q["MW"] = q["Hours"]*q["MPH"]
print(q["Name"], q["MW"], sep =": ")
print()
ws = 0
print("Wage sum (thousands VND): ")
for q in p:
ws = ws + i["MW"]
print(ws) |
249bb62d7426492303300ef436751c1ae7430e3f | drahmuty/Algorithm-Design-Manual | /03-26.py | 2,280 | 4.28125 | 4 | """
3-26.
Reverse the words in a sentence.
i.e., My name is Chris becomes Chris is name My.
Optimize for time and space.
"""
# Reverse the words in a sentence
def reverse_sentence(sentence):
# Create sentence object and linked list
sentence_obj = Sentence(sentence)
sentence_list = LinkedList()
# Add each word to linked list
word = sentence_obj.get_next_word()
while word:
sentence_list.insert(word)
word = sentence_obj.get_next_word()
# Reconstruct sentence using LIFO order
sentence_reversed = ''
word = sentence_list.pop()
while word:
sentence_reversed += word
word = sentence_list.pop()
return sentence_reversed
# Sentence class
class Sentence:
def __init__(self, string):
self.string = str(string)
self.length = len(self.string)
self.index = 0
# Get next word or string of symbols
def get_next_word(self):
i = self.index
j = self.length
s = self.string
y = ''
word = False
symbol = False
while i < j:
c = s[i]
if ord(c.upper()) < 65 or ord(c.upper()) > 90:
if word:
break
symbol = True
else:
if symbol:
break
word = True
y += c
i += 1
self.index = i
return y
# Linked list node class
class Node:
def __init__(self, value):
self.value = value
self.next = None
# Linked list class
class LinkedList:
# Initialize linked list
def __init__(self):
self.head = None
# Insert into list
def insert(self, x):
new_node = Node(x)
if self.head:
new_node.next = self.head
self.head = new_node
else:
self.head = new_node
# Return/remove first item from list
def pop(self):
if self.head:
top = self.head.value
self.head = self.head.next
return top
else:
return None
# Driver program
a = reverse_sentence('Hello, world!')
b = reverse_sentence('This is the greatest Saturday of my life! You just wait and see. - Dave')
print(a)
print(b)
|
5fc239aa51f5e3396d37468f3fbb654a9cfc86bd | TechInTech/Interview_Codes | /杂题/LinkNodeCopy.py | 1,039 | 3.5 | 4 | # -*- coding:utf-8 -*-
class LinkNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class CreateLink:
def __init__(self, lyst):
self.lyst = lyst
self.length = len(lyst)
def get_link(self):
p = link = LinkNode()
i = 0
while i < self.length:
node = LinkNode(self.lyst[i])
p.next = node
p = p.next
i += 1
# p = link.next
# while p:
# val = p.val
# print(val)
# p = p.next
return link.next
def Copy_Nodes(links):
new_link = p = LinkNode()
while links:
node = LinkNode(links.val)
p.next = node
p = p.next
links = links.next
return new_link.next
if __name__ == "__main__":
lyst = list(range(10))
link = CreateLink(lyst)
linkNode = link.get_link()
copy_node = Copy_Nodes(linkNode)
while copy_node:
print("Copy: ",copy_node.val)
copy_node = copy_node.next
|
0ae6e70b0ce1e2dc8a99e7badb8d295049c0b8ec | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4345/codes/1692_1099.py | 629 | 4.03125 | 4 | from math import*
# Leitura dos lados do triangulo a, b, and c
a=float(input("Lado 1: "))
b=float(input("Lado 2: "))
c=float(input("Lado 3: "))
print("Entradas:", a, ",", b, ",", c)
if (a>0) and (b>0) and (c>0):
# Testa se medidas correspondem aas de um triangulo
if ((a < b+c) and (b< c+a) and (c<a+b)):
if ((a==b or b==c))
print("Tipo de triangulo:", "equilatero")
elif (a==b or b==c or c==a)
print("Tipo de triangulo:", "isosceles")
else:
print("Tipo de triangulo:", "escaleno")
else:
print("Tipo de triangulo:", "invalido")
else:
print("Tipo de triangulo:", "invalido")
|
5dd06da63a2e0d506a95e63180bdc1668f84d746 | rajeshvermadav/XI_2020 | /controlstatements/oddnumber1_8.py | 102 | 3.984375 | 4 | #display odd numbers 1 to 8
for y in range(1,9,2):
print("odd numbers between 1 to 8:-",y)
|
f56d2a93c288e04901e4efedc369f3ea705c9d34 | christostsekouronas/learnpython | /second/challenge.py | 226 | 4.1875 | 4 | name = input("Please enter your name: ")
age = int(input("How old are you? "))
if 18 <= age < 31:
print("Welcome club 18-30 holidays, {0}".format(name))
else:
print("I'm sorry, our holidays are only for cool people")
|
f2cbee3f72ab72282bb4b169792864cdf52b21ce | vilvamoorthy/Python | /Numerical Tables.py | 157 | 3.90625 | 4 | # Enter the table number:
num = int(input("Enter the table number you want: "))
# Using for loop:
for i in range(1, 11):
print(num, "x", i, "=", num*i)
|
078c0d5f4f664b34eda46f5ee586716acb6daf5a | moshekagan/Computational_Thinking_Programming | /frontal_exersices/recitation_solutions_2/ex2_part_B.py | 579 | 4.3125 | 4 | number = input("Insert a 3 digits number: ")
if len(number) != 3 or not number.isdigit():
print("Invalid input")
else:
number = int(number)
first_digit = number // 100
second_digit = number // 10 % 10
third_digit = number % 10
is_middle_greater = second_digit > first_digit and second_digit > third_digit
is_middle_smaller = second_digit < first_digit and second_digit < third_digit
if is_middle_greater or is_middle_smaller:
print(str(number) + " is extreme number.")
else:
print(str(number) + " is NOT extreme number.")
|
2aaba7f2b33584f4c9226254025af78706f02747 | terrantsh/Python-- | /third/func.py | 1,243 | 4.09375 | 4 | #-*- coding = utf-8 -*-
#@Time : 2020/4/28 8:24
#@Author : Shanhe.Tan
#@File : func.py
#@Software : PyCharm
'''
#函数的定义
def printinfo():
print("---------------------")
print(" Hello World ")
print("---------------------")
#函数的调用
printinfo()
'''
'''
#带参数的函数
def add2Num(a, b):
c = a + b
print(c)
add2Num(11, 22)
'''
'''
#带返回值的参数
def add2Num(a, b):
return a + b #通过return来返回运算结果
result = add2Num(11, 22)
print(result)
print(add2Num(11, 22))
'''
'''
#返回多个值的函数
def divid(a, b):
shang = a/b
yushu = a%b
return shang, yushu #多个值得返回方式
sh,yu = divid(5, 2) #需要使用多个值来保存返回内容
print("shang: %d, yushu: %d"%(sh,yu))
'''
'''
#打印一条线
def OneLine():
print("-------------------")
def MultiLines(n):
i = 0
while i < n:
OneLine()
i += 1
MultiLines(5)
'''
#求3个数的和
def sum3Number(a,b,c):
return a + b + c
#完成3个数的平均值
def average3Number(a,b,c):
sumResult = sum3Number(10,20,30)
averResult = sumResult/3.0
return averResult
result = average3Number(10,20,30)
print(result)
|
7e18e1076e272a3d0966ae631445c92345040e0b | saiteja2816/guva | /sort.py | 236 | 3.640625 | 4 | list=[int(x) for x in raw_input().split()]
a=[]
for num in range(len(list)):
for i in range(num+1,len(list)):
if(list[num]==list[+i]):
a.append(list[num])
l=set[a]
for i in range(len(l)):
print(l[i],end=" ")
|
789628ac0da916322971d0bcfca85d3391f60899 | Cking351/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 1,524 | 4.03125 | 4 | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self):
self.head = None
def add_to_head(self, value):
node = Node(value)
if self.head is not None:
node.set_next(self.head)
self.head = node
def contains(self, value):
if not self.head:
return False
current = self.head
while current:
if current.get_value() == value:
return True
current = current.get_next()
return False
def reverse_list(self, node, prev):
# BASE CASE
if node is None:
return
# This checks for a single item in the list and sets the node as the head
# No need to reverse
elif node.next_node is None:
self.head = node
return self.head
else:
# Recursive case. sets the node.next.next as the 2nd node from current
# This should make the recursion work backwards through the list, and return the values reversed..
rev = self.reverse_list(node.next_node, prev)
node.next_node.next_node = node # <- This is crazy. Thanks stack overflow
node.next_node = prev
return rev
|
48a73dc8d8f03be39a6b86dd3c4a16a7aef04822 | OdedraBharat303/data-science | /core-python/loop1.py | 86 | 3.734375 | 4 | a=int(input("enter number :"))
i=1
s=0
while i<=a :
s=s+i
i=i+1
print(s)
|
7945dbddc5968844ee50f380dbb84f617b56adc6 | Pavche/python_scripts | /counter.py | 182 | 3.890625 | 4 | def count(sequence, item):
result = 0
for elem in sequence:
if elem == item:
result += 1
return result
print count(['one','two','three',1,2,3,'one','two'],"three") |
4589c495e72c94032e6a7e48764e4a9ada33edb1 | vishalb007/Assignment3 | /Assignment3_2.py | 450 | 3.875 | 4 | def GetElements(num):
lis=[]
for i in range(num):
print("Enter element : ",i+1)
n=int(input())
lis.append(n)
return lis
def Max(lis,num):
max=lis[0]
for i in range(num):
if(lis[i]>max):
max=lis[i]
return max
def main():
num =int(input("Enter number of elements : "))
lis=[]
print("Enter the elements")
lis=GetElements(num)
max=Max(lis,num)
print("Max is : ",max)
if (__name__=="__main__"):
main()
|
5f489efa8461791bd1255c4854a21949e5b4eb88 | avdg/pysudokudemo | /sudokuSolver.py | 4,139 | 4 | 4 | """
Specialised in solving sudoku's
"""
class SudokuSolver:
"""
Constructor
"""
def __init__(self):
self.reset()
"""
Resets the sudoku status for a normal 9x9 grid sudoku
"""
def reset(self):
self.sudoku = [[range(1, 10) for y in range(9)] for x in range(9)]
self.relation = {
'rows': [[[y, x] for y in range(9)] for x in range(9)],
'columns': [[[x, y] for y in range(9)] for x in range(9)],
'blocks': [[[
int(y / 3) + (int(x / 3) * 3), #expecting int does floor stuff
(y % 3) + (x % 3 * 3)
] for y in range(9)] for x in range(9)]
}
"""
Converts a 2D sudoku to its internal 3D representation
"""
def setSudoku(self, sudoku):
self.sudoku = [[range(1, 10) for y in range(9)] for x in range(9)]
for x, rows in enumerate(sudoku):
for y, cell in enumerate(rows):
if cell != 0:
self.sudoku[x][y] = [cell]
"""
Converts an internal 3d representation to a 2d sudoku
"""
def getSudoku(self):
sudoku = [[0] * 9 for x in range(9)]
for x, rows in enumerate(self.sudoku):
for y, cell in enumerate(rows):
if len(cell) == 1:
sudoku[x][y] = cell[0]
return sudoku
"""
Solve algoritme
"""
def solve(self):
self.solveSolved()
if self.isSolved() != True:
self.cleanupTwins()
self.solveSolved()
"""
Checks the state of the sudoku
"""
def isSolved(self):
unsolved = 0
for x, rows in enumerate(self.sudoku):
for y, cell in enumerate(rows):
if len(cell) == 0:
return 'Error'
elif len(cell) != 1:
unsolved += 1
if unsolved > 0:
return 'Not solved'
else:
return True
"""
Scraps leftovers in grid:
the numbers that are already used as a solution
"""
def solveSolved(self):
solved = False
while not solved:
solved = True
for x, rows in enumerate(self.sudoku):
for y, cell in enumerate(rows):
if len(cell) == 1 and self.markCellSolved(x, y):
solved = False
"""
Returns true if the cell occurs in the given relation block
"""
def cellInBlockRow(self, x, y, blockKey, blockRow):
for cell in self.relation[blockKey][blockRow]:
if [x, y] == cell:
return True
return False
"""
Cleans up surrounding fields by eliminating the number in other fields in
the same blocks
"""
def markCellSolved(self, x, y):
if len(self.sudoku[x][y]) != 1:
return False
hit = False
number = self.sudoku[x][y][0]
# lookup
for name, blocks in self.relation.iteritems():
for row, block in enumerate(blocks):
if self.cellInBlockRow(x, y, name, row):
# cleanup
for cleanCell in self.relation[name][row]:
if cleanCell[0] == x and cleanCell[1] == y:
continue
if number in self.sudoku[cleanCell[0]][cleanCell[1]]:
self.sudoku[cleanCell[0]][cleanCell[1]].remove(number)
hit = True
return hit
"""
Tries to find a match where 2 numbers are found
at 2 identical cells in a row/block/column
"""
def cleanupTwins(self):
# lookup
for name, blocks in self.relation.iteritems():
for row, block in enumerate(blocks):
twins = [[] for x in range(10)] # twins[x][] = [cell1, cell2]
for x in range(1, 10):
found = []
for cell in block:
if x in self.sudoku[cell[0]][cell[1]]:
found.append([cell[0], cell[1]])
if len(found) == 2:
twins[x].append(found)
# cleanup
for x in range(1, 10):
for xItem in twins[x]:
for y in range(x + 1, 10):
for yItem in twins[y]:
if xItem == yItem:
for clearBlock in xItem:
for z in range(1, 10):
if x == z or y == z or \
not z in self.sudoku[clearBlock[0]][clearBlock[1]]:
continue
self.sudoku[clearBlock[0]][clearBlock[1]].remove(z) |
238d63d161e3bfd1ef353088992f9f50a7d4d621 | Jasonhou209/notes | /leetcode/20_valid_parentheses.py | 1,284 | 3.96875 | 4 | """
20.给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
1. 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
"""
class Solution:
def __init__(self):
self.d = {'(':')','[':']','{':'}'}
self.stack = []
def isValid(self, s: str) -> bool:
for v in s:
if v in self.d:
self.stack.append(v)
elif len(self.stack) == 0:
return False
elif self.d[self.stack.pop()] == v:
continue
else:
return False
else:
return True
def main():
s = Solution()
print("()", "=>", s.isValid("()"))
print("()[]{}", "=>", s.isValid("()[]{}"))
print("(]", "=>", s.isValid("(]"))
print("([)]", "=>", s.isValid("([)]"))
print("{[]}", "=>", s.isValid("{[]}"))
print("()[{]}", "=>", s.isValid("()[{]}"))
if __name__ == "__main__":
main() |
a01c2066969ed2af100cb2e668ed50845375ef49 | py-john/workoutloader | /workout.py | 1,594 | 3.890625 | 4 | #!/usr/bin/env python3
"""workout.py:
Opens video files for daily workouts based on a workout calendar.
"""
from time import sleep
from datetime import datetime
import create
PROGRAM_START_DATE = datetime(2018, 3, 19, 5, 0)
def print_calendar(day):
"""Draws a calendar with X's for completed days"""
print()
for d in range(1, 91):
text = d
if d < day:
text = 'X'
print(str(text).rjust(2), end=' ')
if d % 7 == 0:
print()
if d < 60 and d % 28 == 0:
print()
if day > 90:
print('\n\n----Elite Block----\n')
for d in range(1, 28):
text = d
if d < (day-91):
text = 'X'
print(str(text).rjust(2), end=' ')
if d % 7 == 0:
print()
def get_day():
"""Return the number of the current day in the schedule"""
return ((datetime.now() - PROGRAM_START_DATE).days + 1)
def get_workout(day_number):
"""Return workout object for current day"""
workouts = create.workout_list()
workout = None
for w in workouts:
if day_number in w.days:
workout = w
break
return workout
def main():
"""Get the workout for the current day and load the image/video files"""
day_number = get_day()
workout = get_workout(day_number)
print_calendar(day_number)
if workout:
print('\n\nDay:', day_number)
print(workout, '\n')
sleep(2)
workout.load_image()
workout.load_video()
if __name__ == '__main__':
main()
|
269072279248f97df7c6a7595d8b527be56d494f | artkpv/code-dojo | /yandex.ru/Yandex2016Algo/pr3_shashmati.py | 6,185 | 3.625 | 4 | """
https://contest.yandex.com/algorithm2016/contest/2497/problems/C/
Строить дерево ходов. Для текущего хода кого-нибудь, найти такой ход при котором будет выигрыш,
knight (w), shashka (black)
a b c d
1
2
3 w
4 b
0 a3, b4, b
(a3) 1 a3, c3, w
2 c4, c3, b (черные выигрывают) 3 b1 4 c2 5 b5
Tree (b - black moves, w - white moves, W - white wins, B - black wins):
b b
w w w w w w w w
b b b B
Knight moves:
1 2 3 4 5
1
2
3 k
4
5
"""
FIELD_SIZE = 8 # field size
class Position:
def __init__(self, knight, shashka, turn, winner=None):
self.k = knight
self.s = shashka
self.t = turn
self.w = winner
def is_s(self):
return self.t
def is_shashka_at_home(self):
return self.s[1] == 1 # shasha.hor
def _get_notation(self, v):
return chr(ord('a') + v[0] - 1) + str(v[1])
def __eq__(self, other):
return self.k == other.k and self.s == other.k and self.t == other.t
def __hash__(self):
return hash((self.k, self.s, self.t))
def __str__(self):
return '({} {} {} "{}")'.format( \
self._get_notation(self.k), \
self._get_notation(self.s), \
'shashka' if self.is_s() else 'knight', \
self.w + ' wins' if self.w else '')
class Game:
def __init__(self, root):
if root.is_shashka_at_home():
root.w = 'shashka'
self.root = root
self.G = {root: []}
self._add_moves([root])
def _add_moves(self, queue): # BFS
"""
Строит дерево всех ходов
"""
while len(queue) > 0:
v = queue.pop()
if v not in self.G:
self.G[v] = []
if v.w is None: # not game end
for w in self._next_moves(v):
self.G[v] += [w]
if w not in self.G:
queue.insert(0, w)
# end of while, all moves in G
def _next_moves(self, v):
global FIELD_SIZE
assert v.w is None, 'not game end'
sver = v.s[0]
shor = v.s[1]
kver = v.k[0]
khor = v.k[1]
if v.is_s(): # shashka
assert shor != 1, "shashka didn't reach last line"
# left move:
if sver > 1: # can move to left
if sver - 1 == kver and shor - 1 == khor: # knight there
if sver > 2 and shor > 2: # there is space to jump
yield Position(v.k, (sver - 2, shor - 2), False, 'shashka')
# else there is no space to jump over
else: # knight not there
yield Position(v.k, (sver - 1, shor - 1), False, 'shashka' if shor == 2 else None)
# right move:
if sver < FIELD_SIZE: # can move
if sver + 1 == kver and shor - 1 == khor: # knight there
if sver < FIELD_SIZE - 1 and shor > 2: # there is space to jump
yield Position(v.k, (sver + 2, shor - 2), False, 'shashka')
# else there is no space to jump over
else: # knight not there
yield Position(v.k, (sver + 1, shor - 1), False, 'shashka' if shor == 2 else None)
else: # knight moves
get_move = lambda k: Position(k, v.s, True, 'knight' if k == v.s else None)
# left 4 moves:
if kver - 2 > 0 and khor - 1 > 0:
yield get_move((kver - 2, khor - 1))
if kver - 1 > 0 and khor - 2 > 0:
yield get_move((kver - 1, khor - 2))
if kver - 2 > 0 and khor + 1 <= FIELD_SIZE:
yield get_move((kver - 2, khor + 1))
if kver - 1 > 0 and khor + 2 <= FIELD_SIZE:
yield get_move((kver - 1, khor + 2))
# right 4 moves:
if kver + 2 <= FIELD_SIZE and khor - 1 > 0:
yield get_move((kver + 2, khor - 1))
if kver + 1 <= FIELD_SIZE and khor - 2 > 0:
yield get_move((kver + 1, khor - 2))
if kver + 2 <= FIELD_SIZE and khor + 1 <= FIELD_SIZE:
yield get_move((kver + 2, khor + 1))
if kver + 1 <= FIELD_SIZE and khor + 2 <= FIELD_SIZE:
yield get_move((kver + 1, khor + 2))
def winner(self):
return self._winner(self.root)
def _winner(self, v):
# выигрышь в текущей позиции определяется тем,
# может ли игрок, делающий ход сейчас выбрать выигрышный
# вариант. Если вариант не определен, то спускаемя ниже по дереву.
if not v.w:
moves = self.G[v]
if v.is_s(): # shashka
v.w = 'shashka' \
if any(self._winner(w) == 'shashka' for w in moves) \
else 'knight'
else:
v.w = 'knight' \
if any(self._winner(w) == 'knight' for w in moves) \
else 'shashka'
return v.w
def __str__(self):
return self.s(self.root, 0)
def s(self, v, level):
s = (' ' * level) + str(v) + '\n'
for w in self.G[v]:
s += self.s(w, level + 1)
return s
turn = (input().strip() == 'black') # otherwise it is white
parse = lambda s: ((ord(s[0]) - ord('a') + 1), int(s[1])) # (ver, hor)
knight = parse(input().strip()) # white knight
shashka = parse(input().strip()) # black shashka
first = Position(knight, shashka, turn)
game = Game(first) # (white position, black position, who moves next, who won)
w = game.winner()
print('white' if w == 'knight' else 'black')
|
961b9352e6c975d49d366d149a044eb2683b8a15 | gordonje/dl_depository | /utils.py | 515 | 3.640625 | 4 | from datetime import timedelta
def time_diff (tdelta):
# if more than a day
if tdelta.total_seconds() > 86400:
return '{} days'.format(abs(tdelta.total_seconds() / 86400))
# if more than an hour
elif tdelta.total_seconds() > 3600:
return '{} hours'.format(abs(tdelta.total_seconds() / 3600))
# if more than a minute
elif tdelta.total_seconds() > 60:
return '{} minutes'.format(abs(tdelta.total_seconds() / 60))
# or just return seconds
else:
return '{} seconds'.format(abs(tdelta.total_seconds())) |
a01d26c64c94877bb4a46aed37d912a6aabdcd82 | aleksamarkoni/uvasolutions | /10646 - What is the Card/main.py | 3,757 | 3.984375 | 4 | import sys
class Card(object):
"""Represents a standard playing card.
Attributes:
suit: integer 0-3
rank: integer 1-13
"""
suit_names = ["C", "D", "H", "S"]
rank_names = [None, None, "2", "3", "4", "5", "6", "7",
"8", "9", "T", "J", "Q", "K", "A"]
def __init__(self, rank="2", suit="C", ):
self.rank = self.rank_names.index(rank)
self.suit = self.suit_names.index(suit)
def __str__(self):
"""Returns a human-readable string representation."""
return '%s%s' % (self.rank_names[self.rank], self.suit_names[self.suit])
def __lt__(self, other):
return self.rank < other.rank
def __eq__(self, other):
return self.rank == other.rank
def card_value(self):
if self.rank >= 2 and self.rank <= 9:
return self.rank
else:
return 10
class Deck(object):
"""Represents a deck of cards.
Attributes:
cards: list of Card objects.
"""
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(2, 15):
card = Card(suit, rank)
self.cards.append(card)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return ' '.join(res)
def add_card(self, card):
"""Adds a card to the deck."""
self.cards.append(card)
def add_deck(self, deck):
self.cards = self.cards + deck.cards
def remove_card(self, card):
"""Removes a card from the deck."""
self.cards.remove(card)
def pop_card(self, i=-1):
"""Removes and returns a card from the deck.
i: index of the card to pop; by default, pops the last card.
"""
return self.cards.pop(i)
def shuffle(self):
"""Shuffles the cards in this deck."""
random.shuffle(self.cards)
def sort(self):
"""Sorts the cards in ascending order."""
self.cards.sort()
def move_cards(self, hand, num):
"""Moves the given number of cards from the deck into the Hand.
hand: destination Hand object
num: integer number of cards to move
"""
for i in range(num):
hand.add_card(self.pop_card())
def split_deck(self, hand, num):
""" splits the deck on two parts
self will contain cards from up to and including num
example, lets say that you have 10 cards in a deck and do the
split_deck(hand, 4) the result will be
that the deck will have 4 cards and hand will have 6
and hand will have cards from num to end of the dec"""
for i in range(num, len(self.cards)):
hand.add_card(self.cards[i])
del self.cards[num:]
class Hand(Deck):
"""Represents a hand of playing cards."""
def __init__(self, cards, label=''):
self.cards = []
for c in cards.split():
self.add_card(Card(c[0], c[1]))
self.label = label
def what_is_the_card(hand):
top_pile = Hand("")
hand.split_deck(top_pile, len(hand.cards) - 25)
y = 0
for i in range(3):
x = hand.pop_card().card_value()
y = y + x
for j in range(10 - x):
hand.pop_card()
hand.add_deck(top_pile)
return hand.cards[y-1]
if __name__=="__main__":
line = sys.stdin.readline().strip()
test_cases = int(line)
for test_case in range(0, test_cases):
line = sys.stdin.readline().strip()
hand = Hand(line[:155])
print("Case {0}: {1}".format(test_case+1, what_is_the_card(hand)))
|
4957f01191aa20a4f752908b89ad57b08c384dda | s654632396/learnPython | /regularExpression/p1.py | 376 | 3.6875 | 4 | # coding=utf-8
import re
str1 = 'StuDy python'
# print str1.startswith('study')
# print str1.endswith('python')
#
# p = re.compile(r'study', re.I)
# m = p.match(str1)
# print m.group()
# print m.span()
# print m.string
# p = re.compile(r'_')
# m = p.match('this is a _string')
# print m.group() # err ,m is None
# m = re.match(r'(study)', str1, re.I)
# print m.groups()
|
fb8d0486394b4d0137e7e5c27dea43f2f9f89945 | guys79/SerachEngine | /StopWordsHolder.py | 885 | 3.953125 | 4 | # This class will save the stop words in a list so we can access the list fast
class StopWordsHolder:
list_of_stop_words = [] # this list will contain all the stop words
# The constructor will initialize the list with the stop words
def __init__(self):
try:
file = open("stop_words.txt","r")
except:
file = None
with file:
lines = file.readlines()
self.list_of_stop_words = [line.rstrip('\n') for line in lines]
file.close()
# This function will return true if the word i9s a stop word
def is_stop_word(self,word):
return word.lower() in self.list_of_stop_words
#x = StopWordsHolder()
#print x.is_stop_word("and")
#print x.is_stop_word("aNd")
#print x.is_stop_word("between")
#print x.is_stop_word("is")
#print x.is_stop_word("i am")
#print x.is_stop_word("i'm")
|
31d7796e61cecd875c2aab6a7bfcc3f7c6b6e078 | stuycs-softdev-2014-2015/classcode | /fall-5/tdd/utils1.py | 838 | 3.71875 | 4 |
def validate_password(pword):
if len(pword)<6 or len(pword)>8:
return False
return True
def test_password_length():
r1 = validate_password("aaa")
if r1 != False:
print "short password test failed"
else:
print "short password test passed"
r2 = validate_password("aaaaaaaaa")
if r2 != False:
print "long password test failed"
else:
print "long password test passed"
r3 = validate_password("aaaaaaa")
if r3 != True:
print "correct length test failed"
else:
print "correct length password test passed"
def test_password_numbers():
pass
def test_password_case():
pass
def run_tests():
test_password_length()
test_password_numbers()
test_password_case()
if __name__=="__main__":
run_tests();
|
59b08bedd46f3c4ae4ddca84107f393cc3a3086c | kavikamal/PythonPractice | /rna-transcription/rna_transcription.py | 570 | 3.8125 | 4 | def to_rna(dna_strand):
dna_strand = dna_strand.upper()
rna_strand=""
for i in dna_strand:
if i=="G":
rna_strand = rna_strand + "C"
elif i=="C":
rna_strand = rna_strand + "G"
elif i=="T":
rna_strand = rna_strand + "A"
elif i=="A":
rna_strand = rna_strand + "U"
else:
try:
break
except ValueError:
print 'Invalid DNA strand.'
print rna_strand
return rna_strand
to_rna(raw_input('Enter dna_strand:'))
|
b31458154872a18e572992f676e0481c2c95192d | SebasBaquero/taller1-algoritmo | /uri_juego/punto1002.py | 68 | 3.734375 | 4 | r= float(input())
a= 3.14159*(r**2)
print("A="+'{:.4f}'.format(a))
|
9fb876bbed1ee65bde603cb7b7faae9e2f8d339b | judong93/TIL | /algorithm/0824~/0826/중위순회.py | 610 | 3.59375 | 4 | def inorder(n=1):
if n:
inorder(left[n])
print(word[n], end='')
inorder(right[n])
for tc in range(1, 11):
N = int(input())
arr = [list(input().split()) for _ in range(N)]
word = [0]
left = [0] * (N+1)
right = [0] * (N+1)
for i in arr:
word.append(i[1])
for i in arr:
if len(i) > 2:
for j in range(2, len(i)):
if left[int(i[0])] == 0:
left[int(i[0])] = int(i[j])
else:
right[int(i[0])] = int(i[j])
print(f'#{tc}', end= ' ')
inorder()
print()
|
ab993d54196604e168dadd5490ae44f0345500c6 | blairza/01-IntroductionToPython | /src/m6_your_turtles.py | 1,829 | 3.703125 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Zane Blair.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# DONE: 2.
# You should have RUN the m5e_loopy_turtles module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOU WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT-and-PUSH when you are done with this module.
#
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
window.delay(20)
stalin = rg.SimpleTurtle()
stalin.pen = rg.Pen('white',10)
stalin.left(90)
stalin.forward(100)
stalin.right(90)
stalin.pen = rg.Pen('red',10)
napoleon = rg.SimpleTurtle()
napoleon.pen = rg.Pen('white',10)
napoleon.left(90)
napoleon.forward(100)
napoleon.right(90)
napoleon.pen = rg.Pen('blue',10)
napoleon.right(180)
stalin.speed = 10
napoleon.speed = 10
for k in range(36):
stalin.forward(20)
napoleon.forward(20)
stalin.right(5)
napoleon.left(5)
stalin.forward(20)
napoleon.forward(20)
window.close_on_mouse_click() |
6d055210a9a31326f748511302d219d25ca7b6ab | bl4cklabel88/Network-Tools | /PycharmProjects/Password_Cracker/password_cracker_all.py | 2,477 | 3.625 | 4 | #!/usr/bin/env python
# Doesnt work right now....
import hashlib
counter = 1
available_hashes = hashlib.algorithms_available
pass_in = raw_input("Please enter the Hash: ")
hash_type = raw_input("From the following list: " + '\n' + str([
'md4',
'md5',
'sha1',
'sha224',
'sha384',
'sha256',
'sha512',
]).strip() + '\nPlease enter the Hash Type: ')
pwfile = raw_input("Please enter the password file name: ")
try:
pwfile = open(pwfile, 'r')
except IOError:
print('\nFile Not Found.')
quit()
for password in pwfile:
lowercase_hash_type = hash_type.lower()
if lowercase_hash_type in available_hashes:
if lowercase_hash_type == 'md5':
file_hash = hashlib.md5(str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
elif lowercase_hash_type == 'sha1':
file_hash = hashlib.sha1(str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
elif lowercase_hash_type == 'sha224':
file_hash = hashlib.sha224(
str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
elif lowercase_hash_type == 'sha256':
file_hash = hashlib.sha256(
str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
elif lowercase_hash_type == 'sha128':
file_hash = hashlib.sha128(
str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
elif lowercase_hash_type == 'sha384':
file_hash = hashlib.sha384(
str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
elif lowercase_hash_type == 'sha512':
file_hash = hashlib.sha512(
str(password).encode('utf-8')).hexdigest()
print(
'Trying password number %d: %s ' % (counter, password.strip()))
counter += 1
if pass_in == file_hash:
print('\nMatch Found. \nPassword is: %s' % password)
break
else:
print('\nPassword Not Found.')
|
c471bdf7f6e66dc14a661bec51eda019686b4572 | pars3c/model_weight_improvement_1 | /__main__.py | 1,053 | 3.890625 | 4 | import numpy as np
# learning rate value
learn_rate = 0.01
# Input pretended target
target_value = input("Insert the number value of your target: ")
# turn input str into integer
target_value = int(target_value)
# number of epochs
epochs = input("Insert the number of cicles( Remember, the more ammount of cicles you have, more accurate the result will be ): ")
# turn input str into integer
epochs = int(epochs)
# input data values
input_data = np.array([2,3])
# weight values
weights = np.array([3,4])
# predicted value (output value)
output_data = (input_data * weights).sum()
error = output_data - target_value
print("The error is: ",error)
print("First output value is: ",output_data)
# until the error is no longer non-existended
for x in range(0, epochs):
slope = 2 * input_data * error
weights = weights - ( learn_rate * slope )
output_data = (input_data * weights).sum()
error = output_data - target_value
print("The error is: ",error)
print("Predicted value is: ",output_data)
print("It worked") |
03c3b033e8ed361308fa763621355b975c214db1 | amanprakash9299/pythonacadview2 | /class 6/q3.py | 131 | 3.953125 | 4 | l=[]
for x in range(5):
l.append(int(input("enter the number:")))
print(l)
l1=[]
for x in range(5):
l1.append(l[x]**2)
print(l1) |
3aff6257c145cbe3d6bc5d4485125acd6309374d | evantoh/unittest | /contact_test.py | 3,635 | 3.703125 | 4 | import unittest # Import the unittest module
import pyperclip
from contact import Contact #Importing the contact Class
class TestContact(unittest.TestCase):
'''
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_contact = Contact("evans","Mwenda","0705861793","[email protected]") # create contact object
def test_init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_contact.first_name,"evans")
self.assertEqual(self.new_contact.last_name,"Mwenda")
self.assertEqual(self.new_contact.number,"0705861793")
self.assertEqual(self.new_contact.email,"[email protected]")
def test_save_contact(self):
'''
test_save_contact test case to test if the object is saved onto
the contact_list
'''
self.new_contact.save_contact() #saving the new contact
self.assertEqual(len(Contact.contact_list),1)
# third test
# setup and class creation up here
# setup and class creation up here
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
Contact.contact_list = []
def test_save_multiple_contact(self):
'''
test_save_multiple_contact to check if we save multiple contact_list
objects to our contact_list
'''
self.new_contact.save_contact()
test_contact=Contact("Test","user","0705861793","[email protected]")
test_contact.save_contact()
self.assertEqual(len(Contact.contact_list),2)
# foorth test
def test_delete_contact(self):
'''
test_delete_contact to test if we can remove a contact from contact_list
'''
self.new_contact.save_contact()
test_contact=Contact("Test","user","0705861793","[email protected]")
test_contact.save_contact()
self.new_contact.delete_contact()# Deleting a contact object
self.assertEqual(len(Contact.contact_list),1)
# fifth test
def test_find_contact_by_number(self):
'''
test to check if we can find a contact by phone number and display information
'''
self.new_contact.save_contact()
test_contact = Contact("Test","user","0705861793","[email protected]") # new contact
test_contact.save_contact()
found_contact = Contact.find_by_number("0705861793")
self.assertEqual(found_contact.email,test_contact.email)
def test_contact_exists(self):
'''
test to check if we can return a Boolean if we cannot find the
contact
'''
self.new_contact.save_contact()
test_contact=Contact("Test","user","0705861793","[email protected]")# add contact
test_contact.save_contact()
contact_exists=Contact.contact_exist("0705861793")
self.assertTrue(contact_exists)
def test_display_all_contacts(self):
'''
method that returns list the contact saved
'''
self.assertEqual(Contact.display_contacts(),Contact.contact_list)
def test_copy_email(self):
'''
Test to confirm that we are copying the email address from a found contact
'''
self.new_contact.save_contact()
Contact.copy_email("0705861793")
self.assertEqual(self.new_contact.email,pyperclip.paste())
if __name__ == '__main__':
unittest.main()
|
ddef8f70281c53b3c948d65a2a40b1df8f370e6e | dansmyers/IntroToCS | /Examples/2-Conditional_Execution/fortune.py | 742 | 4.0625 | 4 | """
Print a randomly chosen message each time the program is run.
"""
# Import the random function from the random module
from random import random
# Generate a random value in [0, 1)
r = random()
# Use r to choose one of the output options
if r < .20:
print("The course of true love never did run smooth. - A Midsummer Night's Dream: I, i")
elif r < .40:
print("We know what we are, but know not what we may be. - Hamlet: IV, v")
elif r < .60:
print("If music be the food of love, play on. - Twelfth Night: I, i")
elif r < .80:
print("Brevity is the soul of wit. - Hamlet: II, ii")
else:
print("We are such stuff as dreams are made on, and our little life is rounded with a sleep. - The Tempest: IV, i")
|
69f03aaefcca27e575021ce3b78ecf6b9ac799be | yatengLG/leetcode-python | /question_bank/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.py | 2,009 | 4 | 4 | # -*- coding: utf-8 -*-
# @Author : LG
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
执行用时:80 ms, 在所有 Python3 提交中击败了99.61% 的用户
内存消耗:17.7 MB, 在所有 Python3 提交中击败了86.69% 的用户
解题思路:
因为是二叉搜索树,左节点值必定小于右节点。
如果当前节点值处于俩个指定节点之间,则最近公共祖先必定为当前节点。
若不是,通过比较节点值,对树进行更新
"""
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
l_val, r_val = p.val, q.val
if l_val > r_val: # 确保指定节点值大小顺序
l_val, r_val = r_val, l_val
while True:
if l_val <= root.val <= r_val: # 当前节点处于指定两节点之间
return root
if root.val > r_val: # 当前节点小于指定节点最小值,更新当前节点为节点左子树
root = root.left
if root.val < l_val: #
root = root.right
"""
执行用时:88 ms, 在所有 Python3 提交中击败了95.71% 的用户
内存消耗:17.1 MB, 在所有 Python3 提交中击败了97.46% 的用户
解题思路:
递归
"""
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val > q.val:
p, q = q, p
def find(root, p, q):
if p.val <= root.val <= q.val: # 比较当前节点与p,q的值, 如果处于p,q之间,则返回
return root
elif root.val < p.val: # 如果当前节点值小于p,则遍历右子树
return find(root.right, p, q)
else: # 否则,遍历左子树
return find(root.left, p, q)
return find(root, p, q) |
628bdae5e9f30dd7eea6d4936f4a6048efa4ea6c | Catarina607/Python-Lessons | /exer02.py | 667 | 4 | 4 |
def do_n(n):
if n <= 0:
return
if n > 0:
print(n)
do_n(n - 1)
# do_n(n - 1)
def robot():
x = ''
while x != 'okay!':
x = input('can i have the control of the whole world ?'.lower())
if x != 'okay':
print('just say okay. '.lower())
if x == 'okay':
for i in range(3, 30, 3):
print("okay it's mine. . . ! ".upper())
for i in range(5):
row = y + '-'*5
y = '+'
x = '|'
column = x + ' '*5
print(row + y)
print(column + x)
robot() |
87f29e22fdb3f68ef94366543805b0578bdda3df | Alek-dr/GraphLib | /core/algorithms/connected_components.py | 1,301 | 3.515625 | 4 | from collections import deque
from typing import Generator, Set, Union
from core.graphs.graph import AbstractGraph, edge
def _dfs(
graph: AbstractGraph,
origin: Union[str, int],
target: Union[str, int] = None,
):
if (target is not None) and (not graph[target]):
raise Exception("There no target node in graph")
if origin == target:
return {origin}
stack = deque()
stack.append(edge(origin, origin, 0, None))
visited = set()
while stack:
curr_edge = stack.pop()
if curr_edge.dst not in visited:
visited.add(curr_edge.dst)
edges = [e for e in graph.get_adj_edges(curr_edge.dst)]
for e in reversed(edges):
if e.dst not in visited:
stack.append(e)
if target is not None:
return visited
edges.clear()
return visited
def connected_components(
graph: AbstractGraph,
) -> Generator[Set[Union[str, int]], None, None]:
"""
Return set of connected components
"""
visited = set()
for v in graph.vertexes:
if v.name not in visited:
connected = _dfs(graph, v.name)
for vertex in connected:
visited.add(vertex)
yield connected
|
c1b8fb35f3fe6c0acb4eeb8e2421f3a975c63dcc | Rafaheel/Curso-de-Python | /30-exercicio.py | 229 | 4.03125 | 4 | # programa deve ler se um numero é par ou ímpar
n = int(input("Digite um numero: "))
resultado = n % 2
if resultado == 0:
print(f"O numero escolhido é par")
else:
print(f"O numero escolhido é impar")
|
5ffdeb0b3078c85ac854422097275a7cb92e4088 | gomanish/Python | /basic/4th.py | 366 | 4.09375 | 4 | # Pig Latin problem
def piglatin(word):
first_letter = word[0]
if first_letter[0] in 'aeiou':
pigword = word + 'ay'
else:
pigword = word[1:] + first_letter + 'ay'
print(pigword)
''' if word start with vowel ,add 'ay' to end
if word do not start vowel ,put first letter at the end ,then add 'ay' '''
piglatin('apple') # function call
piglatin('word')
|
f3d28e76d47f52fec0742a76f37c75a16295bd20 | KVooys/AdventOfCode2015 | /day21.py | 10,205 | 3.5 | 4 | """
--- Day 21: RPG Simulator 20XX ---
Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller.
In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first. Each attack reduces the opponent's hit points by at least 1. The first character at or below 0 hit points loses.
Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defender's armor score. An attacker always does at least 1 damage. So, if the attacker has a damage score of 8, and the defender has an armor score of 3, the defender loses 5 hit points. If the defender had an armor score of 300, the defender would still lose 1 hit point.
Your damage score and armor score both start at zero. They can be increased by buying items in exchange for gold. You start with no items and have as much gold as you need. Your total damage or armor is equal to the sum of those stats from all of your items. You have 100 hit points.
Here is what the item shop is selling:
Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0
Armor: Cost Damage Armor
Leather 13 0 1
Chainmail 31 0 2
Splintmail 53 0 3
Bandedmail 75 0 4
Platemail 102 0 5
Rings: Cost Damage Armor
Damage +1 25 1 0
Damage +2 50 2 0
Damage +3 100 3 0
Defense +1 20 0 1
Defense +2 40 0 2
Defense +3 80 0 3
You must buy exactly one weapon; no dual-wielding. Armor is optional, but you can't use more than one. You can buy 0-2 rings (at most one for each hand). You must use any items you buy. The shop only has one of each item, so you can't buy, for example, two rings of Damage +3.
For example, suppose you have 8 hit points, 5 damage, and 5 armor, and that the boss has 12 hit points, 7 damage, and 2 armor:
The player deals 5-2 = 3 damage; the boss goes down to 9 hit points.
The boss deals 7-5 = 2 damage; the player goes down to 6 hit points.
The player deals 5-2 = 3 damage; the boss goes down to 6 hit points.
The boss deals 7-5 = 2 damage; the player goes down to 4 hit points.
The player deals 5-2 = 3 damage; the boss goes down to 3 hit points.
The boss deals 7-5 = 2 damage; the player goes down to 2 hit points.
The player deals 5-2 = 3 damage; the boss goes down to 0 hit points.
In this scenario, the player wins! (Barely.)
You have 100 hit points. The boss's actual stats are in your puzzle input. What is the least amount of gold you can spend and still win the fight?
"""
import re
import pprint
from collections import defaultdict
from dataclasses import dataclass
from itertools import combinations, product
# part 1: this will mostly involve parsing all the different inputs and finding weapon/armor/ring combinations in a sane way, then finding from the cheapest.
with open("input/day21.txt") as input_file:
inp = input_file.readlines()
RAW_WEAPONS = """
Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0
""".split("\n")
RAW_ARMOR = """
Armor: Cost Damage Armor
Leather 13 0 1
Chainmail 31 0 2
Splintmail 53 0 3
Bandedmail 75 0 4
Platemail 102 0 5
""".split("\n")
RAW_RINGS = """
Rings: Cost Damage Armor
Damage +1 25 1 0
Damage +2 50 2 0
Damage +3 100 3 0
Defense +1 20 0 1
Defense +2 40 0 2
Defense +3 80 0 3
""".split("\n")
SAMPLE_PLAYER = """
Hit Points: 8
Damage: 5
Armor: 5
""".split("\n")[1:-1]
SAMPLE_BOSS = """
Hit Points: 12
Damage: 7
Armor: 2
""".split("\n")[1:-1]
@dataclass
class Item:
name: str
cost: int
damage: int
armor: int
@dataclass
class Character:
HP: int = 100
damage: int = 0
armor: int = 0
def parse_items(items, item_dict):
# function to parse items into a dict
# Rings have slightly different syntax so the matching has an optional group which makes it look a bit messy
item_pattern = r"(\w+)\s(\+\d){0,1}\s+(\d+)\s+(\d+)\s+(\d+)"
# first line is blank, 2nd line is description, take first item & remove colon at the end
category = items[1].split(" ")[0][:-1]
for item in items[2:-1]:
m = re.match(item_pattern, item)
# special case for rings
if m.groups()[1] != None:
name = m.groups()[0] + " " + m.groups()[1]
else:
name = m.groups()[0]
cost, damage, armor = [int(i) for i in m.groups()[2:5]]
item_dict[category][name] = Item(name=name, cost=cost, damage=damage, armor=armor)
def parse_character(character):
HP, damage, armor = [int(line.split(": ")[1]) for line in character]
return Character(HP=HP, damage=damage, armor=armor)
# find combinations of items
def item_combos(item_dict, num_armor, num_rings):
for weapon in item_dict["Weapons"].keys():
# armor is optional
for armor in [c1 for c1 in combinations(item_dict["Armor"], num_armor)]:
# rings can be 0, 1 or 2
for rings in [c2 for c2 in combinations(item_dict["Rings"], num_rings)]:
combo_list.append((weapon, armor, rings))
def get_all_combos():
for num_armor in range(0, 2):
for num_rings in range(0, 3):
item_combos(item_dict, num_armor, num_rings)
# Predicting the fight outcome is actually not that hard, and simulating the entire fight is unnecessary
# There are 2 important stats: how many turns the player lives, and how many turns the boss lives.
# They are determined by their HP, damage and armor.
# Since the player gets to start, as long as they live >= x turns and the boss lives x turns or less, the player wins
def simulate_fight(this_player, this_boss):
# Each attack reduces the opponent's hit points by at least 1
player_turns = this_player.HP / max(1, (this_boss.damage - this_player.armor))
boss_turns = this_boss.HP / max(1, (this_player.damage - this_boss.armor))
# let's keep this function simple and just return True if the player wins
return player_turns >= boss_turns
def simulate_all_fights(combo_list, boss):
# some unrealistic number
lowest_cost = 10000
for weapon, armor, rings in combo_list:
# we start with an unequipped player every time
player = Character(HP=100, damage=0, armor=0)
# keep track of money spent
total_cost = 0
# first we "buff" the player by adding the item stats to theirs
current_weapon = item_dict["Weapons"][weapon]
player.damage += current_weapon.damage
total_cost += current_weapon.cost
if armor:
current_armor = item_dict["Armor"][armor[0]]
player.armor += current_armor.armor
total_cost += current_armor.cost
if rings:
for ring in rings:
current_ring = item_dict["Rings"][ring]
player.damage += current_ring.damage
player.armor += current_ring.armor
total_cost += current_ring.cost
# only simulate the fights if the cost might be the new lowest
if total_cost <= lowest_cost:
# print(player, weapon, armor, rings, total_cost)
# only register costs where the player wins
if simulate_fight(player, boss):
lowest_cost = min(total_cost, lowest_cost)
return lowest_cost
item_dict = defaultdict(dict)
combo_list = []
parse_items(RAW_WEAPONS, item_dict)
parse_items(RAW_ARMOR, item_dict)
parse_items(RAW_RINGS, item_dict)
# player = parse_character(SAMPLE_PLAYER)
# boss = parse_character(SAMPLE_BOSS)
real_boss = parse_character(inp)
get_all_combos()
print(simulate_all_fights(combo_list, real_boss))
"""
--- Part Two ---
Turns out the shopkeeper is working with the boss, and can persuade you to buy whatever items he wants. The other rules still apply, and he still only has one of each item.
What is the most amount of gold you can spend and still lose the fight?
"""
# part 2 can be solved by rewriting the simulate_all_fights function slightly to account for this newly introduced unfairness:
def simulate_all_unfair_fights(combo_list, boss):
highest_cost = 0
for weapon, armor, rings in combo_list:
# we start with an unequipped player every time
player = Character(HP=100, damage=0, armor=0)
# keep track of money spent
total_cost = 0
# first we "buff" the player by adding the item stats to theirs
current_weapon = item_dict["Weapons"][weapon]
player.damage += current_weapon.damage
total_cost += current_weapon.cost
if armor:
current_armor = item_dict["Armor"][armor[0]]
player.armor += current_armor.armor
total_cost += current_armor.cost
if rings:
for ring in rings:
current_ring = item_dict["Rings"][ring]
player.damage += current_ring.damage
player.armor += current_ring.armor
total_cost += current_ring.cost
# only simulate fights if the cost might be the new highest
if total_cost >= highest_cost:
# only register costs where the player loses
if not simulate_fight(player, boss):
highest_cost = max(total_cost, highest_cost)
return highest_cost
print(simulate_all_unfair_fights(combo_list, real_boss))
# Some food for (after)thought: using itertools.product could have been another way than to generate the combo_list
# They are the same speed, but the syntax would be slightly nicer
# something like this (still need to filter out duplicate rings and add None values to the armor and rings dicts)
# combo_list = [i for i in product(item_dict["Weapons"], item_dict["Armor"], item_dict["Rings"], item_dict["Rings"])]
|
85d5b95d660f4d035cb319f7bdd94f9953ddb24b | dhimanmonika/PythonCode | /Regex/Substring.py | 292 | 3.984375 | 4 | """You are given a string .
Your task is to find the indices of the start and end of string in ."""
import re
S,k=input(),input()
results= list(map(lambda x:(x.start(1),x.end(1)-1),re.finditer(r"(?=(%s))"%k,S)))
if results:
for x in results:
print(x)
else:
print("(-1, -1") |
63f444bb548d5f5e0342764419f31a5ba90ddf9d | steslic/markov_stock | /matrix_ops.py | 3,883 | 3.609375 | 4 | import numpy as np
import warnings
def swapRows(A, i, j):
"""
interchange two rows of A
operates on A in place
"""
tmp = A[i].copy()
A[i] = A[j]
A[j] = tmp
def relError(a, b):
"""
compute the relative error of a and b
"""
with warnings.catch_warnings():
warnings.simplefilter("error")
try:
return np.abs(a-b)/np.max(np.abs(np.array([a, b])))
except:
return 0.0
def rowReduce(A, i, j, pivot):
"""
reduce row j using row i with pivot pivot, in matrix A
operates on A in place
"""
factor = A[j][pivot] / A[i][pivot]
for k in range(len(A[j])):
# we allow an accumulation of error 100 times larger
# than a single computation
# this is crude but works for computations without a large
# dynamic range
if relError(A[j][k], factor * A[i][k]) < 100 * np.finfo('float').resolution:
A[j][k] = 0.0
else:
A[j][k] = A[j][k] - factor * A[i][k]
# stage 1 (forward elimination)
def forwardElimination(B):
"""
Return the row echelon form of B
"""
A = B.copy()
m, n = np.shape(A)
for i in range(m-1):
# Let lefmostNonZeroCol be the position of the leftmost nonzero value
# in row i or any row below it
leftmostNonZeroRow = m
leftmostNonZeroCol = n
## for each row below row i (including row i)
for h in range(i,m):
## search, starting from the left, for the first nonzero
for k in range(i,n):
if (A[h][k] != 0.0) and (k < leftmostNonZeroCol):
leftmostNonZeroRow = h
leftmostNonZeroCol = k
break
# if there is no such position, stop
if leftmostNonZeroRow == m:
break
# If the leftmostNonZeroCol in row i is zero, swap this row
# with a row below it
# to make that position nonzero. This creates a pivot in that position.
if (leftmostNonZeroRow > i):
swapRows(A, leftmostNonZeroRow, i)
# Use row reduction operations to create zeros in all positions
# below the pivot.
for h in range(i+1,m):
rowReduce(A, i, h, leftmostNonZeroCol)
return A
####################
# If any operation creates a row that is all zeros except the last element,
# the system is inconsistent; stop.
def inconsistentSystem(B):
"""
B is assumed to be in echelon form; return True if it represents
an inconsistent system, and False otherwise
"""
rows = len(B)
cols = len(B[0])
counter = 0
if B[rows - 1][cols - 1] != 0:
for i in range(0, cols - 1):
if B[rows - 1][i] == 0:
counter += 1
if counter == cols - 1:
return True # inconsistent
return False # consistent
def backsubstitution(B):
"""
return the reduced row echelon form matrix of B
"""
rows = len(B)
cols = len(B[0])
zrows = 0
# check for zero rows
for i in range(rows - 1, -1, -1):
tv = False
for j in range(cols):
if B[i][j] != 0:
tv = True
break
if tv == False:
zrows += 1
# divide each row by pivot
for i in range(rows - zrows):
for j in range(i + 1, cols):
B[i][j] = B[i][j] / B[i][i]
B[i][i] = B[i][i] / B[i][i] # get 1
# row reduction
for i in range(rows - zrows):
for j in range(cols):
if B[i][j] != 0:
pivot = j
break
for k in range(i - 1, -1, -1):
rowReduce(B, i, k, pivot)
return B |
6f58de063d077045a233b52849866d620d53f88e | TimWeiHu/Guess_number | /guess.py | 527 | 3.84375 | 4 | import random
m = input('請輸入數字範圍下限:')
M = input('請輸入數字範圍上限:')
m = int(m)
M = int(M)
num = random.randint(m, M)
count = 0
while True:
count = count + 1
print('')
print('第', count, '次')
guess = input('請猜數字:')
guess = int(guess)
if guess < num:
print('答案比', guess, '大')
elif guess > num:
print('答案比', guess, '小')
else:
print('終於猜對了!')
break
print('')
print('共猜了', count, '次')
|
ce4cd862f219633350a8837c87f5be75f8245905 | omakasekim/python_algorithm | /01_알고리즘 구현/알고리즘구현복습/정렬알고리즘들.py | 6,429 | 4.0625 | 4 | # 선택정렬
def selection_sort(list):
ans = []
while list:
min_value = list[0]
for num in list:
min_value = min(min_value, num)
ans.append(min_value)
list.remove(min_value)
return ans
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(selection_sort(array))
# Time Complexity: O(n^2)
# enumerate로 idx를 가져가면 remove 대신 del을 사용할 수 있긴하지만 둘 다 시간복잡도는 O(n^2)이므로 그냥 remove를 사용함
# 삽입정렬
def insertion_sort(list):
for i in range(0, len(list)):
while list[i - 1] > list[i] and i > 0:
list[i - 1], list[i] = list[i], list[i - 1]
i -= 1
return list
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(insertion_sort(array))
# Time Complexity: O(n^2)
# 합병정렬
def merge(list_1, list_2):
ans = []
while list_1 and list_2:
if list_1[0] < list_2[0]:
ans.append(list_1[0])
del list_1[0]
else:
ans.append(list_2[0])
del list_2[0]
ans += list_1 or list_2
return ans
def merge_sort(list):
if len(list) <= 1:
return list
else:
mid = len(list) // 2
return merge(merge_sort(list[:mid]), merge_sort(list[mid:]))
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(merge_sort(array))
# Time Complexity: O(n(lg(n)) 깊이(divide)가 lg(n)에 비례하고 각 깊이에서 합병은 n 이므로 nlg(n)
# 퀵 정렬
def partition(list):
pivot = list[-1]
small, big = [], []
for num in list[:-1]:
if num < pivot:
small.append(num)
else:
big.append(num)
return small + [pivot] + big, len(small)
def quick_sort(list):
if len(list) <= 1:
return list
else:
list, pivot_idx = partition(list)
return quick_sort(list[:pivot_idx]) + [list[pivot_idx]] + quick_sort(list[pivot_idx+1:])
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(quick_sort(array))
# Time Complexity: O(n(lg(n))
# 퀵 정렬 in-place 로
def partition_2(list, start, end):
i = start
b = start
pivot = list[end]
while i < end:
if list[i] < pivot:
list[i], list[b] = list[b], list[i]
b += 1
i += 1
list[b], list[end] = list[end], list[b]
return b
def quick_sort_2(list, start, end):
if end - start < 1:
return
else:
b = partition_2(list, start, end)
quick_sort_2(list, start, b - 1)
quick_sort_2(list, b + 1, end)
return list
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(quick_sort_2(array, 0, len(array) - 1))
# 역시 in-place는 어려워
# 힙 정렬
def heapify(tree, idx, tree_size):
left_child_idx = idx * 2
right_child_idx = idx * 2 + 1
max_idx = idx
if left_child_idx < tree_size:
if tree[max_idx] < tree[left_child_idx]:
max_idx = left_child_idx
if right_child_idx < tree_size:
if tree[max_idx] < tree[right_child_idx]:
max_idx = right_child_idx
if max_idx != idx:
tree[max_idx], tree[idx] = tree[idx], tree[max_idx]
heapify(tree, max_idx, tree_size)
def heapify_upward(tree, idx, tree_size):
parent_idx = idx // 2
if parent_idx > 0 and tree[parent_idx] > tree[idx]:
tree[parent_idx], tree[idx] = tree[idx], tree[parent_idx]
print(tree)
heapify_upward(tree, parent_idx, tree_size)
def insert(heap, num):
heap.append(num)
heap = [None] + heap
print(heap)
heap_size = len(heap)
heapify_upward(heap, heap_size-1, heap_size)
return heap[1:]
def heap_sort(tree):
tree_size = len(tree)
for i in range(tree_size-1, 0, -1):
heapify(tree, i, tree_size)
for i in range(tree_size-1, 1, -1):
tree[i], tree[1] = tree[1], tree[i]
heapify(tree, 1 ,i)
return tree[1:]
array = [None, 3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
sorted_arr = heap_sort(array)
print(sorted_arr)
# Time Complexity: 맨 아래 포문을 보면 heapify 의 시간복잡도 O(lg(n)) * 포문 O(n) = O(n * lg(n))
# 힙 정렬 헷갈려서 한번 더
def heapify_2(tree, idx, end):
left_child_idx = idx * 2
right_child_idx = idx * 2 + 1
max_idx = idx
if left_child_idx < end and tree[left_child_idx] > tree[max_idx]:
max_idx = left_child_idx
if right_child_idx < end and tree[right_child_idx] > tree[max_idx]:
max_idx = right_child_idx
if max_idx != idx:
tree[max_idx], tree[idx] = tree[idx], tree[max_idx]
heapify_2(tree, max_idx, end)
def heap_sort_2(tree):
tree = [None] + tree
tree_size = len(tree)
# 힙속성을 부여하는 작업
for i in range(tree_size - 1, 0, -1):
heapify_2(tree, i, tree_size)
for i in range(tree_size - 1, 1, -1):
tree[1], tree[i] = tree[i], tree[1]
heapify_2(tree, 1, i)
return tree[1:]
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(heap_sort_2(array))
# 힙한번만 더. 정렬되지 않았을 때는 힙피파이를 아래에서부터 진행해야 한다(힙속성을 갖출때) - 아직 힙이 아닌 부분트리와 비교해봤자 의미가 없기 때문
# 반대로 이미 힙 속성을 지닌 상태에서 루트와 리프를 바꾸고 루트인덱스에 대해서 위에서 아래로 힙피파이를 한번만 진행하는 것은 이미 나머지 부분 트리들이 힙속성을 갖춘 상태이기 때문
def heapify_3(tree, idx, end_idx):
left_child_idx = idx * 2
right_child_idx = idx * 2 + 1
max_idx = idx
if left_child_idx < end_idx and tree[max_idx] < tree[left_child_idx]:
max_idx = left_child_idx
if right_child_idx < end_idx and tree[max_idx] < tree[right_child_idx]:
max_idx = right_child_idx
if max_idx != idx:
tree[max_idx], tree[idx] = tree[idx], tree[max_idx]
heapify_3(tree, max_idx, end_idx)
def heap_sort_3(tree):
tree = [None] + tree
n = len(tree)
# 트리를 힙으로 만들자
for i in range(n-1, 0, -1):
heapify_3(tree, i, n-1)
# 힙정렬
for i in range(n-1, 1, -1):
tree[1], tree[i] = tree[i], tree[1]
heapify_3(tree, 1, i)
return tree[1:]
array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5]
print(heap_sort_3(array))
# 이제 완벽히 이해했다.
# Time Complexity: O(n*lg(n))
|
2aa6ddcf7fa852827846cbbea0a9fd49a3017d47 | JuyeoungJun/algorithm | /pretest/SamsungTest1.py | 1,400 | 3.65625 | 4 | #def dfs(graph, start, goal):
def dfs_paths(graph, start, goal):
st = []
st = st+graph[start]
visit = []
while st:
a = st.pop()
if a == goal:
return 1
if a not in visit:
visit.append(a)
st.extend(graph[a])
return 0
def bfs(graph, start_node):
visit = list()
queue = list()
queue.append(start_node)
while queue:
node = queue.pop(0)
if node not in visit:
visit.append(node)
queue.extend(graph[node])
return visit
def dfs(graph, start_node):
visit = list()
stack = list()
stack.append(start_node)
while stack:
node = stack.pop()
if node not in visit:
visit.append(node)
stack.extend(graph[node])
return visit
if __name__ == "__main__":
n = int(input())
mapp = dict()
for i in range(n):
mapp[i] = list()
flag = 0
temp = input()
temp = temp.split()
temp = list(map(int,temp))
for j in range(len(temp)):
if temp[j] == 1:
mapp[i].append(j)
flag = 0
#print(mapp)
for i in range(n):
for j in range(n):
if dfs_paths(mapp, i, j) == 1:
print("1 ",end = '')
else:
print("0 ", end= '')
print('\n',end = '')
|
011a019a4f4096149d6f3315fb239903942b2af8 | higashigawa/add_password | /add_password.py | 193 | 3.640625 | 4 | import string
import random
chars = string.ascii_letters + string.digits
#print(random.choice(chars))
n = 8
s = ''
mystr = s.join([random.choice(chars) for i in range(n)])
print(mystr)
|
9f3b93d324c3a9a38f7c5e5d0ed846e2a5cbf86e | vpc20/python-misc | /FlattenGenerator.py | 514 | 3.921875 | 4 | # def flatten(lst):
# for item in lst:
# if isinstance(item, list):
# for i in flatten(item):
# yield i
# else:
# yield item
def flatten(lst):
for e in lst:
if isinstance(e, list):
yield from flatten(e)
else:
yield e
# list_of_lists = [1, 2]
# list_of_lists = [[1, 2], 3]
# list_of_lists = [[1, 2], [3, 4], [5, [6, 7]]]
list_of_lists = [[1, 2], [3, 4], [5, 6, [7, 8]]]
print(list(flatten(list_of_lists)))
|
e0718c4da08f34fa622e4f2ec51ba0f199c25992 | DylanPerdigao/TreesDataStructures | /LinkedList.py | 3,372 | 3.75 | 4 | #!/usr/local/bin/python3.8
# -*- coding: utf-8 -*-
import sys
import os
import re
import time
import random
class Node(object):
def __init__(self, word, line):
self.word = word
self.line = [line]
self.right = None
class LinkedList(object):
def insert(self, root, word, line):
if root == None:
return Node(word,line)
elif root.word < word:
root.right = self.insert(root.right,word,line)
elif root.word > word:
aux = root
root = Node(word,line)
root.right = aux
else:
if line not in root.line:
root.line.append(line)
return root
def search(self,root,word):
if root == None:
return None
elif root.word < word:
return self.search(root.right,word)
elif root.word > word:
return None
else:
return root
def readText(src,LL,root):
with open(src,'r',encoding="utf-8") as f:
i=0
for line in f:
newLine = re.sub('[(),;.""'']','',line)
for word in newLine.upper().split():
root=LL.insert(root,word,i)
i+=1
return LL,root
def showLines(instructions,LL,root):
if len(instructions)==2:
r = LL.search(root,instructions[1])
if r == None:
sys.stdout.write("-1\n")
else:
i=0
for l in r.line:
if instructions[0] != None:
i+=1
if i < len(r.line):
sys.stdout.write(str(l)+" ")
else:
sys.stdout.write(str(l)+"\n")
def showAssoc(instructions,LL,root):
if root != None and len(instructions)==3 and instructions[2].isnumeric():
target = instructions[1]
lineNumber = int(instructions[2])
r = LL.search(root,target)
if r != None and lineNumber in r.line:
if instructions[0] != None:
sys.stdout.write("ENCONTRADA.\n")
else:
if instructions[0] != None:
sys.stdout.write("NAO ENCONTRADA.\n")
def selectRandomWords(src,n):
words = list()
line = list()
with open(src,'r',encoding="utf-8") as f:
lines = f.readlines()
for i in range(n):
k = str()
while k == '\n' or k == '':
k = random.choice(lines)
line = re.sub('[(),;.""'']','',k).upper().split()
word = random.choice(line)
words.append(word)
return words,random.randint(0,len(lines))
def stats_LinkedList(PATH,textName,iterLINHAS,iterASSOC,iterations):
print(" ▶︎ LinkedList:")
null = None
instructions = list()
root = None
LL = LinkedList()
instructions.append(None)
for i in range(iterations):
root = None
LL = LinkedList()
times = list()
t = time.process_time()
LL,root = readText(PATH+textName,LL,root)
times.append(time.process_time()-t)
print("\tAVERAGE INSERT TIME: {}".format(sum(times)*1000/len(times)))
for i in range(iterations):
words,null = selectRandomWords(PATH+textName,iterLINHAS)
times = list()
t = time.process_time()
for word in words:
if len(instructions) == 1:
instructions.append(word)
else:
instructions[1] = word
showLines(instructions, LL, root)
times.append(time.process_time()-t)
print("\tAVERAGE LINHAS TIME: {}".format(sum(times)*1000/len(times)))
for i in range(iterations):
words,line = selectRandomWords(PATH+textName,iterASSOC)
times = list()
t = time.process_time()
for word in words:
if len(instructions) == 2:
instructions[1] = word
instructions.append(str(line))
else:
instructions[1] = word
showAssoc(instructions, LL, root)
times.append(time.process_time()-t)
print("\tAVERAGE ASSOC TIME: {}\n".format(sum(times)*1000/len(times)))
|
a394501e390797b6659d7b0a2cd4db644fd627a1 | picuzzo2/Lab101and103 | /Lab9/Lab09_1_600510532.py | 657 | 3.5625 | 4 | #600510532 SEC1
def main():
n = int(input())
square_frame(n,sep = ' ')
def square_frame(n, sep=' '):
start = 1
stop = (n*n) - (n-2)*(n-2)
for i in range(n-1):
print('%02d'%start,end='')
print(sep,end='')
start += 1
print('%02d'%start)
start+=1
for i in range(n-2):
print('%02d'%stop,end='')
for i in range((3*n)-5):
print(sep,end='')
print('%02d'%start)
start += 1
stop -= 1
for i in range(n-1):
print('%02d'%stop,end='')
print(sep,end='')
stop -= 1
print('%02d'%stop)
if __name__ == '__main__':
main() |
862ada0946b8057ccf30bb2170451b64fb23229b | Jane-Zhai/target_offer | /eg_47_gift.py | 1,346 | 3.546875 | 4 | """
在一个mxn的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于0),你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格,直到到达棋盘的右下角。给定一个棋盘及其上面的礼物,请计算你最多能拿多少价值的礼物?
解题思路:这是一个典型的能用动态规划解决的问题。
定义f(i,j)表示到达坐标(i,j)的格子能拿到的礼物总和的最大值。则f(i,j)=max(f(i-1,j),f(i,j-1))+gift(i,j) 利用循环写代码较为高效。
"""
def maxGift(array, row, col):
if array==[] or row<=0 or col<=0:
return 0
# temp = [0 for i in range(col)]
# for i in range(row):
# for j in range(col):
# up = 0
# left = 0
# if i>0:
# up = temp[j]
# if j>0:
# left = temp[j-1]
# temp[j] = max(up,left) + array[i*col+j]
# return temp[-1]
temp = [0]*col
up = 0
for i in range(row):
for j in range(col):
left = 0
if i>0:
up = temp[j]
if j>0:
left = temp[j-1]
temp[j] = max(up,left) + array[i*col+j]
return temp[-1]
print(maxGift([1,10,3,8,12,2,9,6,5,7,4,11,3,7,16,5],4,4))
|
2a089e1d341415edea70a862e0bdb75b9eeb20e8 | etrochim/Project-Euler | /problem41.py | 708 | 3.859375 | 4 | #!/usr/bin/env python
def eratosthenes_sieve(n):
# Create a candidate list within which non-primes will be
# marked as None; only candidates below sqrt(n) need be checked.
candidates = list(range(n+1))
fin = int(n**0.5)
# Loop over the candidates, marking out each multiple.
for i in xrange(2, fin+1):
if candidates[i]:
candidates[2*i::i] = [None] * (n//i - 1)
# Filter out non-primes and return the list.
return [i for i in candidates[2:] if i]
def is_pandigital(n):
return set(str(n)) == set([str(i) for i in range(1, len(str(n))+1)])
for i in reversed(eratosthenes_sieve(100000000)):
if is_pandigital(i):
print "Found %d" % i
break
|
630ce3ca780f6143e0f3f251bab264cfcdfdda98 | FibreBit/Computer-Applications | /Year 3/CA314 OO Analysis and Design/src/Rack.py | 1,766 | 3.5625 | 4 | from Board import *
import pygame
import random
class GameObject:
"""
Parent class
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def update(self):
pass
def draw(self):
pass
class Rack(GameObject):
"""
Class to create the rack
"""
def __init__(self, board, rack_size, bag, x=0, y=0):
super().__init__(x, y)
self.board = board
self.rack_size = rack_size
self.components = []
self.bag = bag
# self.rack_list in the old money
self.tiles = []
# To check if letter is being dragged
self.dragging = None
def start(self):
"""
Function to start the rack
"""
self.fill_rack()
# For loop to space the tiles in rack out side by side
for i in range(len(self.components)):
self.components[i].x = i*50 + self.x
# Taken from V1.0
def fill_rack(self):
# Calculate amount of tiles needed for full rack
missing_tiles = self.rack_size - len(self.tiles)
# Get tiles from bag
new_tiles = self.bag.get_tiles(missing_tiles)
# Add tiles to rack
for tile in new_tiles:
self.add_tile(tile[0], tile[1])
def add_tile(self, tile, value):
# Add tiles to rack
self.tiles.append(tile)
# Add tiles to components
self.components.append(Tile(self, tile, value, 40, 40, self.x, self.y))
def update(self):
for c in self.components:
c.update()
def draw(self, game_display):
for c in self.components:
c.draw(game_display)
def drop_tile(self, tile):
self.dragging = None
dropped = self.board.add_tile(tile) |
b5a4eae2c533e520b0dc97919cfc863569ff9262 | noym94/noy_repo | /openUni/Data_structures_and_Algorithms/maman14.py | 2,363 | 3.640625 | 4 | import mmh3
import sys
from nodes import SingleLinkedList
from nodes import ListNode
def main():
# get m and K fro the user
global m
global K
global T
m = int(input("Insert the value of m: \n"))
K = int(input("Insert the value of K: \n"))
# initialize T array
T = [{"Key": 0, "Value": SingleLinkedList()} for _ in range(m)]
# Open the file for object to insert into the data structure
insert()
# Open file for objects to search
lookups = open("lookup.txt", "r").readline().split(",")
for object in lookups:
search(object)
# Print T table and liked lists for debug. If needed, un-comment the following for loop
# for i in range(m):
# print('table index is: '+ str(i) + '\n')
# print('key is: ' + str(T[i]['Key']) + '\n')
# print('valus is: ' + str(T[i]['Value'].output_list()) + '\n')
def insert():
# This function opens inputs.txt file and for each object in it runs the runHAshFunctions()
print("Inserting objects to the data structure...\n")
inputs = open("inputs.txt", "r").readline().split(",")
for input in inputs:
runHashFunctions(input)
def search(object):
# This function checks if the object is in the data structure
print('Searching for ' + object + ' in the data structure...\n')
for i in range(K):
indexInT=int(mmh3.hash(object, i, signed=True) % m)
if T[indexInT]['Key'] == 0:
print('The object: ' + object + '\n' + 'is not part of the data structure.\n')
return
print('The object: ' + object + '\n' + 'is part of the data structure.\n')
def runHashFunctions(object):
# This function runs K hashing functions and runs updateTable() with each output
for i in range(K):
indexInT=int(mmh3.hash(object, i, signed=True) % m)
try:
updateTable(object, indexInT)
except:
print("Index is out of range of the Hash Table")
def updateTable(object, index):
# This function updates the T array with objects that are inserted to it
node = ListNode(object) # create a node with the value of the object
T[index]['Key'] = 1 # update 'Key' to 1
T[index]['Value'].add_list_item(node) # add item to the linked list in the 'Value'
if __name__ == "__main__":
main()
|
a299f09fc986a558bd56b8c76757d694948bda9d | garimasinghgryffindor/holbertonschool-machine_learning | /supervised_learning/0x11-attention/11-transformer.py | 2,156 | 3.53125 | 4 | #!/usr/bin/env python3
"""
Creates encoder for transformer
"""
import tensorflow as tf
Encoder = __import__('9-transformer_encoder').Encoder
Decoder = __import__('10-transformer_decoder').Decoder
class Transformer(tf.keras.layers.Layer):
"""
Class to create an encoder for a transformer
"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab,
max_seq_input, max_seq_target, drop_rate=0.1):
"""
Class constructor
:param dm: an integer representing the dimensionality of the model
:param h: an integer representing the number of heads
:param hidden: the number of hidden units in the fully connected layer
:param drop_rate: the dropout rate
"""
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab,
max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab,
max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
def call(self, inputs, target, training, encoder_mask, look_ahead_mask,
decoder_mask):
"""
Function to create the decoder block for the transformer
:param x: a tensor of shape (batch, target_seq_len, dm)containing the
input to the decoder block
:param encoder_output: a tensor of shape (batch, input_seq_len, dm)
containing the output of the encoder
:param training: a boolean to determine if the model is training
:param look_ahead_mask: the mask to be applied to the first multi
head attention layer
:param padding_mask: the mask to be applied to the second multi head
attention layer
:return: a tensor of shape (batch, target_seq_len, dm) containing
the block’s output
"""
enc_output = self.encoder(inputs, training, encoder_mask)
dec_output = self.decoder(target, enc_output, training,
look_ahead_mask, decoder_mask)
output = self.linear(dec_output)
return output
|
00de4f55ab4384d085f423a248e9e894049a51f5 | Al153/Programming | /CPU 10/Original Python Emulator/Memory.py | 1,516 | 3.859375 | 4 | def append_bytes(byte_list):
"""converts a list of bytes (such as on a bus) to a binary value"""
result = 0
for byte in byte_list:
result<<=8
result += byte
return result
def bytify(binary):
"""turns a number into bytes"""
bytes = [0,0,0,0]
i = 3
while binary:
bytes[i] = binary&255
binary >>= 8
i -= 1
return bytes
class Memory:
def __init__(self,Address_bus,Data_bus,memory_dict):
self.memory_dict = memory_dict
self.Address_bus = Address_bus
self.Data_bus = Data_bus
def set(self):
address = self.Address_bus.data
bytes = bytify(self.Data_bus.data)
for i in xrange(4):
self.memory_dict[(address+i)&4294967295] = bytes[i]
def enable(self):
address = self.Address_bus.data
bytes = [0,0,0,0]
for i in xrange(4):
bytes[i] = self.memory_dict.get((address+i)&4294967295,0)
self.Data_bus.data = append_bytes(bytes)
def byte_set(self):
address = self.Address_bus.data
self.memory_dict[self.Address_bus.data] = self.Data_bus.data&255
def byte_enable(self):
self.Data_bus.data = self.memory_dict.get(self.Address_bus.data,0)
def word_set(self):
high_byte, low_byte = (self.Data_bus.data>>8)&255,self.Data_bus.data&255
self.memory_dict[self.Address_bus.data] = high_byte
self.memory_dict[(self.Address_bus.data+1)&4294967295] = low_byte
def word_enable(self):
high_byte = self.memory_dict.get(self.Address_bus.data,0)
low_byte = self.memory_dict.get((self.Address_bus.data+1)&4294967295,0)
self.Data_bus.data = (high_byte<<8)+low_byte |
87fe801e002f882982bd77b8a6a90532a027cbd8 | xtreia/pythonBrasilExercicios | /02_EstruturasDecisao/09_ordem_descrescente.py | 581 | 4.0625 | 4 | num1 = int(raw_input('Informe um numero: '))
num2 = int(raw_input('Informe outro numero: '))
num3 = int(raw_input('Informe mais um numero: '))
if (num1 >= num2) and (num1 >= num3):
print num1
if (num2 >= num3):
print num2
print num3
else:
print num3
print num2
elif (num2 >= num3):
print num2
if (num1 >= num3):
print num1
print num3
else:
print num3
print num1
else:
print num3
if (num1 >= num2):
print num1
print num2
else:
print num2
print num1
|
b4c90bedfbe45457d3364be29dace775ab856200 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2640/60705/258421.py | 483 | 3.546875 | 4 | def contains(a, b):
for i in range(0, len(b)):
if b[i] not in a:
return False
return True
s = input()
t = input()
sub = []
for i in range(0, len(s)):
for j in range(i+1, len(s)+1):
if contains(s[i:j], t):
sub.append(s[i:j])
if len(sub) == 0:
print("")
else:
m = len(sub[0])
index = 0
for i in range(0, len(sub)):
if len(sub[i]) < m:
m = len(sub[i])
index = i
print(sub[index])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.