blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
603ca9e3c1b50f264b96b648794cd5ea2f5c7576
|
shinan0/python2
|
/约瑟夫环问题.py
| 1,574 | 4 | 4 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
def move(players,step):
#移动step前的元素到列表末尾
#将如何step的元素从列表中删除
num = step - 1
while num > 0:
tmp = players.pop(0)
players.append(tmp)
num = num - 1
return players #根据step做了元素的移动
def play(players,step,alive):
"""
模拟约瑟夫问题的函数。
Input:
players:参加游戏的人数;
step;数到step函数的人数淘汰;
alive:幸存人数,即游戏结束。
Output:
返回一个列表,列表中元素为幸存者的编号。
"""
#生成一个列表,从[1,...,piayers]
list1=[i for i in range(1,players+1)]
#进入游戏的循环,每次数到step淘汰,step之前的元素移动到列表末尾
#游戏结束的条件,列表剩余人数小于alive
while len(list1) > alive:
#移动step前的元素到列表末尾
#将如何step的元素从列表中删除
# num = step - 1
# while num > 0:
# tmp = list1.pop(0)
# list1.append(tmp)
# num = num - 1
list1=move(list1, step)
list1.pop(0) #此时的step的元素在列表第一个位置,使用pop(0)从列表中删除
return list1
players_num=int(input("请输入参与游戏的人数 "))
step_num=int(input("请输入淘汰的数字 "))
alive_num=int(input("请输入幸存的人数 "))
alive_list=play(players_num, step_num, alive_num)
print(alive_list)
# In[ ]:
|
62bc3309b00d22adaaae76c3cd1cc333b96d5237
|
jinshah-bs/Function_2
|
/Test_19.1_Class_HW_Shapes_jb.py
| 1,324 | 3.828125 | 4 |
import math
class Shapes:
def __init__(self, name, a, b=1.0):
self.name = name
self.dim1 = a
self.dim2 = b
self.area = 0
self.perimeter = 0
self.calc_prop()
def calc_prop(self):
if self.name.casefold() == "circle":
self.area = math.pi * math.pow(self.dim1, 2) * (self.dim2 / 360)
self.perimeter = 2 * math.pi * self.dim1 * (self.dim2 / 360)
elif self.name.casefold() == "square":
self.area = self.dim1 * self.dim1
self.perimeter = 2 * (self.dim1 + self.dim1)
elif self.name.casefold() == "rectangle":
self.area = self.dim1 * self.dim2
self.perimeter = 2 * (self.dim1 + self.dim2)
def print_prop(self):
print("The area of the given {0} is {1:.1f}".format(self.name, self.area))
print("The perimeter of the given {0} is {1:.1f}".format(self.name, self.perimeter))
# circle = Shapes("circle", 10.0,360)
# circle.print_prop()
semicircle = Shapes("Circle", 10.0, 180)
semicircle.print_prop()
print()
# qua_circle = Shapes("Circle", 10.0,90)
# qua_circle.print_prop()
square = Shapes("square", 10.2)
square.print_prop()
print()
rect = Shapes("Rectangle", 20.5, 10.4)
rect.print_prop()
print()
|
6475c1db8e5799bf132d30fd6b795d54809c373c
|
sam1208318697/Leetcode
|
/Leetcode_env/2019/8_24/Powerful_Integers.py
| 2,253 | 3.734375 | 4 |
# 970.强整数
# 给定两个正整数x和y,如果某一整数等于x ^ i + y ^ j,其中整数i >= 0且j >= 0,那么我们认为该整数是一个强整数。
# 返回值小于或等于bound的所有强整数组成的列表。
# 你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。
# 示例1:
# 输入:x = 2, y = 3, bound = 10
# 输出:[2, 3, 4, 5, 7, 9, 10]
# 解释:
# 2 = 2 ^ 0 + 3 ^ 0
# 3 = 2 ^ 1 + 3 ^ 0
# 4 = 2 ^ 0 + 3 ^ 1
# 5 = 2 ^ 1 + 3 ^ 1
# 7 = 2 ^ 2 + 3 ^ 1
# 9 = 2 ^ 3 + 3 ^ 0
# 10 = 2 ^ 0 + 3 ^ 2
# 示例2:
# 输入:x = 3, y = 5, bound = 15
# 输出:[2, 4, 6, 8, 10, 14]
# 提示:
# 1 <= x <= 100
# 1 <= y <= 100
# 0 <= bound <= 10 ^ 6
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int):
if x == y == 1:
if bound >= 2:
return [2]
else:
return []
elif x>1 and y==1:
res = []
i = 0
flag = True
while flag:
cur = x**i + 1
if cur <= bound:
res.append(cur)
i = i + 1
else:
flag = False
return sorted(set(res))
elif x==1 and y>1:
res = []
i = 0
flag = True
while flag:
cur = 1 + y**i
if cur <= bound:
res.append(cur)
i = i + 1
else:
flag = False
return sorted(set(res))
else:
res = []
flagI = True
i = 0
while flagI:
j = 0
flagJ = True
if x**i + y**j <= bound:
while flagJ:
cur = x**i + y**j
if cur <= bound:
res.append(cur)
j = j + 1
else:
flagJ = False
i = i + 1
else:
flagI = False
return sorted(set(res))
sol = Solution()
print(sol.powerfulIntegers(1,2,2))
|
05cb6a1952bb13b27e4989a9c452a69f809d2d45
|
mba811/mkdocs
|
/mkdocs/toc.py
| 2,536 | 3.609375 | 4 |
# coding: utf-8
"""
Deals with generating the per-page table of contents.
For the sake of simplicity we use an existing markdown extension to generate
an HTML table of contents, and then parse that into the underlying data.
The steps we take to generate a table of contents are:
* Pre-process the markdown, injecting a [TOC] marker.
* Generate HTML from markdown.
* Post-process the HTML, spliting the content and the table of contents.
* Parse table of contents HTML into the underlying data structure.
"""
import re
TOC_LINK_REGEX = re.compile('<a href=["]([^"]*)["]>([^<]*)</a>')
class TableOfContents(object):
"""
Represents the table of contents for a given page.
"""
def __init__(self, html):
self.items = _parse_html_table_of_contents(html)
def __iter__(self):
return iter(self.items)
def __str__(self):
return ''.join([str(item) for item in self])
class AnchorLink(object):
"""
A single entry in the table of contents.
"""
def __init__(self, title, url):
self.title, self.url = title, url
self.children = []
def __str__(self):
return self._indent_print()
def _indent_print(self, depth=0):
indent = ' ' * depth
ret = '%s%s - %s\n' % (indent, self.title, self.url)
for item in self.children:
ret += item._indent_print(depth + 1)
return ret
def _parse_html_table_of_contents(html):
"""
Given a table of contents string that has been automatically generated by
the markdown library, parse it into a tree of AnchorLink instances.
Returns a list of all the parent AnchorLink instances.
"""
lines = html.splitlines()[2:-2]
parents = []
ret = []
for line in lines:
match = TOC_LINK_REGEX.search(line)
if match:
href, title = match.groups()
nav = AnchorLink(title, href)
# Add the item to its parent if required. If it is a topmost
# item then instead append it to our return value.
if parents:
parents[-1].children.append(nav)
else:
ret.append(nav)
# If this item has children, store it as the current parent
if line.endswith('<ul>'):
parents.append(nav)
elif line.startswith('</ul>'):
if parents:
parents.pop()
# For the table of contents, always mark the first element as active
if ret:
ret[0].active = True
return ret
|
6c69dd20c5cb0610d16a46d4ce0b7590530dbc49
|
hidayatkhan013/Numpy-and-Pandas
|
/CS 160 Assignment/Question 1/part2.py
| 248 | 3.921875 | 4 |
import numpy as np
ndarray = np.random.randint(1, 27, size=(3, 3, 3))
print(ndarray )
print("Sum of all elements : \n",np.sum(ndarray))
print("Sum of each column: \n",np.sum(ndarray, axis=1))
print("Sum of each row: \n",np.sum(ndarray, axis=2))
|
31ae39d2c2882972396a6a8baf33806bdfaab803
|
shvechikov/algorithms_area
|
/solutions/leonid.py
| 521 | 3.65625 | 4 |
def solve(rectangles):
if not rectangles:
return 0
area = 0
x_points = set()
for start, end, height in rectangles:
x_points.add(start)
x_points.add(end)
x_points = sorted(x_points)
prev_x = x_points[0]
for x in x_points:
max_height = 0
for x1, x2, height in rectangles:
if x1 < x <= x2:
max_height = max(max_height, height)
width = x - prev_x
area += width * max_height
prev_x = x
return area
|
31fcde0cab1ad2ba5fdac68933edb79b02ffda3c
|
araujocristian/progrmas-python
|
/zumbiTWP272_2.py
| 138 | 3.78125 | 4 |
vetor = []
i = 1
while i<=10:
n = int(input("Numero: "))
vetor.append(n)
i+=1
print ("Vetor é:", vetor[::-1])
|
f0770a23527912903b74800b924bb9330a86d167
|
elijahdaniel/Graphs
|
/projects/graph/util.py
| 946 | 4.1875 | 4 |
# Note: This Queue class is sub-optimal. Why?
# for queue we're appending, so we're backing this with an array so we
# enqueue: append (goes to the back)
# comes in from the right to come out to the left
# so when we pop from the left in a queue (first),
# it's addressing right at that exact spot (chunk of cells in one slot of memory)
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
class Stack():
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
|
8f8b4a9df200987b6fa5ce755f5061c2ce349883
|
jliberacki/Jason-Drawer
|
/main.py
| 813 | 3.59375 | 4 |
import sys
import argparse
from os import path
import json
from drawer import draw
def main():
if len(sys.argv) < 2: raise Exception("Please provide json file")
argparser = argparse.ArgumentParser(description='Parse and draw from json')
argparser.add_argument('input', help='path to json')
argparser.add_argument('-o', '--output', help='Optional png file to save image')
args = argparser.parse_args()
# print(args.input)
# print(args.output)
if not path.isfile(args.input): raise Exception("Input file does not exist")
with open(args.input) as input_file:
data = json.load(input_file)
Figures = data["Figures"]
Screen = data["Screen"]
Palette = data["Palette"]
draw(Figures,Screen,Palette,args.output)
if __name__ == "__main__":
main()
|
57e71ce11dda1ee129bf4f15e4e134020ec39f69
|
hamologist/HackerRank
|
/algorithms/implementation/medium/count-triplets-1/main.py
| 832 | 3.765625 | 4 |
import fileinput
import os
from typing import Dict, Iterator, List
def count_triplets(nums: List[int], r: int) -> int:
triplets = 0
num_map: Dict[int, int] = {}
r_map: Dict[int, int] = {}
for num in reversed(nums):
jump = r * num
r_count = r_map.get(jump)
if r_count:
triplets += r_count
num_count = num_map.get(jump)
if num_count:
r_map[num] = r_map.get(num, 0) + num_count
num_map[num] = num_map.get(num, 0) + 1
return triplets
if __name__ == '__main__':
_user_input: Iterator[str] = fileinput.input()
_, _r = [int(num) for num in next(_user_input).split(' ')]
_nums = [int(num) for num in next(_user_input).split(' ')]
output = open(os.getenv('OUTPUT_PATH'), 'w')
output.write(str(count_triplets(_nums, _r)))
|
6bddf86da70647116d1fa90ec52eb7b299b7800d
|
heschmidt04/working-examples
|
/scripts/python/suitcase.py
| 599 | 4.03125 | 4 |
suitcase = []
suitcase.append("sunglasses")
# Your code here!
suitcase.append("shampoo")
suitcase.append("undies")
suitcase.append("shirts")
list_length = len(suitcase)
# Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase
# This is slicing the list
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
# The first and second items (index zero and one)
first = suitcase[0:2]
# Third and fourth items (index two and three)
middle = suitcase[2:4]
# The last two items (index four and five)
last = suitcase[4:6]
|
66cbce13c0ef8a4d4d10dc36a2012d526d3a6b50
|
G00398258/myWork
|
/Week07/messingWithFiles.py
| 348 | 3.875 | 4 |
# Week 07 lab - Write a function that reads in a number from a file that already exists(count.txt)
# test the program by calling the function and outputting the number
# Author: Gillian Kane-McLoughlin
fileName = "count.txt"
def readNumber():
with open(fileName, "rt") as f:
number = int(f.read())
return number
num = readNumber()
print (num)
|
f8b34a02c37cfcfaf16dfacae6f63583bc4a4606
|
ArielArT/Python-for-everyone
|
/PY4E_Exercise_11.py
| 1,924 | 3.5625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 20:13:41 2019
@author: Zakochani
Write a simple program to simulate the operation of the grep command on Unix.
Ask the user to enter a regular expression and count the number of lines that
matched the regular expression:
$ python grep.py
"""
import re
# dane od uzytkownika
plik = input("Enter file name:")
try:
file = open(plik)
except:
print("wrong name")
exit()
szukaj = input("Enter expresion :")
#szukanie i liczenie lini z fraza
count =0
for line in file:
if re.search(szukaj,line):
count = count +1
print(plik , "had" , count, "lines that matched",szukaj)
#%% Exercise 11.2 Nie kumam co mam szukać ?
"""
Write a program to look for lines of the form
"""
import re
# dane od uzytkownika
plik = input("Enter file name:")
try:
file = open(plik)
except:
print("wrong name")
exit()
szukaj =
#szukanie i liczenie lini z fraza
count =0
for line in file:
if re.search(szukaj,line):
count = count +1
print(plik , "had" , count, "lines that matched",szukaj)
#%% 11.3
"""
Extract the number from each of the lines using a regular expression and
the findall() method. Compute the average of the numbers and print
out the average
"""
import re
lista=list()
znalazl = None
suma1 =0
suma2 = 0
suma = 0
count = 0
# dane od uzytkownika
plik = input("Enter file name:")
try:
file = open(plik)
except:
print("wrong name")
exit()
for line in file:
znalazl = re.findall(r"\d+",line)
lista.append(znalazl)
for line in lista:
if line == []:
continue
elif len(line) < 2:
liczba = float(line[0])
suma1 = suma1 + liczba
count = count +1
elif len(line) > 1:
for lb in line:
liczba = float(lb)
suma2 = suma2 + liczba
count = count +1
suma = suma1 + suma2
print(suma)
|
e6d15d6c0361fdc4187de7e4beb08c5cf213e781
|
temur-kh/simple-search-engine
|
/shared/soundex.py
| 1,130 | 4.125 | 4 |
def get_soundex_form(word: str) -> str:
if not word:
return word
elif len(word) == 1:
return word.upper()
upper = word.upper()
# step 1 according to lecture slides
raw_soundex = upper[0]
# step 2-3
for ch in upper[1:]:
if ch in ['A', 'E', 'I', 'O', 'U', 'H', 'W', 'Y']:
raw_soundex += '0'
elif ch in ['B', 'F', 'P', 'V']:
raw_soundex += '1'
elif ch in ['C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z']:
raw_soundex += '2'
elif ch in ['D', 'T']:
raw_soundex += '3'
elif ch == 'L':
raw_soundex += '4'
elif ch in ['M', 'N']:
raw_soundex += '5'
elif ch == 'R':
raw_soundex += '6'
else:
continue
filtered_soundex = raw_soundex[:2]
# step 4
prev_ch = raw_soundex[1]
for ch in raw_soundex[2:]:
if ch != prev_ch:
filtered_soundex += ch
prev_ch = ch
# step 5
filtered_soundex = filtered_soundex.replace('0', '')
# step 6
soundex = (filtered_soundex + '000')[:4]
return soundex
|
5da23c6ef219416876386040f5b53dc7aec6f587
|
bgoonz/UsefulResourceRepo2.0
|
/MY_REPOS/INTERVIEW-PREP-COMPLETE/notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/__MY_OPRIGINAL_DS/_Extra-Practice/08_greedy_algorithms/python/01_set_covering.py
| 771 | 3.921875 | 4 |
# You pass an array in, and it gets converted to a set.
states_needed = set(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"])
stations = {}
stations["kone"] = set(["id", "nv", "ut"])
stations["ktwo"] = set(["wa", "id", "mt"])
stations["kthree"] = set(["or", "nv", "ca"])
stations["kfour"] = set(["nv", "ut"])
stations["kfive"] = set(["ca", "az"])
final_stations = set()
while states_needed:
best_station = None
states_covered = set()
for station, states_for_station in stations.items():
covered = states_needed & states_for_station
if len(covered) > len(states_covered):
best_station = station
states_covered = covered
states_needed -= states_covered
final_stations.add(best_station)
print(final_stations)
|
7f1ca40649cc43e41083479c9681d38ca2a89972
|
Tlepsh64/Lighbot-Kernel
|
/Lightbot.py
| 3,218 | 3.625 | 4 |
# level 1 terrain: write column by column, ex: [ [0,1,0], [2,1,0] ] is a 2x3 terrain
height = [ [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0] ]
isBlue = [ [True,False,False,False], [False,False,False,False], [False,False,False,False], [False,False,False,False], [False,False,False,True] ]
isOn = [ [False,False,False,False], [False,False,False,False], [False,False,False,False], [False,False,False,False], [False,False,False,True] ]
# start by intializing the lightbot status variables
x = 0 # position x coordinate
y = 0 # position y coordinate
yon = 0 # which way our lbot is facing
direction = { 0:"north", 1:"east", 2:"south", 3:"west" }
maxX = len(height) - 1 # max possible value of the x coordinate
maxY = len(height[0]) - 1 # max possible value of the y coordinate
def heightDifferenceForward():
""" A function to compute the difference between the current box that the lightbot is occupying, and the box it is facing. """
if yon == 0 and y < maxY:
return height[x][y+1] - height[x][y]
elif yon == 2 and y > 0:
return height[x][y-1] - height[x][y]
elif yon == 1 and x < maxX:
return height[x+1][y] - height[x][y]
elif yon == 3 and x > 0:
return height[x-1][y] - height[x][y]
# return 0 # Why do we return zero? Doesn't this mean that the above codes are all gonna be useless?
komut = ""
while komut != "q": # repeat as long as we don't get the quit command
print("Enter a command for lbot")
komut = raw_input()
if komut == ">" :
print("I am turning right")
yon = (yon + 1) % 4
elif komut == "<" :
print("I am turning left")
yon = (yon-1) % 4
elif komut == "^" :
if yon == 0: # if we are facing north
if y < maxY: # check we are not at the top row
y = y + 1
elif y == maxY: # This code snippet(s.look below) may not be needed, but I thought it would be smart to remind us that we are at the borders of the game's terrain.
y = y
if yon == 2: # if we are facing south
if y > 0: # check we are not at the bottom row
y = y - 1
elif y == 0:
y = y
if yon == 1: # if we are facing east
if x < maxX: # check we are not at the rightmost column
x = x + 1
elif x == maxX:
x = x
if yon == 3: # if we are facing west
if x > 0: # check we are not at the leftmost column
x = x - 1
elif x == 0:
x = x
elif komut == "@" :
if ( isBlue[x][y] == True ):
print("I am switching on or off")
if ( isOn[x][y] == True ):
isOn[x][y] = False
else:
isOn[x][y] = True
else:
print("Y'all are a-tryin' ta laheet up ayy gray box. I can't do it")
elif komut != "q":
print("This command is not known")
print("As I exit now, my orientation is ", direction[yon])
|
e006c5149709cd60bde03fae0830d20541f90c24
|
C1ARKGABLE/adventOfCode19
|
/day_3/main.py
| 3,033 | 4 | 4 |
with open("wires.csv","r") as file:
wires = [line.rstrip().split(",") for line in file.readlines()]
def dist(p1, p2=(0, 0)):
"""Calculates the Manhattan distance between two points"""
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def trace(step, pos):
"""Draws the line formed by applying a step (`step`) to a given coordinate (`pos`).
Args:
`step`: The step to be taken.
`pos`: The position to which the step should be applied.
Returns:
(list): A list of coordinates that define the line.
"""
shift = int(step[1:])
direction = step[0]
x = pos[0]
y = pos[1]
if direction == "D":
line = [(x, y-j) for j in range(1, shift+1)]
elif direction == "U":
line = [(x, y+j) for j in range(1, shift+1)]
elif direction == "L":
line = [(x-i, y) for i in range(1, shift+1)]
elif direction == "R":
line = [(x+i, y) for i in range(1, shift+1)]
return line
def draw(pos, path):
"""Draws the graph formed by following a sequence of steps (`path`) from a given starting position (`pos`)."""
graph = []
for step in path:
line = trace(step, pos)
pos = line[-1] # Update `pos`.
graph += line
return graph
def intersect(paths):
"""Draws the graphs formed by following the two provided paths and finds their intersection.
Args:
`paths`: A list of two elements, corresponding to the paths for the two wires.
Returns:
(tuple): A 3-tuple representing the graphs of the three wires and their intersections.
`graph_1 (list)`: Graph of the first wire.
`graph_2 (list)`: Graph of the second wire.
`crosses`: Set of points where the two wires cross each other.
"""
graph_1, graph_2 = draw((0, 0), paths[0]), draw((0, 0), paths[1])
crosses = set(graph_1) & set(graph_2)
return crosses, graph_1, graph_2
def reaches(paths):
"""Finds the distance travelled by each wire to their various points of intersection.
Args:
`paths`: A list of two elements, corresponding to the paths for the two wires.
Returns:
(dict): A dictionary mapping each point of intersection to the distances the two wires take to reach it.
"""
crosses, graph_1, graph_2 = intersect(paths)
dct = {point: [None, None] for point in crosses}
for idx, pair in enumerate(graph_1):
if pair in crosses:
dct[pair][0] = dct[pair][0] or idx+1
for idx, pair in enumerate(graph_2):
if pair in crosses:
dct[pair][1] = dct[pair][1] or idx+1
return dct
def part_one():
"""Finds minimum Manhattan distance from origin of the intersection points."""
return min(dist(cross) for cross in intersect(wires)[0])
def part_two():
"""Finds minimum distance travelled by the two wires to reach an intersection point."""
return min(sum(pair) for pair in reaches(wires).values())
print(part_two())
|
7ff451ef2fbb1ddf6881979cc08ca318f7b071d4
|
Cricsudheer/Flight-Management-System
|
/users.py
| 5,350 | 3.5 | 4 |
# encapsulation
class users:
def __init__(self, flight_manager):
self.db = flight_manager
self.db_cursor = flight_manager.cursor()
def auth(self , username , password):
sql_form = "select * from user where username = '{}' and password ='{}'".format(username , password)
self.db_cursor.execute(sql_form)
res = list(self.db_cursor)
if res :
return 1
return 0
def user_existance(self , username):
sql_form = "SELECT * FROM user WHERE username = '{}'".format(username)
self.db_cursor.execute(sql_form)
res = list(self.db_cursor)
if res:
return 1
return 0
def checkadmin(self ,username):
sql_form = "SELECT * FROM user WHERE username = '{}'".format(username)
self.db_cursor.execute(sql_form)
res = list(self.db_cursor)
print(res[0][-1])
if res[0][-1]==1:
return 1
return 0
def add_user(self , username , name , age , password):
if self.user_existance(username):
print("USER ALREADY EXISTS")
return
sql_form = "Insert into user(username, name, age , password, isadmin) values(%s, %s, %s, %s, %s)"
us = [(username ,name, age , password ,0 ) ,]
self.db_cursor.executemany(sql_form, us)
self.db.commit()
print("User created Successfully !")
return
def show_tickets(self, username):
sql_form = "select * from tickets where username ='{}'".format(username)
self.db_cursor.execute(sql_form)
res = list(self.db_cursor)
if res :
for i in range(len(res)):
print(i + 1, *res[i])
else :
print("NO bookings yet")
def search_flight(self , src , dest):
sql_form = "Select * from flight where src = '{}' and dest='{}' order by price".format(src, dest)
self.db_cursor.execute(sql_form)
res = list(self.db_cursor)
if res:
print("Top cheapest flights available for you !")
for i in range(len(res)):
print(i+1 , *res[i])
print("Choose flight number from above screen: ")
n = int(input())
if n>len(res) or n<1 :
print("Invalid input")
else :
print("enter number of seats :")
m = int(input())
if res[n-1][-2]-m>=0:
print("Enter username")
username = input()
print("password")
password = input()
if(users.auth(self ,username ,password)):
#update seats
sql_form1 = "update flight set seat= '{}' where price = '{}' and src = '{}' and dest ='{}'".format(res[n-1][-2]-m , res[n-1][-1] ,
res[n-1][0] ,res[n-1][1])
self.db_cursor.execute(sql_form1)
self.db.commit()
#add ticket
sql_form2 = "insert into tickets values('{}' , '{}' , '{}' , '{}')".format(username , res[n-1][0] ,res[n-1][1], m)
self.db_cursor.execute(sql_form2)
self.db.commit()
print("Booking successful")
else :
print("invalid user credentials")
else :
print("only '{}' seats available".format(res[n-1][-1]))
else:
print("No flights available!")
class admins(users):
#inheritance
def __init__(self, flight_manager):
super().__init__(flight_manager)
self.db = flight_manager
self.db_cursor = flight_manager.cursor()
def delete_user(self, username):
if users.user_existance(self , username):
sql_form = "delete from user WHERE username='{}'".format(username)
self.db_cursor.execute(sql_form)
self.db.commit()
print("USER DELETED SUCCESSFULLY !")
else :
print("USER DOESN'T EXISTS !")
def make_admin(self ,username):
if users.user_existance(self, username):
sql_form = "update user set isadmin ='{}' WHERE username='{}'".format(1 , username)
self.db_cursor.execute(sql_form)
self.db.commit()
print("USER IS NOW ADMIN !")
else:
print("USER DOESN'T EXISTS !")
def add_flights(self , src ,dest , seats , price):
sql_form = "Select * from flight where src = '{}' and dest='{}' and price = '{}' ".format(src, dest ,price)
self.db_cursor.execute(sql_form)
res = list(self.db_cursor)
if res:
print("Flight already present")
else :
sql_form = "Insert into flight values('{}', '{}', '{}', '{}')".format(src, dest, seats, price)
# us = [(src , dest, price , seats),]
self.db_cursor.execute(sql_form)
self.db.commit()
print("Flight added successfully")
|
fddcf9eddc71a2379e0dbc485e30ba4bab6f74f3
|
pphan00/BIOL5153
|
/dna_percentage.py
| 641 | 3.8125 | 4 |
#!/usr/env python3
input = "dna.txt"
inputfile = open(input, "r")
dna_sequence = inputfile.read().lower()
print(dna_sequence)
a_count = dna_sequence.count("a")
g_count = dna_sequence.count("g")
t_count = dna_sequence.count("t")
c_count = dna_sequence.count("c")
total_length = len(dna_sequence)
aper = round(a_count/total_length*100, 2)
tper = round(t_count/total_length*100, 2)
cper = round(c_count/total_length*100, 2)
gper = round(g_count/total_length*100, 2)
print("Percent A : " + str(aper) + "%")
print("Percent T : " + str(tper) + "%")
print("Percent G : " + str(gper) + "%")
print("Percent C : " + str(cper) + "%")
inputfile.close()
|
b6c46c2da2b1512724ff6e08e9f02ac53bb1eee1
|
ndombrowski20/pdes_python
|
/NMP/SIM_2.py
| 345 | 3.8125 | 4 |
# Simple iterations method with a while loop same example as SIM_1.py
x = 10 # unlike last time this is the new arbitrary value because of how the abs is constructed
xnew = 0 # this is our "guess"
i = 0
while abs(xnew - x) >= .0000001:
i += 1
x = xnew
xnew = (2*x**2 + 3)/5
print('the root: %f' % xnew)
print('iterations: %d' % i)
|
e659f17ca3e2a6038ed3690a799b53b8c55ef9ba
|
JasonWuGenius/Nowcoder
|
/BigComp_2018_Python/continousNumCompare.py
| 1,146 | 3.59375 | 4 |
'''
题目描述
对于任意两个正整数x和k,我们定义repeat(x, k)为将x重复写k次形成的数,例如repeat(1234, 3) = 123412341234,repeat(20,2) = 2020.
牛牛现在给出4个整数x1, k1, x2, k2, 其中v1 = (x1, k1), v2 = (x2, k2),请你来比较v1和v2的大小。
输入描述:
输入包括一行,一行中有4个正整数x1, k1, x2, k2(1 ≤ x1,x2 ≤ 10^9, 1 ≤ k1,k2 ≤ 50),以空格分割
输出描述:
如果v1小于v2输出"Less",v1等于v2输出"Equal",v1大于v2输出"Greater".
示例1
输入
复制
1010 3 101010 2
输出
复制
Equal
'''
nums = list(map(int, input().split()))
x1 = ""
k1 = int(nums[1])
x2 = ""
k2 = int(nums[3])
for i in range(k1):
x1 += str(nums[0])
for i in range(k2):
x2 += str(nums[2])
if len(x1) > len(x2):
print("Greater")
elif len(x1) < len(x2):
print("Less")
else:
flag = 0
for i in range(len(x1)):
if x1[i] > x2[i]:
flag = 1
break
elif x1[i] < x2[i]:
flag = -1
break
if flag == 0:
print("Equal")
elif flag == 1:
print("Greater")
else:
print("Less")
|
539dff8ed8076da54f84516ce32b410bb51028f1
|
ahmedhamza47/Advanced_Topics
|
/18)shallow vs deep copy.py
| 404 | 3.984375 | 4 |
import copy
# shallow copying is only one level deep
original = [1,2,3,4,5]
cpy = original.copy()
cpy[0] = 10
print(original)
print(cpy)
org2 = [[1,2,3,4,5],[6,7,8,9,19]]
cpy1 = org2.copy()
cpy1[0][1] = 20
print(org2)
print(cpy1) # both org2 and cpy1 has same value cuz shallow copy is one level deep
# so to make a deep copy we use
cpy2 = copy.deepcopy(org2)
cpy2[0][1] = 30
print(org2)
print(cpy2)
|
38a8956b3368088efbfe75504b832f32ac71455c
|
BJV-git/leetcode
|
/math/perfect_no.py
| 404 | 3.703125 | 4 |
# logic: can use the shortcut methods mentioned and then we go for normal stuff
# i.e. we see if every things is fact or not and then add them up
# in normal process lets keep track of left where we can stop early
def perf_no(n):
i = 2
t = 0
while t < n:
t = (2**(i-1)) * ((2**i)-1)
if t == n:
return True
i+=1
return False
print(perf_no(2976221))
|
f27b849a716f5578c32a48678078eb1b6b2a7395
|
prompt-toolkit/python-prompt-toolkit
|
/examples/telnet/toolbar.py
| 1,117 | 3.5 | 4 |
#!/usr/bin/env python
"""
Example of a telnet application that displays a bottom toolbar and completions
in the prompt.
"""
import logging
from asyncio import Future, run
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.contrib.telnet.server import TelnetServer
from prompt_toolkit.shortcuts import PromptSession
# Set up logging
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
async def interact(connection):
# When a client is connected, erase the screen from the client and say
# Hello.
connection.send("Welcome!\n")
# Display prompt with bottom toolbar.
animal_completer = WordCompleter(["alligator", "ant"])
def get_toolbar():
return "Bottom toolbar..."
session = PromptSession()
result = await session.prompt_async(
"Say something: ", bottom_toolbar=get_toolbar, completer=animal_completer
)
connection.send(f"You said: {result}\n")
connection.send("Bye.\n")
async def main():
server = TelnetServer(interact=interact, port=2323)
await server.run()
if __name__ == "__main__":
run(main())
|
678cdd5f4ed1ce1d85b600a07fac62d6d251df67
|
catboost/catboost
|
/contrib/tools/python/src/Lib/string.py
| 21,548 | 3.90625 | 4 |
"""A collection of string operations (most are no longer used).
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself.
Public module variables:
whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable
"""
# Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase
ascii_lowercase = lowercase
ascii_uppercase = uppercase
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + letters + punctuation + whitespace
# Case conversion helpers
# Use str to convert Unicode literal in case of -U
l = map(chr, xrange(256))
_idmap = str('').join(l)
del l
# Functions which aren't available as string methods.
# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
def capwords(s, sep=None):
"""capwords(s [,sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a single space
and leading and trailing whitespace are removed, otherwise
sep is used to split and join the words.
"""
return (sep or ' ').join(x.capitalize() for x in s.split(sep))
# Construct a translation string
_idmapL = None
def maketrans(fromstr, tostr):
"""maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
"""
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments must have same length"
global _idmapL
if not _idmapL:
_idmapL = list(_idmap)
L = _idmapL[:]
fromstr = map(ord, fromstr)
for i in range(len(fromstr)):
L[fromstr[i]] = tostr[i]
return ''.join(L)
####################################################################
import re as _re
class _multimap:
"""Helper class for combining multiple mappings.
Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary
def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key]
class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
"""
def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass
delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*'
def __init__(self, template):
self.template = template
# Search for $$, $identifier, ${identifier}, and any bare $'s
def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno))
def substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'substitute' of 'Template' object "
"needs an argument")
self, args = args[0], args[1:] # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % (val,)
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
def safe_substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'safe_substitute' of 'Template' object "
"needs an argument")
self, args = args[0], args[1:] # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)
####################################################################
# NOTE: Everything below here is deprecated. Use string methods instead.
# This stuff will go away in Python 3.0.
# Backward compatible names for exceptions
index_error = ValueError
atoi_error = ValueError
atof_error = ValueError
atol_error = ValueError
# convert UPPER CASE letters to lower case
def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower()
# Convert lower case letters to UPPER CASE
def upper(s):
"""upper(s) -> string
Return a copy of the string s converted to uppercase.
"""
return s.upper()
# Swap lower case letters and UPPER CASE
def swapcase(s):
"""swapcase(s) -> string
Return a copy of the string s with upper case characters
converted to lowercase and vice versa.
"""
return s.swapcase()
# Strip leading and trailing tabs and spaces
def strip(s, chars=None):
"""strip(s [,chars]) -> string
Return a copy of the string s with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping.
"""
return s.strip(chars)
# Strip leading tabs and spaces
def lstrip(s, chars=None):
"""lstrip(s [,chars]) -> string
Return a copy of the string s with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return s.lstrip(chars)
# Strip trailing tabs and spaces
def rstrip(s, chars=None):
"""rstrip(s [,chars]) -> string
Return a copy of the string s with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return s.rstrip(chars)
# Split a string into a list of space/tab-separated words
def split(s, sep=None, maxsplit=-1):
"""split(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator.
(split and splitfields are synonymous)
"""
return s.split(sep, maxsplit)
splitfields = split
# Split a string into a list of space/tab-separated words
def rsplit(s, sep=None, maxsplit=-1):
"""rsplit(s [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return s.rsplit(sep, maxsplit)
# Join fields with optional separator
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words)
joinfields = join
# Find substring, raise exception if not found
def index(s, *args):
"""index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
"""
return s.index(*args)
# Find last substring, raise exception if not found
def rindex(s, *args):
"""rindex(s, sub [,start [,end]]) -> int
Like rfind but raises ValueError when the substring is not found.
"""
return s.rindex(*args)
# Count non-overlapping occurrences of substring
def count(s, *args):
"""count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return s.count(*args)
# Find substring, return -1 if not found
def find(s, *args):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.find(*args)
# Find last substring, return -1 if not found
def rfind(s, *args):
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return s.rfind(*args)
# for a bit of speed
_float = float
_int = int
_long = long
# Convert string to float
def atof(s):
"""atof(s) -> float
Return the floating point number represented by the string s.
"""
return _float(s)
# Convert string to integer
def atoi(s , base=10):
"""atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.
"""
return _int(s, base)
# Convert string to long integer
def atol(s, base=10):
"""atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it is chosen from the leading characters of s, 0 for
octal, 0x or 0X for hexadecimal. If base is 16, a preceding
0x or 0X is accepted. A trailing L or l is not accepted,
unless base is 0.
"""
return _long(s, base)
# Left-justify a string
def ljust(s, width, *args):
"""ljust(s, width[, fillchar]) -> string
Return a left-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.ljust(width, *args)
# Right-justify a string
def rjust(s, width, *args):
"""rjust(s, width[, fillchar]) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces.
"""
return s.rjust(width, *args)
# Center a string
def center(s, width, *args):
"""center(s, width[, fillchar]) -> string
Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated. If specified the fillchar is used instead of spaces.
"""
return s.center(width, *args)
# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width)
# Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string
Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8).
"""
return s.expandtabs(tabsize)
# Character translation through look-up table.
def translate(s, table, deletions=""):
"""translate(s,table [,deletions]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings.
"""
if deletions or table is None:
return s.translate(table, deletions)
else:
# Add s[:0] so that if s is Unicode and table is an 8-bit string,
# table is converted to Unicode. This means that table *cannot*
# be a dictionary -- for that feature, use u.translate() directly.
return s.translate(table + s[:0])
# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
def capitalize(s):
"""capitalize(s) -> string
Return a copy of the string s with only its first character
capitalized.
"""
return s.capitalize()
# Substring replacement (global)
def replace(s, old, new, maxreplace=-1):
"""replace (str, old, new[, maxreplace]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxreplace is
given, only the first maxreplace occurrences are replaced.
"""
return s.replace(old, new, maxreplace)
# Try importing optional built-in module "strop" -- if it exists,
# it redefines some string operations that are 100-1000 times faster.
# It also defines values for whitespace, lowercase and uppercase
# that match <ctype.h>'s definitions.
try:
from strop import maketrans, lowercase, uppercase, whitespace
letters = lowercase + uppercase
except ImportError:
pass # Use the original versions
########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class
# The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str and unicode.
# The overall parser is implemented in str._formatter_parser.
# The field name parser is implemented in str._formatter_field_name_split
class Formatter(object):
def format(*args, **kwargs):
if not args:
raise TypeError("descriptor 'format' of 'Formatter' object "
"needs an argument")
self, args = args[0], args[1:] # allow the "self" keyword be passed
try:
format_string, args = args[0], args[1:] # allow the "format_string" keyword be passed
except IndexError:
if 'format_string' in kwargs:
format_string = kwargs.pop('format_string')
else:
raise TypeError("format() missing 1 required positional "
"argument: 'format_string'")
return self.vformat(format_string, args, kwargs)
def vformat(self, format_string, args, kwargs):
used_args = set()
result = self._vformat(format_string, args, kwargs, used_args, 2)
self.check_unused_args(used_args, args, kwargs)
return result
def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
if recursion_depth < 0:
raise ValueError('Max string recursion exceeded')
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string):
# output the literal text
if literal_text:
result.append(literal_text)
# if there's a field, output it
if field_name is not None:
# this is some markup, find the object and do
# the formatting
# given the field_name, find the object it references
# and the argument it came from
obj, arg_used = self.get_field(field_name, args, kwargs)
used_args.add(arg_used)
# do any conversion on the resulting object
obj = self.convert_field(obj, conversion)
# expand the format spec, if needed
format_spec = self._vformat(format_spec, args, kwargs,
used_args, recursion_depth-1)
# format the object and append to the result
result.append(self.format_field(obj, format_spec))
return ''.join(result)
def get_value(self, key, args, kwargs):
if isinstance(key, (int, long)):
return args[key]
else:
return kwargs[key]
def check_unused_args(self, used_args, args, kwargs):
pass
def format_field(self, value, format_spec):
return format(value, format_spec)
def convert_field(self, value, conversion):
# do any conversion on the resulting object
if conversion is None:
return value
elif conversion == 's':
return str(value)
elif conversion == 'r':
return repr(value)
raise ValueError("Unknown conversion specifier {0!s}".format(conversion))
# returns an iterable that contains tuples of the form:
# (literal_text, field_name, format_spec, conversion)
# literal_text can be zero length
# field_name can be None, in which case there's no
# object to format and output
# if field_name is not None, it is looked up, formatted
# with format_spec and conversion and then used
def parse(self, format_string):
return format_string._formatter_parser()
# given a field_name, find the object it references.
# field_name: the field being looked up, e.g. "0.name"
# or "lookup[3]"
# used_args: a set of which args have been used
# args, kwargs: as passed in to vformat
def get_field(self, field_name, args, kwargs):
first, rest = field_name._formatter_field_name_split()
obj = self.get_value(first, args, kwargs)
# loop through the rest of the field_name, doing
# getattr or getitem as needed
for is_attr, i in rest:
if is_attr:
obj = getattr(obj, i)
else:
obj = obj[i]
return obj, first
|
d8e41d1e8238eb8a604778395ffbe3658b2f532c
|
brachbach/project-euler
|
/prob12.py
| 1,142 | 3.875 | 4 |
import math
def nth_triangular_number(n, prev_triangular = 1, prev_int = 1):
if n == prev_int:
return prev_triangular
new_int = prev_int + 1
return nth_triangular_number(n, prev_triangular + new_int, new_int)
assert nth_triangular_number(1) == 1
assert nth_triangular_number(2) == 3
assert nth_triangular_number(3) == 6
def find_factors(n):
factors = [n]
for i in range(1, int(math.floor(n/2)) + 1):
if n % i == 0:
factors.append(i)
return factors
# print find_factors(28)
def find_triangular_with_n_factors(n):
i = 1
current_triangular = 1
# simple lower bound, assuming that everything up to 500 was a factor,
# and of course that there are no factors > 1/2 of n
# a better lower bound would actually look at the first 500 numbers more carefully
lower_bound = 490 * 2
while current_triangular < lower_bound:
i +=1
current_triangular += i
while True:
i +=1
current_triangular += i
if (len(find_factors(current_triangular)) > n):
return current_triangular
print find_triangular_with_n_factors(500)
|
0a07aa8a9c6846cd44c1107718c76bc41d91b68e
|
ucsd-cse-spis-2018/spis18-lab03-Dario-Manuel
|
/drawLetter_Dario.py
| 221 | 3.828125 | 4 |
#Turtle will draw the letter D
import turtle
def drawD(theTurtle):
theTurtle.left(90)
theTurtle.forward(100)
theTurtle.right(90)
theTurtle.circle(-50,180)
myTurtle = turtle.Turtle()
drawD(myTurtle)
|
b1499329a7356f63565db28faa41c0c5ae8e376f
|
melinazik/crypto
|
/src/ex12.py
| 2,535 | 3.71875 | 4 |
'''
Textbook RSA
Exercise 12
Melina Zikou (2021)
'''
import math
import base64
# Converts a rational x/y fraction into
# a list of partial quotients [a0, ..., an]
def rationalToContFrac(x,y):
a = x // y
q = []
q.append(a)
while a * y != x:
x, y = y, x - a * y
a = x // y
q.append(a)
return q
# Converts a finite continued fraction [a0, ..., an]
# to an x/y rational.
def contFracToRational (frac):
if len(frac) == 0:
return (0, 1)
num = frac[-1]
denom = 1
for i in range(-2, -len(frac) - 1, -1):
num, denom = frac[i]*num+denom, num
return (num, denom)
# computes the list of convergents
# using the list of partial quotients
def convergentsFromContFrac(frac):
c = []
for i in range(len(frac)):
c.append(contFracToRational(frac[0:i]))
return c
def fast(b,e,m):
x = b
g = e
d = 1
while g > 0:
if g % 2 == 0:
x = (x * x) % m
g = g / 2
else:
d = (x * d) % m
g = g - 1
return d
def isPerfectSquare(n):
t = math.sqrt(n)
if t * t == n:
return t
else:
return -1
# Finds d knowing (e,n)
# applying the Wiener continued fraction attack
def findD(e,N):
frac = rationalToContFrac(e, N)
convergents = convergentsFromContFrac(frac)
for (k, d) in convergents:
#check if d is actually the key
if k != 0 and (e * d - 1) % k == 0:
phi = (e * d - 1) // k
b = N - phi + 1
# check if the equation x^2 - s*x + n = 0
# has integer roots
D = (b * b) - (4 * N)
if(D >= 0):
t = isPerfectSquare(D)
if t != -1 and (b + t) % 2 == 0:
return d
# print char objects of a list as a string
def printText(text):
for i in range(len(text)):
print(text[i], end="")
N = 194749497518847283
e = 50736902528669041
f = open("..\\files\\textbookRSA.txt", "r")
cipher= f.read()
d = findD(e, N)
privateKey = [N, d]
# print(d)
C = []
M = []
asciiM = []
# convert from base64 to utf - 8
cipher = base64.b64decode(cipher).decode('utf-8')
print(cipher)
cipher = cipher.replace('\r\n', ',')
cipher = cipher.replace('C=[', '')
cipher = cipher.replace(']', '')
cipher = cipher.split(',')
for c in cipher:
C.append(c)
for c in C:
M.append(fast(int(c),d,N))
for m in M:
asciiM.append(chr(m))
print("Private Key:", privateKey)
printText(asciiM)
|
00f774425fef375c49488ab6a600fd7a6446eaa9
|
AdyGCode/Python-Basics-2021S1
|
/Week-14-1/gui-3-guessing-game.py
| 5,734 | 3.921875 | 4 |
# --------------------------------------------------------------
# File: Week-13-2/gui-3-guessing-game.py
# Project: Python-Class-Demos
# Author: Adrian Gould <[email protected]>
# Created: 13/05/2021
# Purpose: GUI Guessing Game version 3
#
# Duplicate the second version of the guessing game.
#
# You will enhance this version of the game by:
# 5) Add a new label that shows the number of guesses taken
# starting at 1, and increment every time a new guess is made.
# 6) When the user guessed the number, disable the guess button.
# 7) When the user guesses the number, display a "play again"
# button that will restart the game with a new number and the count
# reset. Remember to enable the guess button and hide the play
# again button.
# --------------------------------------------------------------
from random import randint
from breezypythongui import EasyFrame
class GuessingGame(EasyFrame):
"""Guessing Game Class
Inherits the EasyFrame methods and properties
"""
def __init__(self):
"""Initialise the frame and instance variables
count integer counts the guesses
computer_number a random number for the user to guess
message the message to
"""
self.count = 0
self.computer_number = randint(1, 100)
self.message = ""
self.fg = "#000000"
self.bg = "#000000"
self.game_won = False
# EasyFrame.__init__(self,
# title="Guessing Game",
# width=300,
# height=150)
super().__init__(title="Guessing Game",
width=300,
height=250)
# Create the interface
self.Title = self.addLabel(text="Guess the Number",
row=0,
column=0,
columnspan=3,
sticky="EW",
font="Verdana",
foreground="#ffffff",
background="#000000")
self.GuessLabel = self.addLabel(text="What is your Guess?",
row=1,
column=0,
foreground="#090909")
self.NumberGuessed = self.addIntegerField(value=0,
row=1,
column=1)
self.GuessButton = self.addButton(text="Guess!",
row=1,
column=2,
command=self.check_guess)
self.MessageLabel = self.addLabel(text="take a guess..",
row=2,
column=0,
columnspan=3,
sticky="EW")
self.CountLabel = self.addLabel(text="0 Guesses",
row=3,
column=0,
sticky="EW")
self.PlayAgainButton = self.addButton(text="Play Again",
row=3,
column=1,
command=self.play_again)
self.QuitButton = self.addButton(text="Quit",
row=3,
column=2,
command=self.quit_game)
# Command handling methods are added after this
def check_guess(self):
# create the method code here
# delete pass when adding code
try:
user_number = self.NumberGuessed.getNumber()
self.count += 1
self.fg = "#000000"
self.bg = "#ffffff"
if user_number > self.computer_number:
self.message = "Too High!"
self.bg = "#ff0000"
self.fg = "#ffffff"
elif user_number < self.computer_number:
self.message = "Too Low!"
self.bg = "#0000ff"
self.fg = "#ffffff"
else:
self.message = f"You got it in {self.count} guesses!"
self.bg = "#00ff00"
self.fg = "#000000"
self.game_won = True
# self.quit()
except ValueError:
self.message = "You need to enter an integer"
self.bg = "#ffbb00"
self.fg = "#000000"
finally:
self.MessageLabel["text"] = self.message
self.MessageLabel["foreground"] = self.fg
self.MessageLabel["background"] = self.bg
self.CountLabel["text"] = f"{self.count} Guesses"
# if self.game_won:
def play_again(self):
# TODO: save game high score
self.computer_number = randint(1, 100)
self.count = 0
self.message = ""
self.game_won = False
self.fg = "#000000"
self.bg = "#ffffff"
self.MessageLabel["text"] = self.message
self.MessageLabel["foreground"] = self.fg
self.MessageLabel["background"] = self.bg
self.CountLabel["text"] = f"{self.count} Guesses"
def quit_game(self):
# TODO: save game high scores
self.quit()
def main():
"""Instantiate and pop up the window."""
GuessingGame().mainloop()
if __name__ == "__main__":
main()
|
678a62748a48000a387e3362c1d6362ffc2efe36
|
yanshengjia/algorithm
|
/leetcode/Tree & Recursion/117. Populating Next Right Pointers in Each Node II.py
| 4,362 | 3.6875 | 4 |
"""
Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example:
Input: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":null,"next":null,"right":{"$id":"6","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}
Output: {"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":null,"right":null,"val":7},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"6","left":null,"next":null,"right":{"$ref":"5"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"6"},"val":1}
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B.
Note:
You may only use constant extra space.
Recursive approach is fine, implicit stack space does not count as extra space for this problem.
Solution:
1. BFS + Queue Level Order Traversal
2. Dummy Node Traversal O(1) space
"""
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
# BFS
# Time: O(N), N is tree size
# Space: O(N)
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
cur_level = [root]
while cur_level:
next_level = []
for node in cur_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
l = len(next_level)
for i in range(l-1):
next_level[i].next = next_level[i+1]
if l > 0:
cur_level = next_level
else:
break
return root
# Level Order Traversal
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
queue = [root]
next_level = []
while queue:
node = queue.pop(0)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
if queue: # queue is not empty means cur node is not tail
node.next = queue[0]
if not queue:
# cur level traversal finish
queue, next_level = next_level, queue
return root
# Level Order Traversal
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
tail = root
queue = [root]
while queue:
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if node == tail:
# travel to the tail node of cur level, update the tail
tail = queue[-1] if len(queue) > 0 else None
node.next = None
else:
node.next = queue[0]
return root
# Dummy Node Traversal
# Time: O(N)
# Space: O(1)
class Solution:
def connect(self, root: 'Node') -> 'Node':
dummy = Node(0, None, None, None) # point to head node of each level
pre = dummy
res = root
while root:
if root.left:
pre.next = root.left
pre = pre.next
if root.right:
pre.next = root.right
pre = pre.next
root = root.next
if root == None: # meet the tail of cur level
pre = dummy # point to the head node of next level
root = dummy.next # became the head node of next level
dummy.next = None # for the last level, break while loop
return res
|
7fccdb9b0145514e945891bfb736eae8c2ae45a3
|
Sbarcenas/exercims_python
|
/pangram/pangram.py
| 178 | 3.8125 | 4 |
import re
from string import ascii_lowercase
def is_pangram(sentence):
pangram = re.sub('[^a-z]','',sentence.lower())
return set(pangram) == set(ascii_lowercase)
|
5c89e76d0ebd23a53463a270ba739e41d7a07d15
|
IbrahimDaurenov/Incoop-cohort-1
|
/Week 2/Day 4 (July 20)/mylists.py
| 452 | 4.0625 | 4 |
names = ['Ibrahim', 'Nabi', 'Alikhan', 'Yaroslav', 'Daulet', 'Bekzat']
print(names)
names.append('Daniyar')
print(names)
print(names[0]) # 'Ibrahim'
print(names [-1] ) # 'Daniyar'
names[0] = 'Ibra'
print(names)
names.remove('Daniyar')
print(names)
names.pop(0)
print(names)
new_names = names.copy()
names.clear()
print(names)
print(new_names)
#.................
my_list = [1,'Name', 5.0, [1,2,3]]
empty_list = []
empty_list = list()
|
6ef145d4ab1cd77f84fce30da07e8048745a1ae1
|
quangbk2010/Courses-MITx-6.00.1x
|
/Midterm/Problem9/Is_list_permutation.py
| 3,159 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 6 17:32:11 2017
@author: quang
"""
def compare_2_dict (d1, d2):
'''
d1, d2: Assumes 2 non-empty dictionaries contain interger -> interger
Returns True if d1==d2, else False
'''
for key in d1.keys():
val2 = d2.get (key, None)
if val2 == None or d1[key] != val2:
return False
return True
'''def sort (L):
""" L is a non-empty list of ints, Use bouble sort algorithm
Sort from low to high
"""
l = len (L)
for i in range (l):
for j in range (l - 1, i - 1, -1):
if L[j] < L[j - 1]:
(L[j], L[j - 1]) = (L[j - 1], L[j])
return L
def convert_list_to_dict(L):
""" Assumes L is a non-empty list of ints
Returns the dictionary that contains entry: from interger -> the number of times that this interger appears """
dup_L = detach_list (L)
ret_d = {}
for lst in dup_L:
sorted_lst = sort(lst)
l = len (sorted_lst)
num = 1
d = {}
for i in range (l):
if i == l - 1:
d[sorted_lst[i]] = num
break
if sorted_lst[i] == sorted_lst[i + 1]:
num += 1
else:
d[sorted_lst[i]] = num
num = 1
ret_d.update (d)
return ret_d
'''
def convert_list_to_dict(L):
""" Assumes L is a non-empty list of ints
Returns the dictionary that contains entry: from interger -> the number of times that this interger appears """
d = {}
for item in L:
d[item] = d.get (item, 0) + 1
return d
def find_max_val (d):
'''
Assumes d is a non-empty dictionary, return the first finding key that has the biggest value
'''
maxVal = 0
ret_key = None
for key in d.keys():
if d[key] > maxVal:
ret_key = key
maxVal = d[key]
return (ret_key, maxVal)
'''def detach_list (L):
int_L = []
str_L = []
for item in L:
if type (item) == int:
int_L.append (item)
else:
str_L.append (item)
return (int_L, str_L)
'''
def is_list_permutation(L1, L2):
'''
L1 and L2: lists containing integers and strings
Returns False if L1 and L2 are not permutations of each other.
If they are permutations of each other, returns a
tuple of 3 items in this order:
the element occurring most, how many times it occurs, and its type
'''
len1 = len (L1)
len2 = len (L2)
if len1 == 0 and len2 == 0:
return (None, None, None)
# Otherwise
if len1 != len2:
return False
d1 = convert_list_to_dict(L1)
d2 = convert_list_to_dict(L2)
#print (d1)
#print (d2)
#print (find_max_val (d1))
if compare_2_dict (d1, d2) == True:
tup = find_max_val (d1)
return tup + (type(tup [0]), )
else:
return False
L1 = [1, 2, '5', 2, 5, 3, 4, 4, 5, 5, 6]
L2 = [1, 2, '5', 2, 5, 3, 4, 4, 5, 5, 6]
#print (convert_list_to_dict (L1))
print (is_list_permutation(L1, L2))
|
6ccd69104c393b404949de13b495a6c7e049e311
|
herolibra/PyCodeComplete
|
/Others/Classes/super/super_init2.py
| 358 | 3.578125 | 4 |
# coding=utf-8
# 子类(派生类)并不会自动调用父类(基类)的init方法
# 需要子类主动调用父类的init
# 方法2
class Foo(object):
def __init__(self):
self.val = 1
class Foo2(Foo):
def __init__(self):
super(Foo2, self).__init__()
print self.val
if __name__ == '__main__':
foo2 = Foo2()
|
a3c1e3b823842536dc3fbee1200d17feb49fd934
|
mamanipatricia/pythonFundamentals
|
/03.loops.py
| 659 | 4.21875 | 4 |
my_variable = "hello"
# print(my_variable[0])
# print(my_variable[1])
# print(my_variable[2])
# print(my_variable[3])
# print(my_variable[4])
# iterating "for" loop
# iterables are strings, lists, sets, tuples, and more
for character in my_variable:
print(character)
# its a very common mistake call variables that is not declared
my_list = [1, 2, 3, 4, 5]
for number in my_list:
print(number ** 2)
# WHILE
user_wants_number = True
while user_wants_number == True:
user_wants_number = False
print(10)
user_input = input("Should we print again (y/n) ")
if user_input =='n':
user_wants_number = False
print(10)
|
ace237444464e69a55fe7a8611973df1182d011c
|
luisC62/Master_Python
|
/21_tkinter/10_ejercicio_plus.py
| 2,868 | 3.765625 | 4 |
'''
CALCULADORA:
Refactorización del código del ejercicio anerior
Se crea la clase Calculadora
'''
from tkinter import *
from tkinter import messagebox as MessageBox
#Definición de la clase Calculadora
class Calculadora:
def __init__(self, alertas):
#Variables
self.numero1 = StringVar()
self.numero2 = StringVar()
self.resultado = StringVar()
self.alertas = alertas
def sumar(self):
try:
self.resultado.set(float(self.numero1.get()) + float(self.numero2.get()))
self.mostrarResultado()
except:
self.alertas.showerror("Error", "Introduce bien los datos")
def restar(self):
try:
self.resultado.set(float(self.numero1.get()) - float(self.numero2.get()))
self.mostrarResultado()
except:
self.alertas.showerror("Error", "Introduce bien los datos")
def multiplicar(self):
try:
self.resultado.set(float(self.numero1.get()) * float(self.numero2.get()))
self.mostrarResultado()
except:
self.alertas.showerror("Error", "Introduce bien los datos")
def dividir(self):
try:
self.resultado.set(float(self.numero1.get()) / float(self.numero2.get()))
self.mostrarResultado()
except:
self.alertas.showerror("Error", "Introduce bien los datos")
def mostrarResultado(self):
MessageBox.showinfo("Resultado", f"El resultado es: {self.resultado.get()}")
self.numero1.set("")
self.numero2.set("")
#Ventana principal
ventana = Tk()
ventana.title("Calculadora")
ventana.geometry("400x400")
ventana.config(bd = 25)
#Creamos el objeto calculadora
calculadora = Calculadora(MessageBox)
#Marco
marco = Frame(ventana, width=250, height=200 )
marco.config(
padx = 15,
pady = 15,
bd = 5,
relief = SOLID
)
marco.pack(side = TOP, anchor = CENTER)
marco.pack_propagate(False) #Para que no se deforme al meter elementos.
#Campo para el primer número
Label(marco, text = "Primer número: ").pack()
Entry(marco, textvariable = calculadora.numero1, justify = "center").pack()
#Campo para el segundo número
Label(marco, text = "Segundo número: ").pack()
Entry(marco, textvariable = calculadora.numero2, justify = "center").pack()
Label(marco, text="").pack() #A modo de separación
#Botones
Button(marco, text = "Sumar", command = calculadora.sumar).pack(side = "left", fill = X, expand = YES)
Button(marco, text = "Restar", command = calculadora.restar).pack(side = "left", fill = X, expand = YES)
Button(marco, text = "Multiplicar", command = calculadora.multiplicar).pack(side = "left", fill = X, expand = YES)
Button(marco, text = "Dividir", command = calculadora.dividir).pack(side = "left", fill = X, expand = YES)
ventana.mainloop()
|
d3eb8ad0b4661215f10fd6e9ee3fa4713c93e405
|
koukan3/basicPython
|
/basics/09继承.py
| 711 | 3.671875 | 4 |
#coding:utf-8
class Animal(object):
name="动物"
def say(self):
print("父类的函数")
class Parent(object):
def __init__(self):
self.age=20
def work(self):
print("父类Parent的函数")
def say(self):
print("父类Parent的函数")
class Dog(Parent,Animal):
__instance=None
def __init__(self,xsex):
self.sex=xsex
def work(self):
print("子类重写的函数")
def __new__(cls, *args, **kwargs):
if cls.__instance==None:
cls.__instance=object.__new__(cls)
return cls.__instance
dog1=Dog("雌性")
dog2=Dog("雄性")
print(dog1.sex)
print(dog1.say())
print(dog1==dog2)
print(Dog.__mro__)
|
c8e0d2949abd724f74d428ffc4b0aedaa668f791
|
iavorskiy/count_holes
|
/count_holes.py
| 437 | 3.59375 | 4 |
b = input("Enter the number to count the holes: \n")
def count_holes(b):
if type(b) != int and type(b) != str:
return("ERROR")
try:
int(b)
except ValueError:
return "ERROR"
c = str(b)
counter = 0
for x in c:
if x in "0469":
counter += 1
elif x == "8":
counter += 2
return counter
print(count_holes(b))
|
6270d438ab41abc580603f0747d6c1d551cf5930
|
anguswilliams91/stan_predict
|
/stan_predict.py
| 4,103 | 3.796875 | 4 |
"""A simple example of how one might use samples from Stan for prediction.
This example uses a simple model
y ~ N(theta_0 + theta_1 * X, 1).
A stan model is fitted, and the resulting posterior samples are cached.
Then, when predictions are required, a separate piece of stan code with only a
generated quantities block is called, and the posterior samples of the model
parameters are passed in the data block, alongside the new data.
One interesting issue that I ran into here was that if I tried to simulate
posterior predictive samples for multiple datapoints, the method
fit.extract()
in pystan was *very slow*. I had to write stan code that produced samples
for a single datapoint, and then do a python list comprehension over all of
the datapoints in order to avoid this issue. I'm not exactly sure why this is,
but it is prohibitive and I should maybe look into it.
"""
import os
import numpy as np
import pystan
def simulate_data(theta_0, theta_1, n=100, seed=42):
"""Simulate some data."""
np.random.seed(seed)
X = np.random.uniform(low=-10, high=10, size=n)
mu = theta_0 + theta_1 * X
y = np.array([np.random.normal(loc=mu[i]) for i, _ in enumerate(X)])
return X, y
class StanPredictor:
"""Simple helper class for fitting a Stan model then predicting later.
The model is a 1D linear regression with unit normal uncertainty.
"""
def __init__(self, seed=42):
"""Set up model."""
self.seed = seed
self.theta_0 = None
self.theta_1 = None
self.model = None
def fit(self, X, y, thin=10, return_fit=False):
"""Fit to the training data."""
stan_data = dict(
X=X,
y=y,
n=len(y)
)
self.X_train = X
self.y_train = y
print("Compiling and fitting stan model...")
with suppress_stdout_stderr():
model = pystan.StanModel(file="fit.stan")
fit = model.sampling(data=stan_data, seed=self.seed)
self.theta_0 = fit["theta_0"].ravel()[::thin]
self.theta_1 = fit["theta_1"].ravel()[::thin]
if return_fit:
return fit
else:
return None
def _predict_single(self, X):
"""Produce samples from the predictive distribution.
Draw samples from p(y | X, X_train, y_train).
"""
stan_data = dict(
X=X,
n=len(self.theta_0),
theta_0=self.theta_0,
theta_1=self.theta_1
)
if self.model is None:
self.model = pystan.StanModel(file="predict.stan")
fit = self.model.sampling(
data=stan_data,
seed=self.seed,
iter=1,
chains=1,
algorithm="Fixed_param"
)
return fit["y_pred"].ravel()
def predict(self, X):
"""Predict for new observations.
Note this will run slower the first time it is used, because the
underlying stan code must be compiled.
"""
with suppress_stdout_stderr():
# suppress messages from stan as the predictions are made.
samples = np.array([self._predict_single(Xi) for Xi in X])
return samples
class suppress_stdout_stderr(object):
"""A context manager for doing a "deep suppression" of stdout and stderr.
Taken from https://github.com/facebook/prophet/issues/223.
"""
def __init__(self):
"""Open a pair of null files."""
self.null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
# Save the actual stdout (1) and stderr (2) file descriptors.
self.save_fds = (os.dup(1), os.dup(2))
def __enter__(self):
"""Assign the null pointers to stdout and stderr."""
os.dup2(self.null_fds[0], 1)
os.dup2(self.null_fds[1], 2)
def __exit__(self, *_):
"""Re-assign the real stdout/stderr back to (1) and (2)."""
os.dup2(self.save_fds[0], 1)
os.dup2(self.save_fds[1], 2)
# Close the null files
os.close(self.null_fds[0])
os.close(self.null_fds[1])
|
945403b02d8065e060468e5d7e03cc08d912d746
|
Taysem/Mypython_study
|
/笔试题目/找重.py
| 692 | 3.578125 | 4 |
#如何在排序数组中
# ,找出给定数字出现次数? 比如:{0,1,2,3,3,3,3,3,3,3,3,4,5,6,7,13,19}
k = {0,1,2,3,3,3,3,3,3,3,3,4,5,6,7,13,19}
def binFindUp(arr, key):
low = 0
high = len(arr) -1
while(low < high):
print("%d,%d" % (low, high))
mid = (low + high) / 2
if (arr[mid] <= key):
low = mid
else:
high = mid - 1
return low
def binFindDown(arr, key):
low = 0
high = len(arr) -1
while(low < high):
print("%d,%d" % (low, high))
mid = (low + high) / 2
if (arr[mid] >= key):
high = mid
else:
low = mid + 1
return high
binFindUp(k, 3)
|
6bb04b5439007939731c87b21ad6f8bb9caf3343
|
1325052669/leetcode
|
/src/DP/easy/303_Range_Sum_Query_Immutable.py
| 533 | 3.546875 | 4 |
from typing import List
class NumArray:
def __init__(self, nums: List[int]):
self.cul_sum = [sum(nums[:i + 1]) for i in range(len(nums))]
def sumRange(self, i: int, j: int) -> int:
if i == 0:
return self.cul_sum[j]
return self.cul_sum[j] - self.cul_sum[i - 1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
def main():
print(NumArray([-2, 0, 3, -5, 2, -1]).sumRange(0,4))
if __name__=='__main__':
main()
|
c14a4e2d112f04020cadcbae628c636bb0792e85
|
dilshod-Cisco/PythonBasics
|
/dictionaries.py
| 1,264 | 4.09375 | 4 |
# Dictionaries - data structure, mutable, {key1: value1, key2: value2}
# in Java > Hashmap, Hashtable, Hashset >> hashing algoritm to store the key-value pairs
# recap: list - data structure, mutable, [a,b]
cars = ['lexus', 'bugatti', 'bmw', 'ferrari']
# recap: Tuple - data structure, immutable, (a,b)
cars = ('lexus', 'bugatti', 'bmw', 'ferrari')
# stores the values as key-value pair
# Must know:
# create, modify (add elements, remove elements, reset ), loop through elements
students = {} # empty dictionary
students1 = dict() # creates empty dictionary, converts to a dictionary
student1 = {'name': 'Hamza', 'gpa': 3.8}
student2 = {'name': 'Alexa', 'gpa': 3.9}
# Accessing the value of Dictionary, as in list with >> cars[0]
print(student1)
print(student1['name'], student1['gpa'])
print(f"Next student is {student2['name']} with GPA = {student2['gpa']}")
# Assigning the value
student1['gpa'] = 3.7 # if key is existing this will reset the value, new gpa=3.7
print(student1)
student1['state'] = 'NY' # if key does not exist, then it will create new key-value pair
print(student1)
print(sorted(student1)) # only sorted keys are printed as a list
del student1['state']
print(student1)
|
478156b8bab8b770b932bb2690a2c178c2d4ca0d
|
gv1410/it-academy_homework-4_ifelse_and_BMI_calc_v.20
|
/homework_ifelse_ХолдеевАлексей.py
| 2,124 | 3.984375 | 4 |
cycle = True
while cycle:
a_value = int(input('Введите первое значение (Значение А): '))
b_value = int(input('Введите второе значение (Значение Б): '))
c_value = int(input('Введите третье значение (Значение С): '))
# Если нет ни ондого нуля - вывести: "Нет нулевых значений!!! :
a_value > 0 and b_value > 0 and c_value > 0 and print('Нет нулевых значений!')
# Вывести первое ненулевое значение. Если введены все нули - вывести "Введены все нули!":
value = a_value or b_value or c_value
value > 0 and print('Первое не нулевое значение: ' + str(value))
value == 0 and print('Все значения равны нулю!')
if a_value > (b_value + c_value):
print('Первое значение больше чем сумма второго и третьего вывести значение(a - b - c) = ' + str(a_value - b_value - c_value))
if a_value < (b_value + c_value):
print('Первое значение меньше чем сумма второго и третьего вывести значение(b + c - a) = ' + str(b_value + c_value - a_value))
if a_value > 50 and b_value > a_value or c_value > a_value:
# Если первое значение больше 50 и при этом одно из оставшихся значение больше первого вывести "Вася":
print('Вася')
if a_value > 5 or b_value == 7 and c_value == 7:
# Если первое значение больше 5 или оба из оставшихся значений равны 7 вывести "Петя":
print('Петя')
question = input('\n Закончить работу с программой? (да / нет): ')
if question == 'да':
cycle = False
elif question == 'нет':
cycle = True
|
a0c4e2a0847b0a97ad751c8fc1cf58f77015ce43
|
liuliqiu/study
|
/competition/euler/source/p048.py
| 413 | 3.734375 | 4 |
##The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
##
##Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
def f(n):
result = 1
for i in range(1, n + 1):
result = (result * n) % (10 ** 10)
if result == 0:
return 0
return result
def fi(n):
return sum([f(i) for i in range(1, n + 1)]) % (10 ** 10)
print(fi(1000))
|
25c9fb84ff75f764049e7273410bdb6a67a71bea
|
mitra97/Calculator
|
/Calculator.py
| 5,528 | 3.5625 | 4 |
import math
from tkinter import *
#save numbers to a string, then just convert it to an int.
class Calculator:
def __init__(self):
self.opcode = ""
self.firstIn = ""
self.secondIn = ""
self.total = 0.0
self.window = Tk()
self.entry = Entry(self.window, width=66, bg="white")
self.entry.grid(row=0, column=0, columnspan=5)
self.buttonFrame = Frame(self.window)
self.buttonFrame.grid(row=3, column=3, columnspan=5)
Button(self.buttonFrame, text = "7", height = 5, width = 10, command=lambda: self.getter("7")).grid(row = 1, column = 0)
Button(self.buttonFrame, text = "8", height = 5, width = 10, command=lambda: self.getter("8")).grid(row = 1, column = 1)
Button(self.buttonFrame, text = "9", height = 5, width = 10, command=lambda: self.getter("9")).grid(row = 1, column = 2)
Button(self.buttonFrame, text = "+", height = 5, width = 10, command=lambda: self.getter("+")).grid(row = 1, column = 3)
Button(self.buttonFrame, text = "4", height = 5, width = 10, command=lambda: self.getter("4")).grid(row = 2, column = 0)
Button(self.buttonFrame, text = "5", height = 5, width = 10, command=lambda: self.getter("5")).grid(row = 2, column = 1)
Button(self.buttonFrame, text = "6", height = 5, width = 10, command=lambda: self.getter("6")).grid(row = 2, column = 2)
Button(self.buttonFrame, text = "-", height = 5, width = 10, command=lambda: self.getter("-")).grid(row = 2, column = 3)
Button(self.buttonFrame, text = "1", height = 5, width = 10, command=lambda: self.getter("1")).grid(row = 3, column = 0)
Button(self.buttonFrame, text = "2", height = 5, width = 10, command=lambda: self.getter("2")).grid(row = 3, column = 1)
Button(self.buttonFrame, text = "3", height = 5, width = 10, command=lambda: self.getter("3")).grid(row = 3, column = 2)
Button(self.buttonFrame, text = "x", height = 5, width = 10, command=lambda: self.getter("x")).grid(row = 3, column = 3)
Button(self.buttonFrame, text = ".", height = 5, width = 10, command=lambda: self.getter(".")).grid(row = 4, column = 0)
Button(self.buttonFrame, text = "0", height = 5, width = 10, command=lambda: self.getter("0")).grid(row = 4, column = 1)
Button(self.buttonFrame, text = "=", height = 5, width = 10, command=lambda: self.getter("=")).grid(row = 4, column = 2)
Button(self.buttonFrame, text = "/", height = 5, width = 10, command=lambda: self.getter("/")).grid(row = 4, column = 3)
Button(self.buttonFrame, text = "sin", height = 5, width = 10, command=lambda: self.getter("sin")).grid(row = 3, column = 4)
Button(self.buttonFrame, text = "cos", height = 5, width = 10, command=lambda: self.getter("cos")).grid(row = 2, column = 4)
Button(self.buttonFrame, text = "tan", height = 5, width = 10, command=lambda: self.getter("tan")).grid(row = 1, column = 4)
Button(self.buttonFrame, text = "CE", height = 5, width = 10, command=lambda: self.getter("CE")).grid(row = 4, column = 4)
self.window.mainloop()
def getter(self, button_id):
if button_id == "CE":
self.firstIn = ""
self.secondIn = ""
self.opcode = ""
self.total = 0.0
self.entry.delete(0,END)
if button_id != "+" and button_id != "-" and button_id != "x" and button_id != "=" and button_id != "/" and self.opcode == "" and button_id != "CE" and button_id != "sin" and button_id != "cos" and button_id != "tan":
self.firstIn += button_id
self.entry.insert(len(self.firstIn), button_id)
if (button_id == "+" or button_id == "-" or button_id == "x" or button_id == "/" or button_id == "sin" or button_id == "cos" or button_id == "tan") and button_id != "CE" and self.total == 0.0:
self.opcode = button_id
self.entry.insert(len(self.firstIn), button_id)
if button_id != "+" and button_id != "-" and button_id != "x" and button_id != "=" and button_id != "/" and self.opcode != "" and button_id != "CE" and button_id != "sin" and button_id != "cos" and button_id != "tan":
self.secondIn += button_id
self.entry.insert(len(self.firstIn + self.opcode + self.secondIn), button_id)
if self.total != 0 and (button_id == "+" or button_id == "-" or button_id == "x" or button_id == "/"):
self.firstIn = str(self.total)
self.opcode = button_id
self.entry.insert(len(self.firstIn), button_id)
self.secondIn = ""
if button_id == "=":
self.entry.delete(0,END)
if self.opcode == "+":
self.total = float(self.firstIn) + float(self.secondIn)
elif self.opcode == "-":
self.total = float(self.firstIn) - float(self.secondIn)
elif self.opcode == "x":
self.total = float(self.firstIn) * float(self.secondIn)
elif self.opcode == "/":
self.total = float(self.firstIn) / float(self.secondIn)
elif self.opcode == "sin":
self.total = math.sin(float(self.secondIn))
elif self.opcode == "cos":
self.total = math.cos(float(self.secondIn))
elif self.opcode == "tan":
self.total = math.tan(float(self.secondIn))
self.entry.insert(0, self.total)
calc = Calculator()
|
725e7b28cbec85d659d2bde65624f4ada215ecfe
|
Jimmykusters/DroneCamBase
|
/Cam_View.py
| 494 | 3.578125 | 4 |
import math
def f(h, alpha, beta, input_is_degree=False):
if input_is_degree:
alpha = math.radians(alpha)
beta = math.radians(beta)
c = h/math.cos(alpha/2)
l1 = 2*(math.sqrt(math.pow(c, 2) - math.pow(h, 2)))
# l1 = (c*2 - h)*0.5 * 2
print("l1 = " + str(l1))
c2 = h/math.cos(beta/2)
l2 = 2*(math.sqrt(math.pow(c2, 2) - math.pow(h, 2)))
# l2 = (c2*2 - h)*0.5 * 2
print("l2 = " + str(l2))
return l1 * l2
print(f(90, 53.50, 41.41, True))
|
908ee1b01377141b0f58317fb7035c935cc313cc
|
zhangfuli/leetcode
|
/手把手刷动态规划/贪心类型问题/55. 跳跃游戏.py
| 1,043 | 3.53125 | 4 |
# 给定一个非负整数数组nums ,你最初位于数组的 第一个下标 。
# 数组中的每个元素代表你在该位置可以跳跃的最大长度。
# 判断你是否能够到达最后一个下标。
#
# 示例1:
#
# 输入:nums = [2,3,1,1,4]
# 输出:true
# 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
# 每一步都计算一下从当前位置最远能够跳到哪里,
# 然后和一个全局最优的最远位置 farthest 做对比,通过每一步的最优解,更新全局最优解,这就是贪心。
class Solution:
def canJump(self, nums):
far = 0
for i in range(len(nums) - 1):
far = max(far, i + nums[i])
# 跳不动了,没有跳到i这个位置
print(far)
if far <= i:
return False
print(far)
print(len(nums))
return far >= len(nums) - 1
solution = Solution()
print(solution.canJump([5, 9, 3, 2, 1, 0, 2, 3, 3, 1, 0, 0]))
|
d825cb3caaef587e172c6c7351613f1d2e987fa7
|
akshays0911/CodeCamp
|
/MIscellaneous/Google/Google_interview_question2.py
| 1,192 | 3.921875 | 4 |
"""
Consider an undirected tree with N nodes, numbered from 1 to N.
Each node has a label associated with it, which is an integer
value. Different nodes can have the same label.
Write a function that, given a zero indexed array A of length N,
where A[j] is the label value of the (j + 1)-th node in the tree
and a zero-indexed array E of length K = (N – 1) * 2 in which the
edges of the tree are described, returns the length of the longest
path such that all the nodes on that path have the same label.
The length is the number of edges in that path.
"""
#@author- Akshay Swaminathan
"""
A = [1,1,1,2,2]
E = [1,2,1,3,2,4,2,5]
def solution(A,E):
path = [1]
for i in range(len(A)):
if (2*i) < len(A) and (A[i]) == A[2*i]:
path[-1] += 1
elif (2 * (i+1)<len(A)) and (A[i]) == A[2*i+1]:
path[-1] += 1
return(path[0])
print (sol(A))
"""
def solution(A,E):
path = [1]
for i in range(len(A)):
if (2*i) < len(A) and (A[i]) == A[2*i]:
path[-1] += 1
elif (2 * (i+1)<len(A)) and (A[i]) == A[2*i+1]:
path[-1] += 1
return(path[0])
print (solution(A,E))
|
38b28278f5c8028066ee6a1b45a1185c3355e3cd
|
Dioni1195/holbertonschool-higher_level_programming
|
/0x0C-python-almost_a_circle/models/rectangle.py
| 4,171 | 3.765625 | 4 |
#!/usr/bin/python3
""" This module contains the class Rectangle """
from models.base import Base
class Rectangle(Base):
""" This class is to build a rectangle with different
parameters
args:
__width(int): The width of the rectangle
__height(int): The height of the rectangle
__x(int): Position in x axis
__y(int): Position in y axis
id(int): Is the golbal identifier,
public instance attribute
attr: __width(int): The width of the rectangle
__height(int): The height of the rectangle
__x(int): Position in x axis
__y(int): Position in y axis
id(int): Is the golbal identifier,
public instance attribute
"""
def __init__(self, width, height, x=0, y=0, id=None):
super().__init__(id)
self.width = width
self.height = height
self.x = x
self.y = y
@property
def width(self):
""" This property manage the width of
the rectangle
"""
return self.__width
@width.setter
def width(self, value):
if type(value) != int:
raise TypeError("width must be an integer")
elif value <= 0:
raise ValueError("width must be > 0")
self.__width = value
@property
def height(self):
""" This property manage the height of
the rectangle
"""
return self.__height
@height.setter
def height(self, value):
if type(value) != int:
raise TypeError("height must be an integer")
elif value <= 0:
raise ValueError("height must be > 0")
self.__height = value
@property
def x(self):
""" This property manage the position x
of the rectangle
"""
return self.__x
@x.setter
def x(self, value):
if type(value) != int:
raise TypeError("x must be an integer")
elif value < 0:
raise ValueError("x must be >= 0")
self.__x = value
@property
def y(self):
""" This property manage the position y
of the rectangle
"""
return self.__y
@y.setter
def y(self, value):
if type(value) != int:
raise TypeError("y must be an integer")
elif value < 0:
raise ValueError("y must be >= 0")
self.__y = value
def area(self):
""" This method calculate the area of the rectangle """
return self.width * self.height
def display(self):
""" This method prints the instance in the stdout """
width = self.width
height = self.height
x = self.x
y = self.y
for d_y in range(y):
print()
for h in range(height):
if x != 0:
print(" " * x, end="")
print("#" * width)
def __str__(self):
""" This method return the str representation of the instance """
name = self.__class__.__name__
id = self.id
x = self.x
y = self.y
wid = self.width
hei = self.height
return "[{}] ({}) {}/{} - {}/{}".format(name, id, x, y, wid, hei)
def update(self, *args, **kwargs):
""" This method update the the attributes of the
instance
Args:
*args: The arguments passed by the user
"""
if len(args) != 0:
try:
self.id = args[0]
self.width = args[1]
self.height = args[2]
self.x = args[3]
self.y = args[4]
except IndexError:
pass
else:
for i in kwargs.keys():
try:
getattr(self, i)
except Exception as er:
raise er
setattr(self, i, kwargs[i])
def to_dictionary(self):
""" Return the dictionary representation of
the instances
"""
dict_rect = {
'x': self.x, 'y': self.y, 'id': self.id,
'height': self.height, 'width': self.width}
return dict_rect
|
7e97e2291242bda807b55d994b2cdc091e2a7259
|
tor1414/python_programs
|
/131_h2_comparing_circles.py
| 6,855 | 4.21875 | 4 |
"""
Victoria Lynn Hagan
Victoria014
2/10/2014
Homework 2 - CSC 131
"""
import math
class Circle2D(object):
"""A circle is represented by the value of it's radius and the corrdinates of it's center"""
def __init__(self, x = 0, y = 0, radius = 0):
"""Intializes the X-corrdinate of the center"""
self._x = x
"""Intializes the Y-corridinate of the center"""
self._y = y
"""Intializes the radius"""
self._radius = radius
def __str__(self):
"""Return a string representation of a circle"""
return 'Circle with center (' + str(self._x) + ' , ' + str(self._y) + ') and radius ' + str(self._radius)
def getX(self):
"""Returns the X-corrdinate of the center"""
return self._x
def getY(self):
"""Returns the Y-corrdinate of the center"""
return self._y
def getRadius(self):
"""Returns the Radius"""
return self._radius
def setRadius(self, radius = 0):
"""Intiallizes a new value for the Radius"""
self._radius = radius
def getArea(self):
"""Returns Area"""
return self._radius * self._radius * math.pi
def getPerimeter(self):
"""Returns Perimeter"""
return 2 * math.pi * self._radius
def containsPoint(self, x, y):
"""Tests to see if a point is within the circle"""
d = math.sqrt((x - self._x)** 2 + (y - self._y)** 2)
if d < self._radius:
return True
else:
return False
def contains(self, circle2D):
"""Tests to see if anothoer circle is within the circle"""
d = math.sqrt((circle2D._x - self._x) ** 2 + (circle2D._y - self._y) ** 2)
if d <= self._radius:
if circle2D._radius + d <= self._radius:
return True
else:
return False
else:
return False
def overlaps(self, circle2D):
"""Tests to see if anther circle overlaps with the circle"""
d = math.sqrt((circle2D._x - self._x) ** 2 + (circle2D._y - self._y) ** 2)
if d <= abs(circle2D._radius + self._radius):
return True
else:
return False
def __cmp__(self, anotherCircle):
"""Compares two circles based on the magnitude of each circles's radius"""
if self._radius < anotherCircle._radius:
return -1
elif self._radius > anotherCircle._radius:
return 1
else:
return 0
def __eq__(self, anotherCircle):
"""Checks for equality between two circles based on each circle's radius"""
if self is anotherCircle:
return True
elif type(self) != type(anotherCircle):
return False
else:
return self._radius == anotherCircle._radius # and \
# self._x == anotherCircle._x and \
# self._y == anotherCircle._y
# I would personally also compare the x and y to validate
# that they are the same circle since in math the center is
# part of what defines a circle alongside the radius
def __ne__(self, anotherCircle):
"""Checks for inequality between two circles based on each circles radius"""
return not self == anotherCircle
def __contains__(self, anotherCircle):
"""Tests to see if another circle is within the circle using the 'in' operator"""
d = math.sqrt((anotherCircle._x - self._x) ** 2 + (anotherCircle._y - self._y) ** 2)
if d <= self._radius:
if anotherCircle._radius + d <= self._radius:
return True
else:
return False
#I included the following method because your instructions sounded like
# you wanted the possiblity of testing a (x,y) tuple using the special
# method __contains__(self, item). If I am incorrect I apologize.
def __contains__(self, item):
"""Tests to see if an item based on type is within the circle using the 'in' operator"""
if type(item) == type(self):
d = math.sqrt((item._x - self._x) ** 2 + (item._y - self._y) ** 2)
if d <= self._radius:
if item._radius + d <= self._radius:
return True
else:
return False
elif type(item) == type(tuple(item)):
x = item[0]
y = item[1]
d = math.sqrt((x - self._x)** 2 + (y - self._y)** 2)
if d < self._radius:
return True
else:
return False
else:
return False
def main():
x = input("Enter x coordinate for the center of circle 1: ")
y = input("Enter y coordinate for the center of circle 1: ")
r = input("Enter the radius of circle 1: ")
c1 = Circle2D(x, y, r)
print c1
x = input("\nEnter x coordinate for the center of circle 2: ")
y = input("Enter y coordinate for the center of circle 2: ")
r = input("Enter the radius of circle 2: ")
c2 = Circle2D(x, y, r)
print c2
#Test the getArea() and getPerimeter() methods
print "\nArea of a %s is %0.2f" % (c1, c1.getArea())
print "Perimeter of a %s is %0.2f" % (c1, c1.getPerimeter())
print "\nArea of a %s is %0.2f" % (c2, c2.getArea())
print "Perimeter of a %s is %0.2f" % (c2, c2.getPerimeter())
#-------------------
#Test containsPoint() method
print "\nResult of c1.containsPoint(c2.getX( ), c2.getY( )) is",
print c1.containsPoint(c2.getX( ), c2.getY( ))
#Test contains() method
if c1.contains(c2):
print "\n%s contains %s" % (c1, c2)
else:
print "\n%s does not contain %s" % (c1, c2)
print "\nResult of c2.contains(c1) is",
print c2.contains(c1)
#----------------
#Test overlap() method
if c1.overlaps(c2):
print "\n%s overlaps with %s" % (c1,c2)
else:
print "\n%s does not overlap with %s" % (c1,c2)
#--------------
#Test overloaded in operator
print "\nResult of c2 in c1 is", c2 in c1
#Testing overloaded comparison and equality operators
#Something similar to this
print "\nTesting overloaded comparison operators..."
print "c1 == c2?", c1 == c2
print "c1 != c2?", c1 != c2
print "c1 < c2?", c1 < c2
print "c1 <= c2?", c1 <= c2
print "c1 > c2?", c1 > c2
print "c1 >= c2?", c1 >= c2
print 'c1 == "Hello"?', c1 == "Hello"
print 'c1 != "Hello"?', c1 != "Hello"
main()
|
350594cc5401599935cb05d485e7ad7b2878b00f
|
Xanonymous-GitHub/main
|
/python/3n+1 uva.py
| 1,493 | 3.609375 | 4 |
import sys
sys.setrecursionlimit(10000000)
# > The recursive range of the title requirement may exceed the limit.
while True:
# > The problem requires multiple test materials.
try:
i, j = map(int, input().split())
# > i,j is the range of data entered by user.
except:
break
# > Stop the program when the input is over.
def caculate(i, j, maxlength, tmp, step):
if i > j:
print(maxlength)
return
# > Print out the maximum length and end the def when out of range.
while True:
# > start to caculate the 3n+1 of tmp.
step += 1
# > Recording steps.
if tmp == 1:
break
# > Stop calculation until the calculated value is equal to 1.
tmp = (3*tmp+1 if tmp % 2 != 0 else tmp/2)
# > If the number is odd, multiply by 3 and add 1 else divide by 2.
if step > maxlength:
maxlength = step
# > If the steps in this number is greater than known, replace it.
return caculate(i+1, j, maxlength, i+1, 0)
# > Use recursive to calculate the next number.
print(i, j, end=' ')
# > Display the range of the input first and leave a gap.
if i > j:
i, j = j, i
# > Exchange to ensure that i is the starting calculation point.
caculate(i, j, -1, i, 0)
# > Start the first calculation.
|
a57c7ded65cacaff1d33a7a039dceed0803ea656
|
adonaifariasdev/CursoemVideo
|
/jokenpo.py
| 2,968 | 3.578125 | 4 |
from random import randint
from time import sleep
from os import system
opcao = 's'
contPC = 0
contUS = 0
while opcao != 'N':
print('='*40)
print('{:=^40}'.format(' JO KEN PO 2.0 '))
print('{:=^40}'.format(' Ceated By: Ten Adonai '))
print(' JOGADOR {} x {} COMPUTADOR'.format(contUS, contPC))
print('='*40)
print('''Suas opções:
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] TESOURA''')
itens = ('PEDRA', 'PAPEL', 'TESOURA')
#print(itens)
jogador = int(input('Qual a sua jogada? '))
computador = randint(0, 2)
sleep(0.5)
print('JO..')
sleep(0.5)
print('KEN..')
sleep(0.5)
print('PO..')
print(' {:=^40} '.format(' JO KEN PO '))
print('|{:^40}|'.format('RESULTADOS'))
print(' {:^40} '.format('-'*40))
print(' Jogador jogou {}'.format(itens[jogador]))
print(' Computador jogou {}'.format(itens[computador]))
print(' {:^40} '.format('-'*40))
if jogador == 0:
if computador == 0:
print(' EMPATE!!!')
elif computador == 1:
print(' COMPUTADOR VENCEU!!!')
contPC = contPC + 1
elif computador == 2:
print(' JOGADOR VENCEU!!!')
contUS = contUS + 1
elif jogador == 1:
if computador == 0:
print(' JOGADOR VENCEU!!!')
contUS = contUS + 1
elif computador == 1:
print(' EMPATE!!!')
elif computador == 2:
print(' COMPUTADOR VENCEU!!!')
contPC = contPC + 1
elif jogador == 2:
if computador == 0:
print(' COMPUTADOR VENCEU!!!')
contPC = contPC + 1
elif computador == 1:
print(' JOGADOR VENCEU!!!')
contUS = contUS + 1
elif computador == 2:
print(' EMPATE!!!')
else:
print('JOGADA INVÁLIDA! TENTE NOVAMENTE!')
print(' {:^40} '.format('='*40))
print('|{:^40}|'.format('PLACAR ELETRÔNICO'))
print(' {:^40} '.format('-' * 40))
print(' JOGADOR {} x {} COMPUTADOR'.format(contUS, contPC))
print(' {:^40} '.format('-' * 40))
opcao = str(input('CONTINUAR? [S/N]')).upper()
if opcao == 'N':
print('PROCESSANDO...')
sleep(2)
print('SAINDO...')
sleep(1)
print(' {:^40} '.format('-' * 40))
print('|{:^40}|'.format('PLACAR ELETRÔNICO'))
print(' {:^40} '.format('-' * 40))
print(' JOGADOR {} x {} COMPUTADOR'.format(contUS, contPC))
print(' {:^40} '.format('-' * 40))
print(' {:^40} '.format('='*40))
print('{:^40}'.format('MUITO OBRIGADO POR JOGAR!'))
print('{:^40}'.format('VOLTE SEMPRE!'))
print('{:^40}'.format('by: TEN ADONAI'))
print('{:^40}'.format('contact: [email protected]'))
print(' {:^40} '.format('='*40))
sleep(3)
system('cls')
|
b97f777dbf1bb766fb80a08dc358fc25ad8123b8
|
jedzej/tietopythontraining-basic
|
/students/ryba_paula/lesson_11_argparse_and_math/regex_search_arg.py
| 695 | 3.53125 | 4 |
import re
import os
import argparse
import sys
def arg_input(args):
parser = argparse.ArgumentParser(description="Regex search")
parser.add_argument('-r', '--regex', help="Regex to be checked",
required=True)
results = parser.parse_args(args)
return results.regex
def regex_search():
reg = arg_input(sys.argv[1:])
regex = re.compile(reg)
files_list = os.listdir('.')
for el in files_list:
if el.endswith(".txt"):
with open(el) as infile:
for line in infile:
if regex.match(line):
print("Matched! " + line)
if __name__ == '__main__':
regex_search()
|
401739de61eaa79b8533f46a6587b0180c834dcc
|
biztudio/JustPython
|
/syntaxlab/src/play_collection.py
| 1,179 | 3.890625 | 4 |
names_list1 = ['sTevEn lOBs',
'coCo lee',
'JAck zhaNG',
'LiSa ChEn',
'elSA Y Shen',
'georgE w bUsH',
'PETER cHeN',
'brUce Ho',
'biLL W clinTON',
'ciRAlI Clinton',
'Yang SHEN',
'robin zhAng',
'Bruce LEE']
# 练习一,把一组大小写不规范的名字 names_list1 转成首字母大写的一组名字
# 练习二,把练习一中大小写规范好的名字列表姓氏(最后一个词作为姓氏)分组, 组名就是姓氏
# 形如 {'Jobs':{'Steven Jobs'}, 'Zhang':{'Robin Zhang','Jack Zhang'} ... }
def get_normalize_names(names_list):
return [' '.join([n[0].upper() + n[1:].lower() for n in name.split(' ')]) for name in names_list]
def get_names_group(names_list):
names_group = {}
for fname in {name.split(' ')[-1] for name in set(names_list)}:
names_group[fname] = {name for name in names_list if name.split(' ')[-1] == fname}
return names_group
names_list2 = get_normalize_names(names_list1)
names_grouped = get_names_group(names_list2)
print(names_list1)
print(names_list2)
print(names_grouped)
print(names_grouped['Shen'])
|
b719f01edcd0e7424c5d1b459a1e67e93630067c
|
Seongju-Lee/code-analysis
|
/pedal/tifa/literal_definitions.py
| 1,224 | 3.828125 | 4 |
def are_literals_equal(first, second):
if first is None or second is None:
return False
elif type(first) != type(second):
return False
else:
if isinstance(first, LiteralTuple):
if len(first.value) != len(second.value):
return False
for l, s in zip(first.value, second.value):
if not are_literals_equal(l, s):
return False
return True
else:
return first.value == second.value
class LiteralValue:
'''
A special literal representation of a value, used to represent access on
certain container types.
'''
def __init__(self, value):
self.value = value
class LiteralNum(LiteralValue):
'''
Used to capture indexes of containers.
'''
def type(self):
return NumType()
class LiteralBool(LiteralValue):
def type(self):
return BoolType()
class LiteralStr(LiteralValue):
def type(self):
return StrType()
class LiteralTuple(LiteralValue):
def type(self):
return TupleType(self.value)
class LiteralNone(LiteralValue):
def type(self):
return LiteralNone()
|
5443557bf0ed37926c5e063c92fab3dda1b91207
|
jonasc/constant-workspace-algos
|
/geometry/ray.py
| 3,740 | 4.03125 | 4 |
"""Defines a ray class with various helper methods."""
from typing import Optional, Union
from .line import Line
from .line_segment import LineSegment
from .point import Point
class Ray(object):
"""Defines a ray in R^2."""
def __init__(self, a: Point, b: Point):
"""Initialize a new ray starting at a and going through b."""
assert isinstance(a, Point)
assert isinstance(b, Point)
self.a = a
self.b = b
def intersects(self, other: LineSegment) -> bool:
"""Return whether the ray intersects some other object."""
if isinstance(other, LineSegment):
turn_other_a = Point.turn(self.a, self.b, other.a)
turn_other_b = Point.turn(self.a, self.b, other.b)
if turn_other_a == turn_other_b and turn_other_a != Point.NO_TURN:
return False
# TODO: Special case: both are collinear
turn_self_a = Point.turn(other.a, other.b, self.a)
turn_self_b = Point.turn(other.a, other.b, self.b)
# This is the normal line segment intersection case
if turn_self_a != turn_self_b:
return True
# From here on both points of the ray lie on the same side of the
# line segment
# We check the orientation of the ray -- the ray and the line
# segment intersect iff the orientation and the ray points are on
# different sides of the line segment.
check_point = other.b + (self.b - self.a)
check_point_turn = Point.turn(other.a, other.b, check_point)
return check_point_turn != turn_self_a
raise NotImplementedError()
def properly_intersects(self, other: LineSegment) -> bool:
"""Return whether the ray properly intersects some other object."""
if isinstance(other, LineSegment):
turn_other_a = Point.turn(self.a, self.b, other.a)
turn_other_b = Point.turn(self.a, self.b, other.b)
if turn_other_a == Point.NO_TURN or turn_other_b == Point.NO_TURN:
return False
return self.intersects(other)
raise NotImplementedError()
def intersection_point(self, segm: Union[LineSegment, Line]) -> Optional[Point]:
"""Return the intersection point of this ray with the given line (segment)."""
assert isinstance(segm, (LineSegment, Line))
if self.b == segm.b or self.b == segm.a:
return self.b
if self.a == segm.b or self.a == segm.a:
return self.a
a1 = self.b.x - self.a.x
b1 = segm.a.x - segm.b.x
c1 = segm.a.x - self.a.x
a2 = self.b.y - self.a.y
b2 = segm.a.y - segm.b.y
c2 = segm.a.y - self.a.y
# TODO, FIXME: Dirty fix, we assume there are no intersecting parallel
# edges
if a1 * b2 - a2 * b1 == 0:
return None
s = (c1 * b2 - c2 * b1) / (a1 * b2 - a2 * b1)
t = (a1 * c2 - a2 * c1) / (a1 * b2 - a2 * b1)
if s == 0:
return self.a
if s == 1:
return self.b
if t == 0:
return segm.a
if t == 1:
return segm.b
# Intersection lies on the wrong side of the ray
if s < 0:
return None
# Intersection lies outside of line segment
if isinstance(segm, LineSegment) and (t < 0 or t > 1):
return None
return Point(
self.a.x + s * a1,
self.a.y + s * a2,
)
def __repr__(self) -> str:
"""Return nice string representation for console."""
return '{class_}({a!r}, {b!r})'.format(class_=self.__class__.__name__, a=self.a, b=self.b)
|
5e318e667844aa8a12294b7ea8d0390d3ec9c8b1
|
adamzoltan/OOP
|
/Python/Garden/garden.py
| 717 | 3.8125 | 4 |
from plants import Plant
class Garden():
def __init__(self):
self.plants = []
def add(self, plant):
self.plants.append(plant)
def garden_status(self):
for plant in self.plants:
plant.status()
def count_dry_plants(plants):
counter = 0
for plant in plants:
if plant.needs_water():
counter += 1
return counter
def water_plants(self, water_amount):
print(f"Watering with {water_amount}")
dry_plants = Garden.count_dry_plants(self.plants)
for plant in self.plants:
if plant.needs_water():
plant.water_level = (water_amount / dry_plants) * plant.absorbtion
|
b52636fb61cac3ee23fb2325f9944bc3922c6488
|
Aaron1515/Richmond_High
|
/Excercise/ex4_3.py
| 756 | 3.953125 | 4 |
import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(11, gpio.IN, gpio.PUD_UP)
gpio.setup(13, gpio.OUT)
while True:
button_state = (gpio.input(11)==0)
# Directions: Fill in the conditions for the "if" and "then" statements below
# and the code such that when the button is held down, the LED
# light will blink 3 times.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BEGIN CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
if #button is pressed# :
#Add for loop to make LED light blink 3 times here#
print ("BUTTON PRESSED")
else:
#Code for default state of LED light (off)#
print ("Button is not pressed")
time.sleep(0.5)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ END CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
gpio.cleanup()
|
c9756c5f2a8a4a73e31b1536e4cbe3f67d2da084
|
DanielMGuedes/Exercicios_Python_Prof_Guanabara
|
/Aulas_Python/Python/Exercícios/Exe072 - contagem por extenso.py
| 424 | 3.953125 | 4 |
cont = 'zero', 'um', 'dois','três', 'quatro', 'cinco', 'seis', 'sete', '...'
while True:
núm = int(input('Digite um número entre 0 e 20: '))
if 0<= núm <= 20:
break
print('tente novamente. ', end='')
print(f'Você digitou {cont[núm]}')
'''Explicação:
o cont está recebendo o valor que escrevemos por
extenso na posição, correspondente a cada um 0 = zero, etc..
'''
COMPLETAR EXERCÍCIO....
|
15a1fc37a817d7024820100d8c1513e922db69cc
|
charliedmiller/coding_challenges
|
/flipping_an_image.py
| 371 | 3.796875 | 4 |
# Charlie Miller
# Leetcode - 832. Flipping an Image
# https://leetcode.com/problems/flipping-an-image/
# Written 2020-11-10
"""
Flip the row, then invert the value in a list comp
"""
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
result = [[px^1 for px in row[::-1]] for row in A]
return result
|
c4398765581c1260b4d074f49fcb4ee68784eed2
|
siddalls3135/cti110
|
/P4LAB_Siddall.py
| 298 | 3.71875 | 4 |
import turtle
t = turtle
t.shape()
t.speed(10)
t.width(3)
t.bgcolor('black')
t.begin_fill()
t.pencolor('silver')
t.fillcolor('teal')
for a in range(8):
for b in range(8):
t.forward(125)
t.left(45)
t.left(45)
t.end_fill()
t.hideturtle()
|
23ebf0e93553d51bf5b5a88489108038642aaaef
|
devscheffer/desafio-2-2020
|
/Assets/Notebooks/personal_function/Model_Missing_Value_Imputer.py
| 960 | 3.5625 | 4 |
# Criação de um objeto SimpleImputer
from sklearn.impute import SimpleImputer
from sklearn.impute import KNNImputer
import numpy as np
def Missing_Value_imputer():
imputer = KNNImputer(
n_neighbors=5
,missing_values=np.nan # os valores faltantes são do tipo ``np.nan`` (padrão Pandas)
,copy=True
)
return imputer
'''
# print(Missing_Value_imputer())
from sklearn.impute import KNNImputer
imputer = KNNImputer(
n_neighbors=5
,missing_values=np.nan # os valores faltantes são do tipo ``np.nan`` (padrão Pandas)
,copy=True
)
imputer = SimpleImputer(
missing_values=np.nan, # os valores faltantes são do tipo np.nan (padrão Pandas)
strategy= , # a estratégia escolhida é a alteração do valor faltante por uma constante
fill_value=0, # a constante que será usada para preenchimento dos valores faltantes é um int64=0.
verbose=0,
copy=True
)
'''
|
0e52d3c0e24e81e0afb04cf29e6b840d59caf808
|
wenquanlu/DP-Operations-Research-App
|
/app.py
| 1,886 | 3.96875 | 4 |
from resource import resource_allocation
from knapsack import knapsack_problem
print("#######\n" +
"# # ##### ###### ##### ## ##### # #### # # ####\n"+
"# # # # # # # # # # # # # ## # #\n"+
"# # # # ##### # # # # # # # # # # # ####\n"+
"# # ##### # ##### ###### # # # # # # # #\n"+
"# # # # # # # # # # # # # ## # #\n"+
"####### # ###### # # # # # # #### # # ####\n"+
" \n" +
"######\n" +
"# # ###### #### ###### ## ##### #### # #\n" +
"# # # # # # # # # # # # #\n" +
"###### ##### #### ##### # # # # # ######\n" +
"# # # # # ###### ##### # # #\n" +
"# # # # # # # # # # # # # #\n" +
"# # ###### #### ###### # # # # #### # #\n")
print("Welcome to Operations Researcher's helper!")
print("INFO: this helper allows you to solve\nResource Allocation Problem (alias: capital budgeting), use command: R\n\
Knapsack solver, use command: K\nTo end the program, use command: Q\nTo Print info again, use command: I")
while True:
print()
x = input("please enter command: ")
print()
if x == "Q":
print("Bye~")
break
if x == "I":
print("INFO: this helper allows you to solve\nResource Allocation Problem (alias: capital budgeting), use command: R\n\
Knapsack solver, use command: K\nTo end the program, use command: Q\nTo Print info again, use command: I")
if x == "R":
resource_allocation()
if x == "K":
knapsack_problem()
|
0e973a414cc363441a9ac2c0bbf932a4a060f8cb
|
heyyou3/atcoder
|
/abc179/c/main.py
| 192 | 3.515625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def resolve():
n = int(input())
ans = 0
for a in range(1, n):
ans += (n - 1) // a
return ans
def main():
print(resolve())
main()
|
79499040a0c83f119807e2b45e32a9ba4f262969
|
wwscthjm/python_work
|
/Chapter4_Deal _with_Lists/dimensions.py
| 327 | 3.84375 | 4 |
"""Tuple-元组"""
dimensions = (200, 50) #object in a tuple is immutable
print('Original dimensions:')
for dimension in dimensions:
print(dimension)
dimensions = (400, 100) #but a tuple is variable
print('\nModified dimension:')
for dimension in dimensions:
print(dimension)
|
7544eec4c12c40ff8d49c49fbdee6ed6b15d8e46
|
flerdacodeu/CodeU-2018-Group8
|
/ibalazevic/assignment2/q2.py
| 4,670 | 4.53125 | 5 |
import unittest
class Node:
"""
A class for a node of a binary tree.
- data - int, the content of a node.
- left_child - Node, pointer to the left child
of a current node.
- right_child - Node, pointer to the right child
of a current node.
"""
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class BinaryTree:
"""
A class representing a binary tree.
The assupmtion is that the tree does not
contain duplicate keys.
- root_data - content of the tree root.
"""
def __init__(self, root_data):
self.root = Node(root_data)
def insert_left(self, node, data):
"""
A method for inserting a left child of a node.
- node - Node, the current node.
- data - the data to insert to the left.
"""
node.left_child = Node(data)
def insert_right(self, node, data):
"""
A method for inserting a right child of a node.
- node - Node, the current node.
- data - the data to insert to the right.
"""
node.right_child = Node(data)
def find_node(self, node, key):
"""
A method that checks whether a key is present
in a binary tree.
- node - Node, the current node.
- key - the value of the Node to find.
Returns: True if the node is in the tree,
False otherwise.
"""
if not node:
return
if node.data == key:
return True
if not (self.find_node(node.left_child, key) or
self.find_node(node.right_child, key)):
return False
return True
def lowest_common_ancestor(self, key1, key2):
"""
A method for finding the lowest common ancestor of
two nodes in a binary tree.
- key1 - value of first of the nodes.
- key2 - value of second of the nodes.
Returns: value of the lowest common
ancestor node, raises KeyError if
either one of the keys is not present
in the tree.
"""
if not (self.find_node(self.root, key1) and
self.find_node(self.root, key2)):
raise KeyError("Key not present in the binary tree.")
else:
return self._lowest_common_ancestor_helper(self.root, key1, key2)
def _lowest_common_ancestor_helper(self, node, key1, key2):
"""
A method for finding the lowest common ancestor of
two nodes in a binary tree.
- node - Node, the root node of the tree.
- key1 - value of first of the nodes.
- key2 - value of second of the nodes.
Returns: value of the lowest common
ancestor node.
"""
if not node:
return None
if node.data == key1 or node.data == key2:
return node.data
left_subtree = self._lowest_common_ancestor_helper(node.left_child, key1, key2)
right_subtree = self._lowest_common_ancestor_helper(node.right_child, key1, key2)
if left_subtree and right_subtree:
return node.data
elif left_subtree:
return left_subtree
else:
return right_subtree
class BinaryTreeTest(unittest.TestCase):
def setUp(self):
self.tree = BinaryTree(7)
self.tree.insert_left(self.tree.root, 3)
self.tree.insert_right(self.tree.root, 4)
self.tree.insert_left(self.tree.root.left_child, 2)
self.tree.insert_right(self.tree.root.left_child, 5)
self.tree.insert_right(self.tree.root.right_child, 8)
self.tree.insert_left(self.tree.root.left_child.left_child, 1)
self.tree.insert_right(self.tree.root.left_child.left_child, 6)
def test_leaves_left(self):
self.assertEqual(self.tree.lowest_common_ancestor(1, 6), 2)
def test_leaves_both_sides(self):
self.assertEqual(self.tree.lowest_common_ancestor(1, 8), 7)
def test_combined_left(self):
self.assertEqual(self.tree.lowest_common_ancestor(1, 5), 3)
def test_middle_both_sides(self):
self.assertEqual(self.tree.lowest_common_ancestor(2, 4), 7)
def test_one_key_missing(self):
self.assertRaises(KeyError, self.tree.lowest_common_ancestor, 2, 11)
def test_both_keys_missing(self):
self.assertRaises(KeyError, self.tree.lowest_common_ancestor, 44, 11)
if __name__ == "__main__":
unittest.main()
|
3442a672ff0d964c16986cdaeb46fae885681228
|
Little-Captain/py
|
/Lean Python/calc.py
| 390 | 3.859375 | 4 |
def calc(a, op, b):
if op not in '+-/*':
return None, 'Operator must be +-/*'
try:
if op == '+':
result = a + b
elif op == '-':
result = a - b
elif op == '/':
result = a / b
else:
result = a * b
except Exception as e:
return None,e.__class__.__name__
return result,str(result)
|
d6193c977ac0aece825498859e3e01bc6e3e2e7e
|
mizhi/project-euler
|
/python/problem-52.py
| 770 | 3.875 | 4 |
#!/usr/bin/env python
# It can be seen that the number, 125874, and its double, 251748,
# contain exactly the same digits, but in a different order.
#
# Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and
# 6x, contain the same digits.
def samedigits(x,y):
xs = list(str(x))
ys = list(str(y))
xs.sort()
ys.sort()
return xs == ys
n = 1
while True:
print n
n2 = n * 2
if samedigits(n, n2):
n3 = n * 3
if samedigits(n2, n3):
n4 = n * 4
if samedigits(n3, n4):
n5 = n * 5
if samedigits(n4, n5):
n6 = n * 6
if samedigits(n5, n6):
break
n += 1
print n
|
58d8e4a3a9bf95d34687b65605282aea6418bd7f
|
lucasmfredmark/PyShips
|
/classes/BattleshipsGame.py
| 4,683 | 3.703125 | 4 |
from . import BattleshipsGameSettings
import copy
import random
class BattleshipsGame:
def __init__(self, player):
self.BOARD_SIZE = copy.deepcopy(BattleshipsGameSettings.BOARD_SIZE)
self.ships = copy.deepcopy(BattleshipsGameSettings.SHIPS)
self.board = [['#' for y in range(self.BOARD_SIZE)] for x in range(self.BOARD_SIZE)]
self.player = player
def place_ship(self, ship_length, ship_char, is_vertical, position_x, position_y):
if is_vertical:
for i in range(ship_length):
self.board[position_x + i][position_y] = ship_char
else:
for i in range(ship_length):
self.board[position_x][position_y + i] = ship_char
def validate_ship_placement(self, ship_length, is_vertical, position_x, position_y):
if not self.validate_position(position_x, position_y):
return False
elif is_vertical and ship_length + position_x >= self.BOARD_SIZE:
return False
elif not is_vertical and ship_length + position_y >= self.BOARD_SIZE:
return False
else:
if is_vertical:
for i in range(ship_length):
if self.board[position_x + i][position_y] != '#':
return False
else:
for i in range(ship_length):
if self.board[position_x][position_y + i] != '#':
return False
return True
def validate_position(self, position_x, position_y):
return 0 <= position_x < self.BOARD_SIZE and 0 <= position_y < self.BOARD_SIZE
def place_ships(self):
for ship in self.ships.keys():
valid_placement = False
while not valid_placement:
is_vertical = bool(random.getrandbits(1))
position_x = random.randint(0, self.BOARD_SIZE - 1)
position_y = random.randint(0, self.BOARD_SIZE - 1)
valid_placement = self.validate_ship_placement(self.ships[ship], is_vertical, position_x, position_y)
self.place_ship(self.ships[ship], ship[0], is_vertical, position_x, position_y)
def make_move(self, position_x, position_y):
if not self.validate_position(position_x, position_y):
return False
state = self.board[position_x][position_y]
if state == '#':
self.board[position_x][position_y] = '!'
return False
elif state == '@' or state == '!':
return False
else:
self.hit_ship(position_x, position_y)
self.board[position_x][position_y] = '@'
return True
def hit_ship(self, position_x, position_y):
for ship in self.ships.keys():
if self.board[position_x][position_y] == ship[0]:
ship_name = ship
break
self.ships[ship_name] -= 1
def check_win(self):
for ship_length in self.ships.values():
if ship_length != 0:
return False
return True
def print_board(self):
for x in range(self.BOARD_SIZE):
for y in range(self.BOARD_SIZE):
# shot was a hit
if self.board[x][y] == '@':
print('\x1b[6;30;42m' + " " + '\x1b[0m', end='')
# shot was a miss
elif self.board[x][y] == '!':
print('\x1b[0;30;41m' + " " + '\x1b[0m', end='')
# default
elif self.board[x][y] == '#':
print('\x1b[0;30;40m' + " " + '\x1b[0m', end='')
# ship
else:
print('\x1b[0;34;47m' + self.board[x][y] + '\x1b[0m', end='')
print()
print()
def play_game(self, rounds=1, debug=False):
total_shots = {}
for round_number in range(rounds):
shots = 0
max_shots = self.BOARD_SIZE ** 2
self.place_ships()
if debug:
self.print_board()
while shots < max_shots:
position_x, position_y = self.player.get_shot_position(self.ships)
hit = self.make_move(position_x, position_y)
if debug:
self.print_board()
self.player.hit_feedback(hit, self.ships)
shots += 1
if hit and self.check_win():
break
total_shots.setdefault(shots, 0)
total_shots[shots] += 1
self.__init__(self.player)
self.player.__init__()
return sorted(total_shots.items())
|
a99cf6fe24e5bab66224b668c6862c99a86d7b25
|
Comyn-Echo/leeCode
|
/字符串/KMP/1367. 二叉树中的列表.py
| 3,374 | 3.765625 | 4 |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSubPath(self, head, root):
"""
:type head: ListNode
:type root: TreeNode
:rtype: bool
"""
# 计算next数组, next[i]代表前i个字符串的最长子串
def getnext(s):
n = len(s)
next = [0, 0] # 第一个0代表空字符串
for i in range(2, n + 1):
# print(next, s, i-1)
if s[next[i - 1]] == s[i - 1]:
next.append(next[i - 1] + 1)
else:
j = next[next[i - 1]]
while j > 0:
if s[j] == s[i - 1]:
next.append(j + 1)
break
j = next[j]
if j == 0:
if s[i - 1] == s[0]:
next.append(1)
else:
next.append(0)
return next
needle = []
while head:
needle.append(head.val)
head = head.next
next = getnext(needle)
print(next)
# 构造有限状态机
def kmp(s, next): # 一个状态机
n = len(s)
state = {'other': True}
for i in s:
state[i] = True
matrix = [{} for i in range(n + 1)]
# 初始化
for i in state:
matrix[0][i] = 0
matrix[0][s[0]] = 1
# 归纳法进行递推
for i in range(1, n + 1):
j = i
while j > 0:
if j >= n:
j = next[j]
continue
char = s[j]
if char not in matrix[i]:
matrix[i][char] = j + 1
j = next[j]
if j == 0:
if s[0] not in matrix[i]:
matrix[i][s[0]] = 1
for k in state:
if k not in matrix[i]:
matrix[i][k] = 0
return matrix, state
matrix, state = kmp(needle, next)
print(matrix)
self.flag = False
# kmp
def dfs(stateNow, node):
# print(node.val,stateNow,len(needle))
val = node.val
statetmp = None
if stateNow == len(needle):
self.flag = True
if val in matrix[stateNow]:
statetmp = matrix[stateNow][val]
else:
statetmp = matrix[stateNow]['other']
if statetmp == len(needle):
self.flag = True
if node.left:
dfs(statetmp, node.left)
if node.right:
dfs(statetmp, node.right)
dfs(0, root)
print(self.flag)
if self.flag:
return self.flag
else:
return False
# return False
|
35426f58a4dc79302363808940858100f682e3ee
|
katrin87/assignments-kate_iv
|
/assignments_4task3.py
| 1,635 | 3.96875 | 4 |
#! /usr/bin/env python
from __future__ import division, print_function
def matrix_mul(matr1, matr2):
''' Calculates the result of multiplication of two matrices
:type matr1: list
:param matr1: list of lists integer or float numbers
:type matr2: list
:param matr2: list of lists integer or float numbers
:return:
'''
nrow_matr1, ncol_matr1 = len(matr1), len(matr1[0])
nrow_matr2, ncol_matr2 = len(matr2), len(matr2[0])
if ncol_matr1 != nrow_matr2:
raise ValueError("Matrices are of incorrect length")
matrix_mult_res = [[None for j in xrange(ncol_matr2)]
for i in xrange(nrow_matr1)]
def vector_mult(row, col): # multiple row on a column
if len(row) != len(col):
raise ValueError("Vectors can not be multiplied")
res = 0
for i in xrange(len(row)):
if not (isinstance(row[i], (int, float)) and isinstance(col[i], (int, float))):
raise ValueError("Invalid data format")
res += row[i]*col[i]
return res
def get_col(matr, j):
return [row[j] for row in matr]
for i in xrange(nrow_matr1):
for j in xrange(ncol_matr2):
matrix_mult_res[i][j] = vector_mult(matr1[i], get_col(matr2, j))
return matrix_mult_res
matr1 = [[1,2,3], [1,2,3], [1,2,3]]
matr2 = [[1,2], [2,1], [0,5]]
print(matrix_mul(matr1, matr2))
# matr1 = [[1,2,3]]
# matr2 = [[1], ['a'], [3]]
# print(matrix_mul(matr1, matr2))
matr1 = [[1,2,3], [1,2,5.2], [1,2,3]]
matr2 = [[1,2], [2,1], [0,5]]
print(matrix_mul(matr1, matr2))
|
5f70cd0c30171bbb7d63ea450438ead88b6b32f3
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/python/word-count/021a1dbfab3c43a68e1d302e915031d8.py
| 486 | 3.65625 | 4 |
def get_next_word(text, pos):
while( text[pos] == ' ' or text[pos] == '\t' or text[pos] == '\r' or text[pos] == '\n' ):
pos = pos + 1
ref = pos
word = ''
while( text[pos] != '' or text[pos] != '\t' or text[pos] != '\r' or text[pos] != '\n' ):
word[pos-ref] = text[pos]
return word
def word_count(text):
wordArray = dict()
for word in text.split():
if word not in wordArray:
wordArray.update({word:1})
else:
wordArray[word] = wordArray[word] + 1
return wordArray
|
2e8e243cd4555828ae12e133f5b536c5a2026e37
|
Shavezz/Python-Tech-Degree-Project3-Phrase-Hunters
|
/phrasehunter/character.py
| 435 | 3.625 | 4 |
class Character:
def __init__(self, char1):
self.original_char = char1
was_guessed_character = False
def update(self, guess):
if guess == original_char:
was_guessed_character == True
def show_character():
if was_guessed_character == True and len(original_char) == 1 and original_char.isalpha():
print(original_char)
else:
print("_")
|
4b86797859715751a034c58d209e8ea7fb110646
|
LHTECH-COM/preview_project
|
/preview_project3/account.py
| 4,497 | 3.671875 | 4 |
import csv
import json
import datetime
CSV_FILE = "account_03.csv"
NEW_CSV_FILE = "account_03_new.csv"
ID_INDEX = 0
FIRST_NAME_INDEX = 1
LAST_NAME_INDEX = 2
DOB_INDEX = 3
class Account():
"""
A class to represent a user.
Attributes
----------
id: str
id of the person
first_name : str
first name of the person
last_name : str
last name of the person
dob : str
date of birth of the person
Methods
-------
format_dob():
format date of birth
"""
def __init__(self, info):
self.id = info["id"]
self.first_name = info["first_name"]
self.last_name = info["last_name"]
self.dob = info["dob"]
#format data of birth with m/d/Y
def format_dob(self):
try:
dob = datetime.datetime.strptime(self.dob,'%d%m%Y').date()
except Exception as ex:
print ("Invalid DOB")
dob = self.dob
return f'{dob}'
"""
A class to register accounts for users from csv file.
Attributes
----------
accounts : object
list of user
Methods
-------
read_from_csv(): void
Read all data from csv file.
get_duplicate_row(): void
Returns result as json format.
get_valid_row(): void
Returns result as json format.
write_available_users_to_csv_file(): void
Write all valid accounts to new file.
"""
class AccountRegister():
def __init__(self):
self.accounts = []
#count num of row have the same id
def count_id(self,id):
data = list(filter(lambda x: x.id == id, self.accounts))
return len(data)
#read data from csv file
def read_from_csv(self, file_name):
try:
with open(file_name, "r") as file:
reader = csv.reader(file, delimiter=",")
for index, line in enumerate(reader):
if index == 0:
continue
else:
user_info = {
"id":line[ID_INDEX],
'first_name': line[FIRST_NAME_INDEX],
'last_name': line[LAST_NAME_INDEX],
'dob': line[DOB_INDEX],
}
self.accounts.append(Account(user_info))
print('Read accounts from csv file successfully.')
except FileNotFoundError:
raise
print('Read accounts from csv file failed.')
#get row have duplicate id
def get_duplicate_row(self):
data = filter(lambda x: self.count_id(x.id) > 1, self.accounts)
return [json.dumps({
'id':account.id,
'first_name': account.first_name,
'last_name': account.last_name,
'dob': account.dob
}) for account in data]
#return list of valid data
def get_valid_row(self):
data = filter(lambda x: self.count_id(x.id) == 1, self.accounts)
return [json.dumps({
'id':account.id,
'first_name': account.first_name,
'last_name': account.last_name,
'dob': account.format_dob()
}) for account in data]
#write data to csv file
def write_available_users_to_csv_file(self):
data = filter(lambda x: self.count_id(x.id) == 1, self.accounts)
try:
with open(NEW_CSV_FILE, mode='w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(['ID', 'First Name', 'Last Name', 'DOB'])
for account in data:
writer.writerow([account.id,account.first_name, account.last_name, account.format_dob()])
print ("write to csv file successfully")
except FileNotFoundError as err:
raise
print(err)
if __name__ == "__main__":
account_register = AccountRegister()
account_register.read_from_csv(CSV_FILE)
print ("list duplicate row data:")
print (account_register.get_duplicate_row())
print ("list valid row data:")
print (account_register.get_valid_row())
print("Write processed data to new CSV file:")
account_register.write_available_users_to_csv_file()
|
4b21dea5cf4ef6416592ae126d8e2b3c6d8885f7
|
mderamus19/dictionary-of-words
|
/dictionaryOfWords.py
| 981 | 4.71875 | 5 |
# Create a dictionary with key value pairs to
# represent words (key) and its definition (value)
word_definitions = dict()
# Add several more words and their definitions
# Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python"
word_definitions = {
"assiduous" : "meticulous and diligent",
"esurient" : "hungry",
"rigging" : "lines of chains used in theater set design for support and movement",
"alacrity" : "a prompt response"
}
# Use square bracket lookup to get the definition of two
# words and output them to the console with `print()`
print(word_definitions["rigging"])
print(word_definitions["esurient"])
# Loop over the dictionary to get the following output:
# The definition of [WORD] is [DEFINITION]
# The definition of [WORD] is [DEFINITION]
# The definition of [WORD] is [DEFINITION]
for word, definition in word_definitions.items():
print(f"The definition of {word} is {definition}")
|
588f15cf0c3858a6cfa764eda6c5f8eab243d329
|
ShirleyMwombe/Training2
|
/open a file.py
| 539 | 3.671875 | 4 |
from tkinter import *
from tkinter import filedialog
def openfile():
filepath = filedialog.askopenfilename(initialdir="C:\\Users\\hp\\PycharmProjects\\Training2",
title='open file?',
filetypes=(('text files', "*.txt"), ('all files', "*.*")))
file = open(filepath)
print(file.read())
file.close()
window = Tk()
button = Button(window, text='open',
command=openfile)
button.pack()
window.mainloop()
|
10e279dece483a5450275a773103badf0a327549
|
Ashasrinivas/100programs
|
/ex_74.py
| 222 | 3.921875 | 4 |
# random.choice is used to pick a randomm elemnt in a list
import random
print(random.choice([x for x in range(11) if x %2 == 0]))
import random
print(random.choice([x for x in range(201) if x % 7 == 0 and x % 5 == 0 ]))
|
beb026e2e8c689590529e5c3ac8162261ec1494c
|
virginiah894/python_codewars
|
/5KYU/perimeter.py
| 313 | 3.515625 | 4 |
def perimeter(n: int) -> int:
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
D = {0: 0}
result = [0, 1]
for i in range(1, n + 2):
result.append(result[-1] + result[-2])
D[i] = result[i]
return sum(list(D.values())) * 4
|
04f5e7e10239b995d231cbafdddbf6e2c81551b3
|
Chamillion1/Girls-Who-Code-Projects-
|
/Atom/Dictionary.py
| 192 | 3.890625 | 4 |
names_ages = {
"Kamila": 16,
"Isabella": 12,
"Anabel": 48,
"Omar": 49,}
total=0
#print(names_ages)
for keys,values in names_ages.items():
total= values+total
print(total/len(names_ages))
|
3f6f9db6be0d6e8aa941f0625197ab1974611bf8
|
sdzr/python_for_study
|
/chapter07/practice7_7.py
| 244 | 3.65625 | 4 |
def dict_change(in_dic):
out_dic={}
for key,val in in_dic.items():
out_dic[val]=key
return out_dic
if __name__=='__main__':
in_dic={'a':1,'b':2,'c':3}
out=dict_change(in_dic)
for i in out:
print(out[i])
|
1161c398adeaaa5dc7c978dabf0fdd3545b158a6
|
MurilloFagundesAS/Exercicios-Resolvidos-Curso-em-Video
|
/Ex010-ConversaoMoeda.py
| 124 | 3.640625 | 4 |
x = float(input("Quanto Você Tem? "))
conv = x//3.27
print('Você tem R${:.2f} e pode comprar US${:.2f}'.format(x, conv))
|
15d68f8d5ba2aaa9242113f810f2f975856bf01f
|
kjowong/holbertonschool-higher_level_programming
|
/0x11-python-network_1/1-hbtn_header.py
| 370 | 3.671875 | 4 |
#!/usr/bin/python3
"""
Python script that takes in a URL, sends request and displays value
of X-Request-Id in header of the response
"""
import sys
import urllib.request
if __name__ == "__main__":
req = urllib.request.Request(sys.argv[1])
with urllib.request.urlopen(req) as response:
html = response.getheader('X-Request-Id')
print(html)
|
9cc0a19bb24b050acbb1ec24fb8b3e0c9101f9ad
|
aumaro-nyc/leetcode
|
/trees/1261.py
| 802 | 3.859375 | 4 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class FindElements:
def __init__(self, root: TreeNode):
self.val_set = set()
self.root = self.create_tree(root,0)
def find(self, target: int) -> bool:
return target in self.val_set
def create_tree(self, root, val):
if not root: return
root.val = val
self.val_set.add(val)
if root.left is not None:
root.left = self.create_tree(root.left, val*2 + 1)
else:
root.left = None
if root.right is not None:
root.right = self.create_tree(root.right, val*2 + 2)
else:
root.right = None
return root
|
ed879bf348f7ebae3b96ef8515347fe6ade84d87
|
jmuguerza/adventofcode
|
/2017/day3.py
| 6,196 | 3.984375 | 4 |
#/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PART 1
A new kind of memory is used to store info in an infinite
two dimentional grid. Each square of the grid is allocated
in an spiral pattern starting at a location marked 1, and
then counting up while spiraling outward. Data is carried
always from the square 1, using the minimum distance.
"""
INPUT = 312051
import math
import itertools
from collections import defaultdict
# Store already calculated sums to avoid recalculation
calculated_sums = defaultdict(int)
def get_side_length(position):
""" Get the side length of the square where
the position is found.
Each square goes up to L^2, where L = 2d+1,
L is the side length, and d is the distance
to the center."""
side = math.ceil(math.sqrt(position))
return side if side % 2 else side + 1
def is_corner(position):
""" True if position is in a corner of a square """
if position == 1:
return False
side = get_side_length(position)
corners = {
int(side**2),
int(side**2 - 1 * (side - 1)),
int(side**2 - 2 * (side - 1)),
int(side**2 - 3 * (side - 1)),
}
return position in corners
def is_not_corner(position):
""" True if position is not a corner of a square """
if position == 1:
return False
return not is_corner(position)
def get_distance_to_inner(position):
""" Get the distance to a position in the inner square """
# Difference between positions square and inners square depends on side
# For RIGHT side, is D=4*(L-1)+1, where L is the size of inner square
# For TOP side is D+2, LEFT D+4, BOTTOM D+6
L = get_side_length(position)
inner_L = L - 2
if position > (L**2 - (L -1)):
return 4 * (inner_L - 1) + 7
if position > (L**2 - 2 * (L -1)):
return 4 * (inner_L - 1) + 5
if position > (L**2 - 3 * (L -1)):
return 4 * (inner_L - 1) + 3
else:
return 4 * (inner_L - 1) + 1
def square_smallest(length):
""" Get the smallest number of a square """
if length == 1:
return 1
return (length - 2)**2 + 1
def get_adjacent(position):
""" Get smaller adjacent positions for a position """
if position == 1:
return []
# Previous position is always adjacent
adj = {position - 1}
# Get adjacent positions in inner square
L = get_side_length(position)
D = get_distance_to_inner(position)
if is_corner(position):
# 1. the one diagonally in
adj.add(position - D - 1)
# 2. if last corner, then the first element of square
if position == L ** 2:
adj.add(position - 4 * L + 5)
else:
# If it's the first of the square, then just add smallest of inner square
if position == square_smallest(L):
adj.add(square_smallest(L - 2))
else:
# 1. the one right next to it
if is_not_corner(position):
adj.add(position - D)
# 2. the one diagonally inner back
# (smaller + 1 has a different expression)
if is_not_corner(position - 1):
if position == square_smallest(L) + 1:
adj.add((L - 2)**2)
else:
adj.add(position - D - 1)
# 3. the one diagonally inner front
if is_not_corner(position + 1):
adj.add(position - D + 1)
# 4. if the next is the last of the square, then
# the first of the square is adjacent
if position + 1 == L ** 2:
adj.add(square_smallest(L))
# 5. If previous is in a corner, then position - 2 is adjacent
if is_corner(position - 1):
adj.add(position - 2)
yield from adj
def adjacent_sum(position):
""" Get the sum of all lesser adjacent positions """
if not calculated_sums[position]:
for adj_position in get_adjacent(position):
calculated_sums[position] += adjacent_sum(adj_position)
return calculated_sums[position]
def manhattan_distance(position):
""" Get the manhattan distance for position """
# Get the square side length
side = get_side_length(position)
# Get the shortest distance to a side center
d_to_side_center = min([
abs(position - (side**2 - 0.5 * (side - 1))),
abs(position - (side**2 - 1.5 * (side - 1))),
abs(position - (side**2 - 2.5 * (side - 1))),
abs(position - (side**2 - 3.5 * (side - 1))),
])
# The manhattan distance is equal to the shortest
# distance to the side center plus the distance
# from it, to the square center
return int(d_to_side_center + 0.5 * (side - 1))
def test(truth, distance_calculator):
for position, result in truth:
try:
assert(distance_calculator(position) == result)
except AssertionError:
print("Error trying to assert {}('{}') == {}".format(
distance_calculator.__name__, position, result))
if __name__ == "__main__":
# Store value for first position
calculated_sums[1] = 1
# Test for PART 1
GROUND_TRUTH = (
(1, 0),
(12, 3),
(23, 2),
(1024, 31),
)
test(GROUND_TRUTH, manhattan_distance)
# Test for PART 2
GROUND_TRUTH = (
(1, 1),
(2, 1),
(3, 2),
(4, 4),
(5, 5),
(6, 10),
(7, 11),
(8, 23),
(9, 25),
(10, 26),
(11, 54),
(12, 57),
(13, 59),
(14, 122),
(15, 133),
(16, 142),
(17, 147),
(18, 304),
(19, 330),
(20, 351),
(21, 362),
(22, 747),
(23, 806),
)
test(GROUND_TRUTH, adjacent_sum)
# RUN
print('PART 1 result: {}'.format(manhattan_distance(INPUT)))
for i in itertools.count(start=1):
if adjacent_sum(i) > INPUT:
print('PART 2 result: {}'.format(adjacent_sum(i)))
break
|
082cdb2a95cf5414f17423641b110d179a232cc2
|
Anjalipatil18/Hackerrank-And-Codesignle-Questions
|
/paramid_pattern.py
| 584 | 3.890625 | 4 |
size = 7
m = (2 * size) - 2
for i in range(0, size):
for j in range(0, m):
print(end=" ")
m = m - 1 # decrementing m after each loop
for j in range(0, i + 1):
# printing full Triangle pyramid using stars
print("* ", end=' ')
print(" ")
for i in range (0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")
lastNumber = 6
asciiNumber = 65
for i in range(0, lastNumber):
for j in range(0, i+1):
character = chr(asciiNumber)
print(character, end=' ')
asciiNumber+=1
print(" ")
|
e0af6efc91fc7aebe77266300339867ed55536f9
|
luokeke/selenium_python
|
/python_doc/Python基础语法/0.mooc课堂实例/6.2文本词频统计.py
| 1,117 | 3.734375 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/12 14:02
# @Author : liuhuiling
'''
文本词频统计
- 英文文本:Hamet 分析词频
https://python123.io/resources/pye/hamlet.txt
- 中文文本:《三国演义》 分析人物
https://python123.io/resources/pye/threekingdoms.txt
'''
from os.path import abspath,dirname
project_path = dirname(dirname(abspath(__file__)))
def getText():
txt = open(project_path+"\\0.素材\\hamlet.txt","r").read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~ ':
txt = txt.replace(ch, " ") #特殊字符替换成空格
return txt # 可以直接返回列表形式的
hamletTxt = getText()
words = hamletTxt.split()#默认根据空格将字符串分隔成列表
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1 #不在字典中就加入,次数加1;在次数+1
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True) #排序
for i in range(10):
word,count = items[i] #items列表内元素是元组形式,注意赋值形式
print("{0:<10}{1:>5}".format(word,count))
|
d6349571afe00c36cce2137fe4936a66a4aa4ef9
|
flysaint/RookiePython
|
/Term01/2019Day07_Term01.py
| 3,523 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 9 23:47:43 2019
@author: fly_s
Day07
1. 来排个序
对给定字符串排序。字符串中每个单词都包含一个数字。此数字是单词在在结果中应该具有位置。
注意:数字可以是1到9,因此1将是第一个单词(不是0).
example:
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
testcase:
assert order("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est", "Oops! it don't like right."
assert order("4of Fo1r pe6ople g3ood th5e the2") == "Fo1r the2 g3ood 4of th5e pe6ople", "Oops! it don't like right."
assert order("") == "","Oops! it don't like right."
"""
import re
# 菜鸟法
def order(text):
if len(text)==0:return ""
# 先将text截取成字符串组
str_list = text.split()
# 将个字符串组中的数值找出来。
num_list = [re.sub('[^\d+]','',num) for num in str_list]
# 组成 dict键值对,然后使用数值作为key,进行sort排序
sort_list = sorted(zip(num_list,str_list),key = lambda x:x[0])
# 利用字符串组和字符串数值,
new_list = [t[1] for t in sort_list]
return (' '.join(new_list))
'''
# 高手法1 这个非常巧妙,利用数字和字母组合的字符串,又一个技巧,数字总是排序在字母前面
s='1ad9'
print (sorted(s))
>>['1', '9', 'a', 'd']
为啥数字排序在字母前面,因为1和字母的ascii的码,数字的小,字母的大
print ({c:ord(c) for c in s})
>>{'1': 49, 'a': 97, 'd': 100, '9': 57}
'''
def order(words):
return ' '.join(sorted(words.split(), key=lambda w:sorted(w)))
# 高手法2 这个通俗点,把key里面原来用lambda 写的改成了 extract_number函数
def extract_number(word):
for l in word:
if l.isdigit(): return int(l)
return None
def order(sentence):
return ' '.join(sorted(sentence.split(), key=extract_number))
'''
2 点赞
你可能知道Facebook和其他网页上的“点赞”系统。人们可以“喜欢”博客文章,图片或其他项目。
我们想要创建应该在这样的项目旁边显示的文本。
实现一个函数
likes :: [String] --> String, 它必须包含输入数组,包含喜欢项目的人的名字
它必须返回显示文本,如示例所示:
likes([]) // must be "no one likes this"
likes(["Peter"]) // must be "Peter likes this"
likes(["Jacob", "Alex"]) // must be "Jacob and Alex like this"
likes(["Max", "John", "Mark"]) // must be "Max, John and Mark like this"
likes(["Alex", "Jacob", "Mark", "Max"]) // must be "Alex, Jacob and 2 others
like this"
对于4个或更多名称,数字 and 2 others 只会增加
点评
1. 利用字典来返回字符串结构,非常巧妙。返回value,返回各种字符串
2. 字典的遍历利用 min(4,n)
3. format里面 关键字定位,非常易扩展
4. *['aa'] 星号和列表连用的做法很独特
'''
# 高手法1
def likes(names):
n = len(names)
return {
0: 'no one likes this',
1: '{} likes this',
2: '{} and {} like this',
3: '{}, {} and {} like this',
4: '{}, {} and {others} others like this'
'''
这里的 *names[:3] 是将name[:3]放入一个元组里,这样前面的 3个{}都会有值
* 代表 starred expression 详见 https://blog.csdn.net/DawnRanger/article/details/78028171
# example 1
a, *b, c = range(5)
此时: a = 0,*b = [1, 2, 3],c = 4
'''
}[min(4, n)].format(*names[:3], others=n-2)
|
a19ff31ed5ebf3d304e3813fff755128dd0b386d
|
longluo/Python
|
/functional/filter.py
| 446 | 3.65625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filter
# 2015-07-22 03:12:38
def is_odd(n):
return n % 2 == 1
print filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
def not_empty(s):
return s and s.strip()
print filter(not_empty, ['A', '', 'B', None, 'C', ' '])
# Exercise
# Prime Number
def is_prime(n):
if n == 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
print filter(is_prime, range(1, 101))
|
fa7961c360263d53f1e84c3bbfa6a32543a8c484
|
ericthansen/fluffy-waddle
|
/fibo.py
| 2,138 | 4.0625 | 4 |
def factorial(n):
#print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
#print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(5))
def iterative_factorial(n):
result = 1
for i in range(2,n+1):
result *= i
return result
print(iterative_factorial(5))
from timeit import Timer
#from fibo import factorial
t1 = Timer("factorial(10)","from fibo import factorial")
for i in range(1,20):
s = "factorial(" + str(i) + ")"
t1 = Timer(s,"from fibo import factorial")
time1 = t1.timeit(3)
s = "iterative_factorial(" + str(i) + ")"
t2 = Timer(s,"from fibo import iterative_factorial")
time2 = t2.timeit(3)
print("n=%2d, factorial: %8.6f, iterative_factorial: %7.6f, percent: %10.2f" % (i, time1, time2, time1/time2))
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def fibi(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
print(fib(10), fibi(10))
from timeit import Timer
#from fibo import fib
t1 = Timer("fib(10)","from fibo import fib")
for i in range(1,30):
s = "fib(" + str(i) + ")"
t1 = Timer(s,"from fibo import fib")
time1 = t1.timeit(3)
s = "fibi(" + str(i) + ")"
t2 = Timer(s,"from fibo import fibi")
time2 = t2.timeit(3)
print("n=%2d, fib: %8.6f, fibi: %7.6f, percent: %10.2f" % (i, time1, time2, time1/time2))
'''Think of a recusive version of the function f(n) = 3 * n, i.e. the multiples of 3
Write a recursive Python function that returns the sum of the first n integers.
(Hint: The function will be similiar to the factorial function!)
Write a function which implements the Pascal's triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
You find further exercises on our Python3 version of recursive functions, e.g. creating the Fibonacci numbers out of Pascal's triangle or produce the prime numbers recursively, using the Sieve of Eratosthenes.'''
|
4a61809e7e5ed2a45d63c36a0a1463d1f7724087
|
caowei3002008/python_week4
|
/car.py
| 909 | 3.84375 | 4 |
class car(object):
def __init__(self,price,speed,fuel,mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.display_all()
def display_all(self):
print 'Price:',self.price
print 'Speed:',self.speed
print 'Fuel:',self.fuel
print 'Mileage:',self.mileage
if self.price > 10000:
tax = 0.15
elif self.price <10000 or self.price > 0:
tax = 0.12
print 'Tax:', tax
car1 = car(2000,'35mph','Full','15mpg')
# car1.display_all()
car2 = car(2000,'5mph','Not Full','105mpg')
# car2.display_all()
car3 = car(2000,'15mph','Kind of Full','95mpg')
# car3.display_all()
car4 = car(2000,'25mph','Full','25mpg')
# car4.display_all()
car5 = car(2000,'45mph','Empty','25mpg')
# car5.display_all()
car6 = car(20000000,'35mph','Empty','15mpg')
# car6.display_all()
|
c05daefa993afd70aefb3f14eec3e72d0241297b
|
andrebor/My-Personal-Projects
|
/Code Prompts/Pig Latin.py
| 555 | 3.796875 | 4 |
# Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of
# an English word the initial consonant sound is transposed to the end of the word and an ay is affixed
# (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules.
consonants = set("bcdfghjklmnpqrstvwxyz")
string = input("Give me your words: ")
words = string.split()
for i in range(len(words)):
if words[i][0] in consonants:
words[i] += "-" + words[i][0] + "ay"
words[i] = words[i][1:]
print(words)
|
45aef0af80803a9b62be00380418075759f2e202
|
Pshypher/tpocup
|
/ch07/labs/lab06.py
| 2,294 | 3.90625 | 4 |
# lab06.py
# Unless stated otherwise, each variable is assumed to be a list data type.
import string
def find_mean_score(student_scores):
"""Finds the mean score of the score from four exams. Returns
the mean scores of the student, a float data type."""
total_int = sum(student_scores[1:])
average_float = total_int/len(student_scores[1:])
return average_float
file_obj = open("scores.txt", "r") # open the file containing the score
# for each student
# Create a list of tuples to hold each students name, four scores
# and mean score
student_scores = []
for line in file_obj:
student_info = []
if line not in string.whitespace:
line = line.strip()
student_info.append(line[:20].strip())
student_info.extend(line[20:].strip().split())
student_info = [int(elem) if elem.isdigit() else elem
for elem in student_info]
avg_float = find_mean_score(student_info)
student_info.append(avg_float)
student_info_tuple = tuple(student_info)
student_scores.append(student_info_tuple)
# Display the each students name, scores and mean score. Also the
# mean score of students for a particular exam is shown
# Sort the list of tuples according to the names of each student
student_scores.sort()
print("{:20s}{:>6s}{:>6s}{:>6s}{:>6s}{:>10s}".format("Name","Exam1","Exam2",
"Exam3","Exam4","Mean"))
exam_total_scores = [0,0,0,0]
for student_record in student_scores:
name,exam1,exam2,exam3,exam4,mean = student_record
print("{:20s}{:6d}{:6d}{:6d}{:6d}{:10.2f}".format(name,exam1,exam2,exam3,
exam4,mean))
exam_total_scores[0] += exam1
exam_total_scores[1] += exam2
exam_total_scores[2] += exam3
exam_total_scores[3] += exam4
exams_avg_tuple = tuple([exam_total/len(student_scores)
for exam_total in exam_total_scores])
print("{:20s}{:6.1f}{:6.1f}{:6.1f}{:6.1f}".format("Exam Mean",
exams_avg_tuple[0],exams_avg_tuple[1],
exams_avg_tuple[2],exams_avg_tuple[3]))
|
34c1ec3a9091a586ca5af82bedbc1677d2483fab
|
mdoprog/Warehouse
|
/Python/conditionals/positive-or-negative.py
| 219 | 3.90625 | 4 |
# coding=utf8
# Entrada
num = int (input("Informe um número inteiro: "))
# Processamento
if num >= 0:
a = num
print("Valor positivo: {0}".format(a))
else:
b = num
print("Valor negativo: {0}".format(b))
|
9c0d11ab3d921d3e591d02a79fc92d2e29bdc06b
|
Raja-mishra1/snake_ladder
|
/snake_ladder/game.py
| 4,552 | 3.859375 | 4 |
import time
import random
import sys
from conf.config import SLEEP_BETWEEN_ACTIONS,DICE_FACE,MAX_VAL,player_turn_text,snake_bite,ladder_jump,ladders
class Snake:
def add_snake(self,start,dest):
"""[Add snake to game]
Args:
start ([str]): [starting point of snake]
dest ([str]): [ending point of snake]
Raises:
ValueError: [description]
Returns:
snakes [dict]: [dictionary of snake]
"""
snakes = dict()
if start>dest:
snakes[start] = dest
else:
raise ValueError('Snake destination greater than start point')
return snakes
def __repr__(self):
return self.snakes
class Dice:
def get_dice_value():
"""[Returns dice value]
Returns:
[str]: [Returns normal dice value after dice is thrown]
"""
time.sleep(SLEEP_BETWEEN_ACTIONS)
dice_value = random.randint(1, DICE_FACE)
print("Its a " + str(dice_value))
return dice_value
def get_crooked_dice_value():
"""[Crokked dice returns a value after dice is thrown]
Returns:
[type]: [description]
"""
time.sleep(SLEEP_BETWEEN_ACTIONS)
dice_value = random.randrange(2, DICE_FACE+1,2)
print("Its a " + str(dice_value))
return dice_value
def get_player_names():
player1_name = None
while not player1_name:
player1_name = input("Please enter a valid name for first player: ").strip()
print("\nMatch will be played by'" + player1_name+"'\n")
return player1_name
def got_snake_bite(old_value, current_value, player_name):
print("\n" + random.choice(snake_bite).upper() + " ~~~~~~~~>")
print("\n" + player_name + " got a snake bite. Down from " + str(old_value) + " to " + str(current_value))
def got_ladder_jump(old_value, current_value, player_name):
print("\n" + random.choice(ladder_jump).upper() + " ########")
print("\n" + player_name + " climbed the ladder from " + str(old_value) + " to " + str(current_value))
def snake_ladder(player_name, current_value, dice_value,snakes):
time.sleep(SLEEP_BETWEEN_ACTIONS)
old_value = current_value
current_value = current_value + dice_value
if current_value > MAX_VAL:
print("You need " + str(MAX_VAL - old_value) + " to win this game. Keep trying.")
return old_value
print("\n" + player_name + " moved from " + str(old_value) + " to " + str(current_value))
if current_value in snakes:
final_value = snakes.get(current_value)
got_snake_bite(current_value, final_value, player_name)
elif current_value in ladders:
final_value = ladders.get(current_value)
got_ladder_jump(current_value, final_value, player_name)
else:
final_value = current_value
return final_value
def check_win(player_name, position):
time.sleep(SLEEP_BETWEEN_ACTIONS)
if MAX_VAL == position:
print("\n\n\nThats it.\n\n" + player_name + " won the game.")
print("Congratulations " + player_name)
sys.exit(1)
def start():
time.sleep(SLEEP_BETWEEN_ACTIONS)
player1_name = get_player_names()
time.sleep(SLEEP_BETWEEN_ACTIONS)
player1_current_position = 0
print("Add snakes to the game")
no_of_snakes = int(input("Enter no_of_snakes to be added to the game"))
for i in range(no_of_snakes):
try:
start = input("Enter start position of snake: ")
end = input("Enter end position of snake: ")
snake = Snake()
snakes = snake.add_snake(start, end)
print(f"Added snake from {start} to {end}")
except Exception as e:
print(f"Error {e}")
dice_type = input("Enter 1 for Crooked dice: ")
for i in range(10):
time.sleep(SLEEP_BETWEEN_ACTIONS)
dice = Dice()
input_1 = input("\n" + player1_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
print("\nRolling dice...")
if dice_type == "1":
dice_value = Dice.get_crooked_dice_value()
else:
dice_value = Dice.get_dice_value()
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(player1_name + " moving....")
player1_current_position = snake_ladder(player1_name, player1_current_position, dice_value,snakes)
check_win(player1_name, player1_current_position)
if __name__ == "__main__":
start()
|
9e2eb0daa07f4d1839946feefc0f2ed6d7f8446a
|
ICCV/coding
|
/dfs/q1227.py
| 1,800 | 3.5 | 4 |
"""
当 n>2n>2 时,如何计算 f(n)f(n) 的值?考虑第 11 位乘客选择的座位,有以下三种情况。
第 11 位乘客有 \frac{1}{n}
n
1
的概率选择第 11 个座位,则所有乘客都可以坐在自己的座位上,此时第 nn 位乘客坐在自己的座位上的概率是 1.01.0。
第 11 位乘客有 \frac{1}{n}
n
1
的概率选择第 nn 个座位,则第 22 位乘客到第 n-1n−1 位乘客都可以坐在自己的座位上,第 nn 位乘客只能坐在第 11 个座位上,此时第 nn 位乘客坐在自己的座位上的概率是 0.00.0。
第 11 位乘客有 \frac{n-2}{n}
n
n−2
的概率选择其余的座位,每个座位被选中的概率是 \frac{1}{n}
n
1
。
假设第 11 位乘客选择第 ii 个座位,其中 2 \le i \le n-12≤i≤n−1,则第 22 位乘客到第 i-1i−1 位乘客都可以坐在自己的座位上,第 ii 位乘客到第 nn 位乘客的座位不确定,第 ii 位乘客会在剩下的 n-(i-1)=n-i+1n−(i−1)=n−i+1 个座位中随机选择(包括第 11 个座位和第 i+1i+1 个座位到第 nn 个座位)。由于此时剩下的乘客数和座位数都是 n-i+1n−i+1,有 11 位乘客会随机选择座位,因此问题规模从 nn 减小至 n-i+1n−i+1。
"""
class Solution(object):
def nthPersonGetsNthSeat(self, n):
"""
:type n: int
:rtype: float
"""
if n == 1:
return 1
dp = [0] * (n+1)
dp[1] = 1
dp[2] = 0.5
status = [0] * (n+1)
status[2] = 0.5
for i in range(3,n+1):
r = 1.0*status[i-1]/(i-1)
dp[i] = r
status[i] = status[i-1]*(1-r)
return dp[n]
if __name__ == '__main__':
s = Solution()
print(s.nthPersonGetsNthSeat(3))
|
ce0a5e261bc2711bd6745d47c494cd2585f6be47
|
SergicHill/Big_Data_Analytics
|
/Kafka/hw8p2_prod.py
| 1,180 | 3.859375 | 4 |
# Illustrates the work of kafka's producer and consumer
# @author Serguey Khovansky
# @version: March 2016
# The problem:
# Construct a producer and a consumer object. Let producer generate one random number
# between 0 and 10 every second.Let both producer and consumer run until you kill
# them. Demonstrate that your consumer is receiving messages by printing both the stream
# of numbers generated on the producer and the stream of numbers fetched by the consumer.
# To run: python hw8p2.py
from kafka import KafkaProducer
import random
import time
#Producer for Kafka, the consumer is another program
class Producer():
def run(self):
#Connect to port 9092
producer = KafkaProducer(bootstrap_servers='localhost:9092')
print('inside Producer')
#Generate an int random number in [0,10] and send it to topic 'spark_topic'
while True:
myrnd=str(random.randint(0,10))
print('Producer generates: ' + myrnd)
producer.send('spark_topic',myrnd)
time.sleep(1)
print('start producer')
oproducer = Producer()
#Start producer, which run indefinitely
oproducer.run()
print('end')
|
b650b156bdb6bea383dbaee28cb3d7e2359ac7b0
|
lucasljoliveira/OlistCurso
|
/18.12.2020/CRUD_Console.py
| 14,094 | 3.609375 | 4 |
class Category:
__id : int
__name : str
def __init__(self, id: int, name: str):
self.__id = id
self.__name = name
def set_id(self, id : int) -> None:
self.__id = int(id)
def set_nome(self, nome : str) -> None:
try:
if nome != '':
self.__nome = str(nome)
else:
raise Exception
except:
print('O nome da categoria não pode ser nulo.')
def set_id_mae(self, id : int) -> None:
self.__id_mae = int(id)
def get_id(self) -> int:
return self.__id
def get_nome(self) -> str:
return self.__nome
def get_id_mae(self) -> int:
return self.__id_mae
def __str__(self):
return f"""
Id: {self.get_id()}
Name: {self.get_name()}
"""
class SubCategory:
def __init__(self, id: int, name: str, parent: Category):
self.__parent = oaning
super().__init__(id, name)
def __str__(self):
return f"""
Id: {self.get_id()}
Name: {self.get_nome()}
Mother: {self.get_parent_name()}
"""
class Produto:
__id : int
__nome : str
__descricao : str
__preco : float
__peso : float
__dimensoes : list
__categorias : list
def set_id(self, id : int) -> None:
self.__id = int(id)
def set_nome(self, nome : str) -> None:
try:
if nome != '':
self.__nome = str(nome)
else:
raise Exception
except:
print('O nome deve ser alfanumérico e não nulo.')
def set_descricao(self, descricao : str) -> None:
try:
if len(descricao) >= 20:
self.__descricao = str(descricao)
else:
raise Exception
except:
print('A descrição deve conter no minímo 20 caracteres alfanuméricos.')
def set_preco(self, preco : float) -> None:
try:
if int(preco) > 0:
self.__preco = float(preco)
else:
raise Exception
except:
print('O preço deve ser numérico e maior que zero.')
def set_peso(self, peso : float) -> None:
try:
if float(peso) > 0:
self.__peso = float(peso)
else:
raise Exception
except:
print('O peso deve ser numérico e maior do que zero.')
def set_dimensoes(self, dimensoes : list) -> None:
try:
dimensoes[0] = float(dimensoes[0])
dimensoes[1] = float(dimensoes[1])
dimensoes[2] = float(dimensoes[2])
if dimensoes[0] >= 0 and dimensoes[1] >= 0 and dimensoes[2] >= 0:
self.__dimensoes = dimensoes
else:
raise Exception
except:
print('As dimensões devem conter valores numéricos acima de zero.')
def set_categorias(self, cat: list):
try:
if len(cat) > 0:
self.__categorias = cat
else:
raise Exception
except:
print('O produto deve pertencer a pelo menos uma categoria.')
def get_id_(self) -> int:
return self.__id
def get_nome(self) -> str:
return self.__nome
def get_descricao(self) -> str:
return self.__descricao
def get_preco(self) -> float:
return self.__preco
def get_peso(self) -> float:
return self.__peso
def get_dimensoes(self) -> list:
return self.__dimensoes
def get_categorias(self) -> list:
return self.__categorias
t_produtos = 0
t_categorias = 6
produtos = []
categorias = []
def criar_categoria2(id, nome, idmae):
c = Categoria()
c.set_id(id)
c.set_nome(nome)
c.set_id_mae(idmae)
categorias.append(c)
criar_categoria2(1, 'informatica', 0)
criar_categoria2(2, 'computadores', 1)
criar_categoria2(3, 'notebook', 1)
criar_categoria2(4, 'beleza', 0)
criar_categoria2(5, 'sabonete', 4)
criar_categoria2(6, 'shampoo', 4)
def criar_categoria():
c = Categoria()
c.set_id(t_categorias + 1)
c_mae = 0
nome = input(' Nome da Categoria: ')
option = input('É uma subcategoria? Digite 1 para Sim: ')
if option == 1:
for c1 in categorias:
if c1.get_id_mae() == 0:
print('ID: ' + str(c1.get_id()) + ', Nome: ' + c1.get_nome())
c_mae = input(' Insira o ID da principal: ')
c.set_nome(nome)
c.set_id_mae(c_mae)
return c
while(True):
print('**** CADASTRO DE PRODUTOS ****\n1. Listar Categorias\n2. Listar Produtos\n3. Cadastrar Categorias\n4. Cadastrar Produtos\n5. Alterar Produto\n6. Deletar Produto\n0. Sair')
option = int(input(' Insira uma opção: '))
if option == 1:
if len(categorias) == 0:
print(' Nenhuma categoria cadastrada. ')
else:
print('Categorias:')
for c in categorias:
if c.get_id_mae() == 0:
print(' * ID: ' + str(c.get_id()) + ', Nome: ' + c.get_nome())
for c1 in categorias:
if c.get_id() == c1.get_id_mae():
print(' - ID: ' + str(c1.get_id()) + ', Nome: ' + c1.get_nome() + ', ID Categoria Principal: ' + str(c1.get_id_mae()))
achou = True
if option == 2:
if len(produtos) == 0:
print(' Nenhum produto cadastrado. ')
else:
achou = False
option = int(input('1. Todos\n2. Por Nome\n3. Por Descrição\n4. Por Preço\n Insira uma opção: '))
if option == 1:
for p in produtos:
cat = ''
for c in p.get_categorias():
for c1 in categorias:
if c1.get_id() == c:
cat = cat + c1.get_nome() + ', '
print('Nome: ' + p.get_nome() + ', Descrição: ' + p.get_descricao() + ', Preço: R$ ' + str(p.get_preco()) + ', Dimensões: ' + str(p.get_dimensoes()[0]) + ' x ' + str(p.get_dimensoes()[1]) + ' x ' + str(p.get_dimensoes()[2]) + ', Categorias: ' + cat)
achou = True
elif option == 2:
option = str(input('Insira o nome: '))
for p in produtos:
if p.get_nome() == option:
cat = ''
for c in p.get_categorias():
for c1 in categorias:
if c1.get_id() == c:
cat = cat + c1.get_nome() + ', '
print('Nome: ' + p.get_nome() + ', Descrição: ' + p.get_descricao() + ', Preço: R$ ' + str(p.get_preco()) + ', Dimensões: ' + str(p.get_dimensoes()[0]) + ' x ' + str(p.get_dimensoes()[1]) + ' x ' + str(p.get_dimensoes()[2]) + ', Categorias: ' + cat)
achou = True
elif option == 3:
option = str(input('Insira a descrição: '))
for p in produtos:
if p.get_descricao() == option:
cat = ''
for c in p.get_categorias():
for c1 in categorias:
if c1.get_id() == c:
cat = cat + c1.get_nome() + ', '
print('Nome: ' + p.get_nome() + ', Descrição: ' + p.get_descricao() + ', Preço: R$ ' + str(p.get_preco()) + ', Dimensões: ' + str(p.get_dimensoes()[0]) + ' x ' + str(p.get_dimensoes()[1]) + ' x ' + str(p.get_dimensoes()[2]) + ', Categorias: ' + cat)
achou = True
elif option == 4:
option = int(input('Insira o preço: '))
for p in produtos:
if p.get_preco() == option:
cat = ''
for c in p.get_categorias():
for c1 in categorias:
if c1.get_id() == c:
cat = cat + c1.get_nome() + ', '
print('Nome: ' + p.get_nome() + ', Descrição: ' + p.get_descricao() + ', Preço: R$ ' + str(p.get_preco()) + ', Dimensões: ' + str(p.get_dimensoes()[0]) + ' x ' + str(p.get_dimensoes()[1]) + ' x ' + str(p.get_dimensoes()[2]) + ', Categorias: ' + cat)
achou = True
if achou == False:
print(' Nenhum registro encontrado.')
elif option == 3:
try:
c = criar_categoria()
categorias.append(c)
t_categorias = t_categorias + 1
except Exception as e:
print(' Informações da categoria inválidas. %s' % (str(e)))
elif option == 4:
p = Produto()
p.set_id = t_produtos + 1
nome = input(' Nome do Produto: ')
descricao = input(' Descrição do Produto: ')
preco = input(' Preço do produto: ')
altura = input(' Altura do produto: ')
largura = input(' Largura do produto: ')
comprimento = input(' Comprimento do produto: ')
dimensoes = [altura, largura, comprimento]
p_categorias = []
while(True):
existe = False
for c in categorias:
if c.get_id_mae() == 0:
print('ID: ' + str(c.get_id()) + ', Nome: ' + c.get_nome())
try:
c_id = int(input('Insira o ID da categoria: '))
for c in categorias:
if c.get_id_mae() == 0:
if c.get_id() == c_id:
existe = True
if existe == True:
p_categorias.append(c_id)
option = input('Deseja inserir outra categoria? Digite 1 para Sim: ')
if option != '1':
break
else:
raise Exception
except:
print('ID da categoria inválido.')
option = input('Deseja inserir uma subcategoria? Digite 1 para Sim: ')
if option == '1':
for c1 in p_categorias:
print('Categoria ID ' + str(c1) + ': ')
while(True):
existe = False
t_subcategoria = 0
for c in categorias:
if c.get_id_mae() != 0:
if int(c.get_id_mae()) == c1:
print('ID: ' + str(c.get_id()) + ', Nome: ' + c.get_nome())
t_subcategoria += 1
if t_subcategoria > 0:
try:
c_id = int(input('Insira o ID da subcategoria: '))
for c in categorias:
if c.get_id_mae() == c1:
if c.get_id() == c_id:
existe = True
if existe == True:
p_categorias.append(c_id)
option = input('Deseja inserir outra subcategoria da categoria ' + str(c1) + '? Digite 1 para Sim: ')
if option != '1':
break
else:
raise Exception
except:
print('ID da subcategoria inválido.')
else:
print('A categoria ' + str(c1) + ' não possui subcategoria a serem inseridas.')
break
p.set_nome(nome)
p.set_descricao(descricao)
p.set_preco(preco)
p.set_dimensoes(dimensoes)
p.set_categorias(p_categorias)
produtos.append(p)
t_produtos = t_produtos + 1
print('Produto cadastrado com sucesso.')
elif option == 5:
if len(produtos) == 0:
print(' Nenhum produto cadastrado.')
else:
achou = False
option = int(input('Pesquisar por: \n1. Nome\n2. Descrição\n3. Preço\nInsira uma opção: '))
print('** Produtos **')
for p in produtos:
print('Nome: ' + p.get_nome() + ', Descrição: ' + p.get_descricao() + ', Preço: R$ ' + str(p.get_preco()))
if option == 1:
option = str(input('Insira o nome atual: '))
for p in produtos:
if p.get_nome() == option:
p.set_nome(input('Insira o novo nome: '))
achou = True
elif option == 2:
option = str(input('Insira a descrição atual: '))
for p in produtos:
if p.get_descricao() == option:
p.set_descricao(input('Insira a nova descrição: '))
achou = True
elif option == 3:
option = int(input('Insira o preço atual: '))
for p in produtos:
if p.get_preco() == option:
p.set_preco(input('Insira o novo preço: '))
achou = True
if achou == False:
print(' Nenhum registro encontrado.')
elif option == 6:
if produtos.count() == 0:
print(' Nenhum produto cadastrado.')
else:
for p in produtos:
print('Nome: ' + p.get_nome() + ', Descrição: ' + p.get_descricao() + ', Preço: R$ ' + str(p.get_preco()))
option = input('Insira o nome do produto: ')
for p in produtos:
if p.get_nome() == option:
produtos.remove(p)
elif option == 0:
print('Apagando galeria de produtos e categorias!')
print('Saindo!!')
break
|
67bcd67d943a6d5a181e1951b51e22265588bf39
|
UnstoppableGuy/MNA-4-SEM
|
/lab2/main1.py
| 2,107 | 3.6875 | 4 |
import math
import numpy as np
def finding_a_matrix_by_formula():
k = 0
while k < 1:
k = int(input("Enter the variant:"))
size = 0
while size < 2:
size = int(input("Enter the size of matrix:"))
c = [[float(input("Enter the [{0}][{1}] element for matrix c:".format(i, j)))
for i in range(size)] for j in range(size)]
d = [[float(input("Enter the [{0}][{1}] element for matrix D:".format(i, j)))
for i in range(size)] for j in range(size)]
a = np.array(c) * k + np.array(d)
b = [float(
input("Enter the [{0}]element for matrix B:".format(i))) for i in range(size)]
return a, b
def simple_iteration_method(a, b):
for i in range(len(a)):
q = a[i][i]
a[i] /= q
b[i] /= q
a = np.eye(len(a)) - a
if np.linalg.norm(a, np.inf) >= 1 and np.linalg.norm(a, 1) >= 1 and np.linalg.norm(a) >= 1:
print("The system is not solved by this method")
exit(1)
copy_b = np.copy(b)
x = np.matmul(a, copy_b) + b
num_of_iteration = math.ceil(math.log((1e-4 * (1 - np.linalg.norm(a, np.inf))) / np.linalg.norm(x - copy_b, np.inf), np.linalg.norm(a, np.inf)))
for i in range(num_of_iteration):
copy_b = x
x = np.matmul(a, copy_b) + b
for i in range(len(a)):
print("X{0} = {1}".format(i + 1, x[i].__format__(".4f")))
def main():
C = np.array([[0.01, 0, -0.02, 0, 0],
[0.01, 0.01, -0.02, 0, 0],
[0, 0.01, 0.01, 0, -0.02],
[0, 0, 0.01, 0.01, 0],
[0, 0, 0, 0.01, 0.01]])
D = np.array([[1.33, 0.21, 0.17, 0.12, -0.13],
[-0.13, -1.33, 0.11, 0.17, 0.12],
[0.12, -0.13, -1.33, 0.11, 0.17],
[0.17, 0.12, -0.13, -1.33, 0.11],
[0.11, 0.67, 0.12, -0.13, -1.33]])
b = np.array([1.2, 2.2, 4.0, 0.0, -1.2])
a = np.array(C) * int(input("Enter the variant:")) + np.array(D)
simple_iteration_method(a, b)
#simple_iteration_method(finding_a_matrix_by_formula())
if __name__ == '__main__':
main()
|
427e427dcb43914eadaa187cada04cde5246f90f
|
nazna/archives
|
/Practice/python/LeapYear.py
| 264 | 3.828125 | 4 |
# coding: utf-8
print("閏年かどうかを判定します:", end="")
year = int(input())
if (year%4 == 0 and year%100 != 0) or year%400 == 0:
print("{}年は閏年です".format(year))
else:
print("{}年は閏年ではありません".format(year))
|
21dd9e1882a3cae4a42f622a93468fd1928b6654
|
tchaiyasena/TDD_work
|
/compute_stats_refactor.py
| 1,330 | 4.21875 | 4 |
# -*- coding: utf-8 -*-
"""
This program computes basic statistics
"""
fpath = r'random_nums.txt'
def read_ints(filePath):
h = open(fpath,'r')
dats = h.read().split('\n')
return [int(x) for x in dats]
def count(lst:list) -> int:
return len(lst)
def summation(nums:list) -> int:
return sum(nums)
def average(nums:list) -> float:
return summation(nums) / count(nums)
def minimum(nums:list) -> int:
return min(nums)
def maximum(nums:list) -> int:
return max(nums)
def harmonic_mean(nums:list) -> float:
recips = [1/n for n in nums]
return count(nums) / summation(recips)
def variance(nums:list) -> float:
avg = average(nums)
sqrDiffs = [(float(n)-avg)**2 for n in nums]
return average(sqrDiffs)
def standard_dev(nums:list) -> float:
var = variance(nums)
return var**0.5
if __name__ == '__main__':
nums = read_ints(fpath)
print(type(nums))
print('count: %6d' % count(nums))
print('summation: %6d' % summation(nums))
print('average: %5.3f' % average(nums))
print('minimum: %6d' % minimum(nums))
print('maximum: %6d' % maximum(nums))
print('harmonic_mean: %5.3f' % harmonic_mean(nums))
print('variance %5.3f' % variance(nums))
print('standard_dev %5.3f' % standard_dev(nums))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.