blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
988cf9746585dc6e2954bf1b56334c8f7567b3e5 | cs9902/RentCaculator | /carrent.py | 225 | 3.578125 | 4 | total = 327800
rate = 0.50757/100
count = 36
print('total:', total)
print('rate:', rate)
print('count:', count)
money = total * rate * (1 + rate)**count / ((1 + rate)**count - 1)
print money
print money * count - total
|
2580ad9e803634e7a8fcf904af830cc1a9642801 | dmoonfire/mfgames-media-python | /src/mfgames-mplayer-mythtv | 7,563 | 3.53125 | 4 | #!/usr/bin/python
import Tkinter
import datetime
import dateutil.relativedelta
import logging
import mfgames_media.mplayer
import os
import sys
import time
class RenderState(object):
"""Encapsulates the functionality for rendering text to the display."""
def __init__(self):
self.canvas_texts = []
self.texts = []
def add_line(self, text):
"""Adds a text line to the canvas in a manner like World of Goo."""
# Delete all the lines currently on screen since I couldn't
# figure out how to change text in a canvas "in place".
for index in self.canvas_texts:
self.canvas.delete(index)
self.canvas_texts = []
# If we have more than 10 items in the text, then pop off the
# next one.
if len(self.texts) >= 10:
self.texts.pop()
# Add the text to the list of text fields.
self.texts.insert(0, text)
# Display the text on the canvas.
x = 20
y = self.screen_height - 10
color = 255
delta_y = -55
delta_color = -25
for text in self.texts:
# Create a line element inside the canvas.
self.canvas_texts.append(
self.canvas.create_text(
x,
y,
text=text,
fill="#{0:02X}{0:02X}{0:02X}".format(color),
anchor=Tkinter.SW,
font=(self.splash_font_name, self.splash_font_size)))
# Adjust the various colors and deltas
y = y + delta_y
color = color + delta_color
def create_text():
for i in range(10):
# Shift the Y offset up so we don't have overlapping lines.
y = y + dy
color = color + dcolor
def format_time(d):
"""Formats the date time and returns the textual response.
http://stackoverflow.com/questions/1551382/python-user-friendly-time-format
"""
# Create some helper lambdas to make the English prettier.
plural = lambda x: 's' if x > 1 else ''
singular = lambda x: x[:-1]
display_unit = lambda unit, name: '%s %s%s'%(unit, name, plural(unit)) if unit > 0 else ''
# Get the time units we are interested in, those in the default
# case, only # days and less are important. But it is possible the
# user set the configuration to never expire.
tm_units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
now = datetime.datetime.utcnow()
rdelta = dateutil.relativedelta.relativedelta(now, d)
for idx, tm_unit in enumerate(tm_units):
first_unit_val = getattr(rdelta, tm_unit)
if first_unit_val > 0:
primary_unit = display_unit(first_unit_val, singular(tm_unit))
# Grab the second unit to display.
if idx < len(tm_units)-1:
next_unit = tm_units[idx + 1]
second_unit_val = getattr(rdelta, next_unit)
if second_unit_val > 0:
secondary_unit = display_unit(
second_unit_val, singular(next_unit))
return primary_unit + ', ' + secondary_unit
return primary_unit
return None
def play_video(filename, state):
state.root.lower()
mfgames_media.mplayer.do_mplayer_tool(["play", filename])
state.db.close()
state.root.destroy()
def show_filename(filename, state):
"""Displays the filename on the screen, removing any directory roots
and splitting the remaining directory components into new lines."""
# Remove the directory roots.
for root in state.directory_roots:
filename = filename.replace(root, '')
# Remove the possible directory root and strip off the extension.
filename = filename.lstrip('/')
filename = os.path.splitext(filename)[0]
# Split out the directories and make each one its own line.
prefix = ''
for part in filename.split('/'):
state.add_line(prefix + part)
prefix = prefix + ' '
state.add_line('')
def start_video(filename, state):
"""Starts the video in the given arguments or displays an error
message and times out."""
# Show the file we are trying to open.
filename = os.path.abspath(filename)
show_filename(filename, state)
# Look to see if we have a record for this file.
lookup = filename.replace("'", '')
cursor = state.db.cursor()
cursor.execute('SELECT position, duration, timestamp'
+ ' FROM bookmark'
+ " WHERE path='" + lookup + "'")
dbrow = cursor.fetchone()
cursor.close()
if dbrow:
last_played = datetime.datetime.strptime(
dbrow[2],
'%Y-%m-%d %H:%M:%S')
last_played_formatted = format_time(last_played)
state.add_line('Last played ' + last_played_formatted + ' ago')
# Keep track if we have an error. If we do, we wait a period of time
# then exit out.
has_error = True
# Check to see if the file exists first.
if os.path.exists(filename):
# Play the video using the mplayer tool.
state.root.after(
state.splash_play_pause,
lambda: play_video(filename, state))
has_error = False
# If we still have an error, then we couldn't find the video file
# to play. Pause for a short period of time, then close the
# window.
if has_error:
state.add_line("Cannot find the video file to play!")
state.db.close()
state.root.after(
state.splash_error_pause,
lambda: state.root.destroy())
def do_mplayer_mythtv_tool(arguments):
# Create a Tk window and scale it up to the full size of the window.
root = Tkinter.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("{0}x{1}+0+0".format(screen_width, screen_height))
# Logging
logging.basicConfig(
format=mfgames_media.mplayer.LOG_FORMAT,
level=logging.DEBUG)
# Database
db = mfgames_media.mplayer.database_connect()
# Keep track of the state variable so we can pass it over to the
# render method.
state = RenderState()
state.db = db
state.directory_roots = mfgames_media.mplayer.get_setting(
db,
"directory_roots").split(":")
state.splash_error_pause = mfgames_media.mplayer.get_setting(
db,
"splash_error_pause")
state.splash_play_pause = mfgames_media.mplayer.get_setting(
db,
"splash_play_pause")
state.splash_font_name = mfgames_media.mplayer.get_setting(
db,
"splash_font_name")
state.splash_font_size = mfgames_media.mplayer.get_setting(
db,
"splash_font_size")
state.root = root
state.screen_height = screen_height
# Create a canvas for displaying data. We use a highlight
# thickness of 0 so there is no visible border on the screen.
canvas = Tkinter.Canvas(
highlightthickness=0,
background='black')
canvas.pack(expand=Tkinter.YES, fill=Tkinter.BOTH)
state.canvas = canvas
# Show the main window
root.after(0, lambda: start_video(arguments[0], state))
root.mainloop()
if __name__ == "__main__":
# MythTV will pass the filename, with spaces, as separate
# arguments to this and we need to convert it into spaces. This
# does assume that the is not double spaces in filanames.
do_mplayer_mythtv_tool([" ".join(sys.argv[1:])])
|
7e1c56ab3ce044a6ba50adafb44aeb97b1c493ae | mmweber2/adm | /hash/dic2.py | 1,529 | 3.75 | 4 | # Dictionary: set of n records, each with one or more key fields
# Build and maintain a data structure to efficiently locate, insert,
# and delete the record associated with any query key q.
# We could make objects for this, but it is probably less memory to
# just put the key/record pair in a list. If we weren't going to be
# changing the record, we could use a tuple instead.
# Unsorted list implementation
class Dic(object):
items = None
def __init__(self):
self.items = []
# Internal function to find key in dictionary.
def _locate(self, q):
for i in xrange(len(self.items)):
if self.items[i][0] == q:
return i
# Locate key q in the dictionary and return its value.
# Raises a KeyError if q is not in the dictionary.
def locate(self, q):
loc = self._locate(q)
if loc == None:
raise KeyError("Key {} not found in dictionary.".format(q))
return self.items[loc][1]
# Insert key q with value value.
# If q is already in the dictionary, its value is overwritten.
def insert(self, q, value):
loc = self._locate(q)
# q is already in the dictionary; overwrite it.
if loc is not None:
self.items[loc][1] = value
# q is not in the dictionary
else:
self.items.append([q, value])
# Delete does not return the value associated with the key.
def delete(self, q):
loc = self._locate(q)
if loc is None:
raise KeyError("Key {} not found in dictionary".format(q))
self.items = self.items[:loc] + self.items[loc+1:]
|
cceb24d6002701d663aa3796b3081b146b8479cc | ketanpandey01/DS_Algo | /Graph/TopologicalSort.py | 956 | 3.8125 | 4 | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v):
self.graph[u].append(v)
def topologicalSort(self):
isVisited = [False] * self.V
tempStack = []
for node in range(self.V):
if(isVisited[node] == False):
self.topologicalSortRecurse(node, isVisited, tempStack)
print(*tempStack[::-1])
def topologicalSortRecurse(self, node, visited, tempStack):
visited[node] = True
for n in self.graph[node]:
if(visited[n] == False):
self.topologicalSortRecurse(n, visited, tempStack)
tempStack.append(node)
g= Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
print("Topological Sort: ", end=" ")
g.topologicalSort()
|
7b1eefb1d4b7cf3ee01ad95d2a8850a540c6b85a | kylelee89/kyle_ycc | /hw_200824_3.py | 706 | 3.875 | 4 | # https://www.hackerrank.com/challenges/python-mod-divmod/problem, mod divmod
# enter your code here. read input from stdin. print output to stdout
a = int(input())
b = int(input())
print(a // b)
print(a % b)
print((a // b, a % b)
# https://www.hackerrank.com/challenges/python-power-mod-power/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
a = int(input())
b = int(input())
m = int(input())
print(a ** b)
print(pow(a, b, m))
#https://www.hackerrank.com/challenges/python-integers-come-in-all-sizes/problem
# Enter your code here. Read input from STDIN. Print output to STDOU
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print(a ** b + c ** d)
|
12e3df06c83c9f36a30e66dc5f39d314db130f62 | Napier-JP/AtCoder | /abc101_d.py | 183 | 3.546875 | 4 | K = int(input())
for i in range(1,K+1): #1からKまで
ansStr = ""
ansStr += "9"*(i//9)
if i%9 == 0:
print(ansStr)
else:
print(str(i%9)+ansStr)
|
ff7b0275a4cd0ba7ac968e574f8204a89ac957f7 | GeeksIncorporated/playground | /wires_and_pins.py | 609 | 3.53125 | 4 | from collections import defaultdict
LEFT = 0
RIGHT = 1
wires = {
"A": ["B", "D"],
"B": ["A", "C"],
"C": ["B", "D"],
"D": ["A", "C"]
}
pins = defaultdict(lambda: {"side": None})
pins_pool = wires.keys()
def split_wires():
if len(pins_pool) == 0:
print (pins)
return
pin = pins_pool.pop()
for side in (LEFT, RIGHT):
if is_safe(pin, side):
pins[pin]["side"] = side
split_wires()
def is_safe(pin, side):
for child in wires[pin]:
if pins[child]["side"] == side:
return False
return True
split_wires() |
1b857dc2199ba3cce6c6bf97ff785124ef51a2a7 | EashanKaushik/LeetCode | /30-Day-Challange/Day-17/next_pointer-2.1.py | 1,088 | 3.828125 | 4 | from collections import deque
class TreeNode:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
queue = deque()
queue.append(root)
while len(queue) != 0:
size = len(queue)
while size > 0:
curr_node = queue.popleft()
if size - 1 != 0:
curr_node.next = queue[0]
else:
curr_node.next = None
if curr_node.left:
queue.append(curr_node.left)
if curr_node.right:
queue.append(curr_node.right)
size -= 1
return root
s = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.right = TreeNode(4)
root.right.right = TreeNode(4)
print(s.connect(root))
|
3393805de6c614217ff8555c69d501ef0558d034 | drknsblct/find_grade_py | /main.py | 1,517 | 3.671875 | 4 | from find_grade_functions import *
from sql_functions import *
while True:
try:
answer = int(input('\n' +
'[1] Add Courses\t\t\t' +
'[4] Find Student Grade\n' +
'[2] View List (Databases)\t' +
'[5] Delete Entries\n' +
'[3] Reset List (Database)\t' +
'[6] Find Classroom Average\n' +
'[0] Exit\n\n' +
'Enter answer: '))
except Exception:
continue
if answer == 0:
print('Exiting program!\n')
break
elif answer == 1:
print('\n<<< Add Courses >>>')
create_table('courses')
courses()
# conn.close()
elif answer == 2:
try:
get_from_table('students')
except sqlite3.OperationalError:
print("Students table doesn't exist yet!")
try:
get_from_table('courses')
except sqlite3.OperationalError:
print("Courses table doesn't exist yet!")
print()
elif answer == 3:
pass
elif answer == 4:
print("\n<<< Find Average Score >>>")
find_student_average()
elif answer == 5:
pass
elif answer == 6:
print("\n<<< Find Class Average Score >>>")
create_table('students')
find_class_average()
# conn.close()
else:
print('Input must be between 0 - 6!\n')
|
da844a32a08ea3c384be3dcf02c772cafc298d5d | adi0229/Python-AI | /pythonbasic/week1.py | 2,112 | 4.25 | 4 | print('hello world')
print('hello world 2')
print('Hello world'+'Hello Hong Kong')
print(1+1)
print(3-1)
print(3*4)
print(12/4)
# print('iphone'+4)
# 字符串不可以直接加上数字
print(int('2')+3) # int 定义为整数型
print(int(1.9)) # 当 int 一个浮点型数时,int 会保留整数部分
print(float('1.2')+3) # float()是浮点型,可以把字符串转换成小数
# python 可以直接运算,也可以用 print() 打印出来
print(3**2) # **2表示2次方
print(3**3) # **3表示3次方
print(3**4) # **4表示4次方
print(8%3) # 余数符号为%,返回的值是相除后的余数
apple = 1
print(apple)
apple = 'iphone 7 plus' # 赋值字符串
print(apple)
a,b,c = 11,12,13 # 一次定义多个变量
print(a,b,c)
condition = 0
while condition < 10:
print(condition)
condition = condition + 1
condition = 10
while condition:
print(condition)
condition -= 1
a = range(10)
while a:
print(a[-1])
a = a[:len(a)-1]
example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
print(i)
example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:
print(i)
print('inner of for')
print('outer of for')
for i in range(1,10):
print(i)
tup = ('python', 2.7 , 64)
for i in tup:
print(i)
dic = {}
dic['lan'] = 'python'
dic['version'] = 2.7
dic['platform'] = 64
for key in dic:
print(key, dic[key])
s = set(['python','python2','python3','python'])
for item in s:
print(item)
# define a Fib class
class Fib(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
# using Fib object
for i in Fib(5):
print(i)
def fib(max):
a, b = 0,1
while max:
r = b
a, b = b, a+b
max -= 1
yield r
# using generator
for i in fib(5):
print(i)
|
5f338224720decf8d6c037e6b2c09067e1ebfbb0 | daniel-reich/turbo-robot | /qTmbTWqHNTtDMKD4G_2.py | 2,411 | 4.25 | 4 | """
It's been a long day for Matt. After working on Edabit for quite a bit, he
decided to go out and get a beer at the local bar a few miles down the road.
However, what Matt didn't realise, was that with too much drinks you can't
find the way home properly anymore. Your goal is to help Matt get back home by
telling him how long the path to his house is if he drives the optimal route.
Matt lives in a simple world: there is only dirt (represented by a dot), a
single house (Matt's house, represented by the letter "h") and there are trees
(represented by the letter "t") which he obviously can't drive through. Matt
has an unlimited amount of moves and each move he can go north, north-east,
east, south-east, south, south-west, west and north-west. There will only be
one Matt and one house, which is Matt's.
The world is given to you as a comma-delimited string which represents the
cells in the world from top-left to bottom-right. A 3x3 world with Matt on the
top-left and his house on the bottom-right, with a tree in the middle would be
represented as:
m,.,.,.,t,.,.,.,h
The answer to this world would be 3: Matt would first move east, then south-
east, then south (or south > south-east > east). The function call related to
this example would be the following:
get_path_length("m,.,.,.,t,.,.,.,h", 3, 3)
If Matt is unable to get home from his current location, return `-1`,
otherwise return the amount of moves Matt has to make to get home if he
follows the optimal path. You are given the world, it's width and it's height.
**Good luck!**
"""
from queue import Queue
def get_path_length(world, width, height):
p2idx = lambda x, y: x * height + y
p_in_range = lambda x, y: 0 <= x < height and 0 <= y < width
dirs = [(0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)]
world = world.split(',')
q, mrk, op = Queue(), [0] * (width * height), world.index('m')
ox, oy = op // width, op % width
q.put(((ox, oy), 0))
mrk[p2idx(ox, oy)] = 1
while not q.empty():
p, l = q.get()
cx, cy = p
for dx, dy in dirs:
nx, ny = cx + dx, cy + dy
if p_in_range(nx, ny) and not mrk[p2idx(nx, ny)] and world[p2idx(nx, ny)] != 't':
if world[p2idx(nx, ny)] == 'h': return l + 1
q.put(((nx, ny), l + 1))
mrk[p2idx(nx, ny)] = 1
return -1
|
737c18eaebc27123d4ee0ee770ea4cf01902acd9 | mohitsaroha03/The-Py-Algorithms | /src/3.9Stringalgorithms/WildcardMatch.py | 2,147 | 4.375 | 4 | # Link:
# IsDone: 0
# Python program to implement wildcard
# pattern matching algorithm
# Function that matches input strr with
# given wildcard pattern
def strrmatch(strr, pattern, n, m):
# empty pattern can only match with
# empty strring
if (m == 0):
return (n == 0)
# lookup table for storing results of
# subproblems
lookup = [[False for i in range(m + 1)] for j in range(n + 1)]
# empty pattern can match with empty strring
lookup[0][0] = True
# Only '*' can match with empty strring
for j in range(1, m + 1):
if (pattern[j - 1] == '*'):
lookup[0][j] = lookup[0][j - 1]
# fill the table in bottom-up fashion
for i in range(1, n + 1):
for j in range(1, m + 1):
# Two cases if we see a '*'
# a) We ignore ‘*’ character and move
# to next character in the pattern,
# i.e., ‘*’ indicates an empty sequence.
# b) '*' character matches with ith
# character in input
if (pattern[j - 1] == '*'):
lookup[i][j] = lookup[i][j - 1] or lookup[i - 1][j]
# Current characters are considered as
# matching in two cases
# (a) current character of pattern is '?'
# (b) characters actually match
elif (pattern[j - 1] == '?' or strr[i - 1] == pattern[j - 1]):
lookup[i][j] = lookup[i - 1][j - 1]
# If characters don't match
else:
lookup[i][j] = False
return lookup[n][m]
# Driver code
strr = "baaabab"
pattern = "*****ba*****ab"
# char pattern[] = "ba*****ab"
# char pattern[] = "ba*ab"
# char pattern[] = "a*ab"
# char pattern[] = "a*****ab"
# char pattern[] = "*a*****ab"
# char pattern[] = "ba*ab****"
# char pattern[] = "****"
# char pattern[] = "*"
# char pattern[] = "aa?ab"
# char pattern[] = "b*b"
# char pattern[] = "a*a"
# char pattern[] = "baaabab"
# char pattern[] = "?baaabab"
# char pattern[] = "*baaaba*"
if (strrmatch(strr, pattern, len(strr), len(pattern))):
print("Yes")
else:
print("No")
|
15ae3b082c03b338927ad7c1cc06ed8a8bbf7ef3 | nandadao/Python_note | /note/my_note/second_month/day04/struct.py | 287 | 3.53125 | 4 | """
struct模块打包数据
"""
import struct
# 生成格式对象 i->int f---> float s--> bytes
st = struct.Struct("i4sif")
# 数据打包
data = st.pack(1, b"Lily", 172, 8)
# print(data)
# 解析数据
print(st.unpack(data))
print(type(st.unpack(data)))
|
7384e0f03b7d7066d932b3dbe9ef6f0795789e19 | indexcardpills/python-labs | /16_variable_arguments/16_01_args.py | 194 | 3.734375 | 4 | '''
Write a script with a function that demonstrates the use of *args.
'''
def tennis_score(*args):
for x in args:
print(x)
tennis_score('love', 15, 30, 40, 'deuce', 'advantage') |
287c408405e2e6971a9fe384f3a5982fd5d08fac | NiaWilliams/python | /practice2.py | 261 | 3.859375 | 4 | demond_salary = 525600
arelia_salary = 135820
def potato(salary):
if demond_salary > arelia_salary:
print('Demond\'s salary is greater than Arelia\'s salary.')
# if True:
# print(demond_salary + arelia_salary)
potato(7531) |
ef4f2abd65eb75775cf41e86cc86a5b6da6c98dd | fatima-naqvi/Python-Problems | /Fatima/random.py | 190 | 4.0625 | 4 | print("Enter your age : ")
age: int = int(input())
if age > 12 :
print("What did one wall say to the other wall? I’ll meet you at the corner!")
elif age > 11 :
|
ba61f04914fd54610dd924b5d88cc0e584b25888 | jeff-cangialosi/learn_python | /ex12.py | 474 | 4 | 4 | # Exercise 12
# I went a little ahead and changed up this exercise a little.
biggest_city_wi = input("What is the biggest city in Wisconsin? ")
biggest_city_il = input("What is the biggest city in Illinois? " )
biggest_city_mi = input("What is the biggest city in Michigan? ")
print(f"""\nWhen we scope out cities around Lake Michigan,
we see that {biggest_city_wi} is the biggest city in Wisconsin,
{biggest_city_il} in Illinois, and {biggest_city_mi} in Michigan.
"""
)
|
84e36755891df8aeb20ca49d08e8d1571e9db4e7 | SUTDNLP/ZPar | /scripts/var/cclassifier/posreader.py | 191 | 3.53125 | 4 | import sys
def readpossent(path):
file = open(path)
for line in file:
line = line[:-1]
sent = line.split()
yield [word.split('|') for word in sent]
file.close()
|
2846a8f6563b129cd159ebd123f1157990cc5d92 | Spursh/Edmodo | /unit_test.py | 4,576 | 3.6875 | 4 | import unittest
from python_file_reader import is_not_valid_date, split_line, is_row_valid, insert_valid_rows, \
is_user_entry_valid
class TestIsNotValidDate(unittest.TestCase):
def test_not_valid_date1(self):
self.assertTrue(is_not_valid_date(r"2016-06-100-17:53:22"))
def test_not_valid_date2(self):
self.assertTrue(is_not_valid_date(r"1111-06-10-17:69:22"))
def test_valid_date3(self):
expected = False
actual = is_not_valid_date(r"2016-06-10-17:53:22")
self.assertEqual(expected, actual)
class TestSplitLine(unittest.TestCase):
def test_split1(self):
expected = ['8', '2016-06-10-17:53:22', 'Str1', 'Value', 'Str3']
actual = split_line(r'8 2016-06-10-17:53:22 Str1 Value Str3')
self.assertEqual(expected, actual)
def test_split2(self):
expected = ['10', '2016-06-10-17:53:22', '"Also invalid"', 'Str2']
actual = split_line(r'10 2016-06-10-17:53:22 "Also invalid" Str2')
self.assertEqual(expected, actual)
def test_split3(self):
expected = [
'7',
'2016-06-10-17:53:22',
'"A quoted string we don’t care about"',
'"The string we do care about."',
'"Another string we don’t are about with escaped\\" \\" quotes. "']
actual = split_line(
r'7 2016-06-10-17:53:22 "A quoted string we don’t care about" "The string we do care about." "Another '
r'string we don’t are about with escaped\" \" quotes. "')
self.assertEqual(expected, actual)
class TestRowValidity(unittest.TestCase):
def test_check_row_validity1(self):
row = ['8', '2016-06-10-17:53:22', 'Str1', 'Value', 'Str3']
expected = True
actual = is_row_valid(row)
self.assertEqual(expected, actual)
def test_check_row_validity2(self):
row = [
'-1',
'2016-06-10-17:53:22',
'"This line is invalid"',
'Str2',
'Str3']
expected = False
actual = is_row_valid(row)
self.assertEqual(expected, actual)
def test_check_row_validity3(self):
row = [
'7',
'2016-06-10-17:53:22',
'"A quoted string we don’t care about"',
'"The string we do care about."',
'"Another string we don’t are about with escaped\\" \\" quotes. "']
expected = True
actual = is_row_valid(row)
self.assertEqual(expected, actual)
def test_check_row_validity4(self):
row = ['10', '1111-06-10-17:69:22', '"Also invalid"', 'Str2', 'Str3']
expected = False
actual = is_row_valid(row)
self.assertEqual(expected, actual)
def test_check_row_validity5(self):
row = [
'10',
'2016-06-10',
'17:53:22',
'"Also invalid"',
'Str2',
'Str3']
expected = False
actual = is_row_valid(row)
self.assertEqual(expected, actual)
def test_check_row_validity6(self):
row = [""]
expected = False
actual = is_row_valid(row)
self.assertEqual(expected, actual)
def test_check_row_validity7(self):
row = []
expected = False
actual = is_row_valid(row)
self.assertEqual(expected, actual)
class TestUserEntry(unittest.TestCase):
row1 = ['8', '2016-06-10-17:53:22', 'Str1', 'Value', 'Str3']
row2 = ['9', '2016-06-10-17:53:22', 'Str1', 'Value2', 'Str3']
insert_valid_rows(row1)
insert_valid_rows(row2)
def test_check_valid_user_entry1(self):
expected = True
actual = is_user_entry_valid("8")
self.assertEqual(expected, actual)
def test_check_valid_user_entry2(self):
expected = False
actual = is_user_entry_valid("fghfhgfhg")
self.assertEqual(expected, actual)
def test_check_valid_user_entry3(self):
expected = False
actual = is_user_entry_valid("")
self.assertEqual(expected, actual)
def test_check_valid_user_entry4(self):
expected = True
actual = is_user_entry_valid("9")
self.assertEqual(expected, actual)
def test_check_valid_user_entry5(self):
expected = False
actual = is_user_entry_valid("6")
self.assertEqual(expected, actual)
def test_check_valid_user_entry6(self):
expected = False
actual = is_user_entry_valid(",,,,,")
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
5417087ddd289111a3f5846729fd25e4e2ed433f | AmitLY21/image_convert_app | /ImageConverter/program.py | 4,045 | 3.859375 | 4 | import os
from tkinter import filedialog
from PIL import Image
import tkinter as tk
"""
In this project Ive learned while coding the tkinter library and pillow library.
Made an application that convert photos from png to jpg and jpg to png.
Added file explorer option and saved the converted photos to a different Directory
"""
class Counter:
def __init__(self):
self.counter = 1
counter = Counter()
changed_pic = ''
def browse_files():
global changed_pic
filename = filedialog.askopenfilename(initialdir="/", title="Select a File", filetypes=(("Image Files",
"*.png* *.jpg*"),
("all files", "*.*")))
changed_pic = filename
change_text(label_changed, filename)
def jpg_convert(counter):
if len(changed_pic) > 0:
im = Image.open(changed_pic).convert('RGB')
im.save(f'converted_images/converted{counter.counter}.jpg')
msg = 'Converted to jpg\nSaved in converted_images_directory'
change_text(txt=label_changed, msg=msg)
counter.counter += 1
else:
change_text(txt=label_changed, msg='Choose Image to convert')
def png_convert(counter):
if len(changed_pic) > 0:
im = Image.open(changed_pic)
im.save(f'converted_images/converted{counter.counter}.png')
msg = 'Converted to png\nSaved in converted_images_directory'
change_text(txt=label_changed, msg=msg)
counter.counter += 1
else:
change_text(txt=label_changed, msg='Choose Image to convert')
def change_text(txt, msg):
txt.config(text=msg)
def open_image_folder():
path = 'C:\\Users\\user\\Desktop\\Game Dev\\ImageConverter\\converted_images'
path = os.path.realpath(path)
os.startfile(path)
# Creating window
window = tk.Tk()
window.title("Image Converter")
window.geometry('300x500')
bg_color = '#536162'
window.configure(bg=bg_color)
# images
icon = tk.PhotoImage(file='images/icon.png')
middle_convert_pic = tk.PhotoImage(file='images/resizing.png')
window.iconphoto(False, icon)
# creating frames
frame = tk.Frame(window)
frame.configure(bg=bg_color)
frame.pack()
# top - frame
top_frame = tk.Frame(frame)
top_frame.grid(row=0, column=0, pady=50)
top_frame.configure(bg=bg_color)
# center mid pic
panel = tk.Label(top_frame, image=middle_convert_pic)
panel.pack(side='top')
panel.configure(bg=bg_color)
# bottom - frame
bottom_frame = tk.Frame(frame)
bottom_frame.grid(row=1, column=0, pady=20)
bottom_frame.configure(bg=bg_color)
# inside bottom frame
b_frame_top = tk.Frame(bottom_frame)
b_frame_top.grid(row=0, column=0, pady=10)
b_frame_top.configure(bg=bg_color)
b_frame_bottom = tk.Frame(bottom_frame)
b_frame_bottom.grid(row=1, column=0, pady=10)
b_frame_bottom.configure(bg=bg_color)
# Creating buttons
button_color = '#F3F4ED'
# File explorer button
button_explore = tk.Button(b_frame_top, text="Browse Files", command=browse_files,
bg=button_color)
button_explore.pack(side='top')
# Label that alert to changes
label_changed = tk.Label(b_frame_top, text='Nothing changed yet', bg=bg_color, borderwidth=20)
label_changed.pack(side='bottom')
# Open folder btn
open_folder = tk.Button(b_frame_top, text='Open Folder', command=open_image_folder,
bg=button_color)
open_folder.pack(side='bottom', pady=20)
# Converting button and functions
convert_to_jpg = tk.Button(b_frame_bottom, text='Convert to JPG', command=lambda: jpg_convert(counter),
bg=button_color)
convert_to_jpg.grid(row=0, column=0)
convert_to_png = tk.Button(b_frame_bottom, text='Convert to PNG', command=lambda: png_convert(counter),
bg=button_color)
convert_to_png.grid(row=0, column=2, padx=10)
window.mainloop()
|
70d379ece0c0df877437b029e9c49aadb5c5da58 | ankit-rane/Task-reminder | /Task reminder.py | 699 | 3.65625 | 4 | import time
from plyer import notification # installed plyer by giving the command pip install plyer.
if __name__=="__main__": # it helps in encapsulation
while True:
# running a loop to push notification after a given time.
Reminder=input("Enter that task you want to get reminded of")
reminder_interval=int(input("Enter the time (in hrs) of the task you want to get reminded of"))
notification.notify(title = "**Its time for your task",
message = "Don't ignore your tasks, kindly do "+Reminder,
timeout=10
# the amount of time the notfication would be displayed
)
time.sleep(reminder_interval*3600) |
854f991a95353f1fe9d4425097da2859c9147976 | sparklynjewel/PYTHON_TASK3 | /Modified Number Guessing Game.py | 3,039 | 4.0625 | 4 | import random
level = 0
print("Hello lets play a game")
game = True
while True:
print("To begin please select a level of difficulty")
level = int(input("input a level of difficulty 1 for easy, 2 for medium and 3 for hard!.\n"))
if level == 1:
print("This is the easy level")
break
if level == 2:
print("This is the medium level")
break
if level == 3:
print("This is the hard level")
break
elif level != 1 and level != 2 and level != 3:
print("invalid input!")
while level == 1:
easy = random.randint(1, 10)
try:
print("I've got a private number between 1 and 10, are you able to guess it?")
attempts = 6
for attempt in range(attempts, 0, -1):
print("You have {0} attempts left.".format(attempt))
userNumber = int(input("please enter number guessed \n"))
if userNumber > easy:
print("That was wrong, your answer is too high")
if userNumber < easy:
print("That was wrong, Your answer is too low")
if userNumber == easy:
print("You got it right")
break
attempts -= 1
if attempts <= 0:
print("Game Over")
input("\nThanks for playing")
except ValueError:
print("please input a number")
while level == 2:
medium = random.randint(1, 20)
try:
print("I've got a private number between 1 and 10, are you able to guess it?")
attempts = 4
for attempt in range(attempts, 0, -1):
print("You have {0} attempts left.".format(attempt))
userNumber = int(input("please enter number guessed \n"))
if userNumber > medium:
print("That was wrong, your answer is too high")
if userNumber < medium:
print("That was wrong, Your answer is too low")
if userNumber == medium:
print("You got it right")
break
attempts -= 1
if attempts <= 0:
print("Game Over")
input("\nThanks for playing")
except ValueError:
print("please input a number")
while level == 3:
hard = random.randint(1, 50)
try:
print("I've got a private number between 1 and 50, are you able to guess it")
attempts = 3
for attempt in range(attempts, 0, -1):
print("You have {0} attempts left.".format(attempt))
userNumber = int(input("please enter number guessed \n"))
if userNumber > hard:
print("That was wrong, your answer is too high")
if userNumber < hard:
print("That was wrong, your answer is too low")
if userNumber == hard:
print("You got it right")
break
attempts -= 1
if attempts <= 0:
print("Game Over")
input("\nThanks for playing")
except ValueError:
print("please input a number")
|
26ce16b6c7c5cb73579dee69e17bc7adbe38f6f9 | aearl16/Python | /src/Python 3/RaspberryPi/blink.py | 1,095 | 3.90625 | 4 | ################################
# #
# LED Blink #
# #
################################
# #
# @Author: Aaron Earl #
# #
# Tutorial from Freenove to #
# make an LED blink on #
# a Raspbery Pi Zero W #
################################
import RPi.GPIO as GPIO
import time
ledPin = 11 #RPi board pin 11
def setup():
GPIO.setmode(GPIO.BOARD) # Numpers GPIOs by Physical Location
GPIO.setup(ledPin, GPIO.OUT) # Set ledPin's mode to output
GPIO.output(ledPin, GPIO.LOW) # Set ledPin low to turn LED off
print('using pin %d' %ledPin)
def loop():
while True:
GPIO.output(ledPin, GPIO.HIGH) # Turn LED On
print("...LED On")
time.sleep(1) # Delay 1 second
GPIO.output(ledPin, GPIO.LOW) # Turne LED Off
print("...LED Off")
time.sleep(1)
def destroy():
GPIO.output(ledPin, GPIO.LOW) # Turn LED Off
GPIO.cleanup() # Release resources
if __name__ == "__main__": # Program start
setup()
try:
loop()
except KeyboardInterrupt: # When Ctrl-C is pressed, the subroutine destroy() will be executed
destroy()
|
d39c171c6a84f0b787ab2dea1e7f99a121a92c5d | IvayloValkov/Python-the-beginning | /Exams/03_oscars_week_in_cinema.py | 886 | 3.6875 | 4 | movie = input()
hall = input()
tickets = int(input())
price = 0
if movie == 'A Star Is Born':
if hall == 'normal':
price = 7.50
elif hall == 'luxury':
price = 10.50
elif hall == 'ultra luxury':
price = 13.50
elif movie == 'Bohemian Rhapsody':
if hall == 'normal':
price = 7.35
elif hall == 'luxury':
price = 9.45
elif hall == 'ultra luxury':
price = 12.75
elif movie == 'Green Book':
if hall == 'normal':
price = 8.15
elif hall == 'luxury':
price = 10.25
elif hall == 'ultra luxury':
price = 13.25
elif movie == 'The Favourite':
if hall == 'normal':
price = 8.75
elif hall == 'luxury':
price = 11.55
elif hall == 'ultra luxury':
price = 13.95
total = price * tickets
print(f'{movie} -> {total:.2f} lv.') |
f83a824f24b19fdbcae3afed9d28efaa8de46d0e | Qiutiancheng/Python | /hello.py | 780 | 4 | 4 | import math
# define a function
def something (arg1,arg2):
return 'Something'
# It's still work if you don't return
def PrintSomething (c):
fahremheit = str(c * 9/5 + 32)
print(fahremheit + '℉')
PrintSomething(17)
# G to KG
def toKilogram (v):
kilogram = str(v/1000)
return print(kilogram + 'KG')
toKilogram(500)
# get hypotenuse
def getHypotenuse (a,b):
# 开根
hypotenuse = math.sqrt(a * a + b * b)
return print(hypotenuse)
getHypotenuse(3,4)
# sep:The printed results are separated by the value of sep
print(' *',' * *',' * * *',' | ',sep='\n')
# 写入一个文件,'w'参数表示如果没有该文件则创建一个,否则写入并覆盖文本内容
file = open('C://Users/FE/Desktop/TODO.txt','w')
file.write('hi')
|
f17d4a07fcde5ced510c4a27e8a01b0723c9e7b1 | rajatAS142/Takshashila-Python-SQL-Assignment | /Assignment Q4.py | 1,667 | 3.5 | 4 | #installing the libraries psycopg2, Workbook, pandas
import psycopg2
from openpyxl.workbook import Workbook
import pandas as pd
class employee_info:
def emp(self):
try:
# to connect to the PostgreSQL database server in the Python program using the psycopg database adapter.
con = psycopg2.connect(
database="python-sql",
user="postgres",
password="timestone4me")
# Creating a cursor object using the cursor() method
cursor = con.cursor()
# Reading table which we imported using connection through query
query_data_command = """
select dept.deptno, dept_name, sum(total_compensation) from Compensation, dept
where Compensation.dept_name=dept.dname
group by dept_name, dept.deptno
"""
cursor.execute(query_data_command)
#iterating inside description
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
dataframe = pd.DataFrame(list(data), columns=columns)
#storing values inside excel
writer = pd.ExcelWriter('ques_4.xlsx')
# converting data frame to excel
dataframe.to_excel(writer, sheet_name='bar')
writer.save()
except Exception as e:
print("Something went wrong", e)
finally:
if con is not None:
cursor.close()
con.close()
if __name__ == '__main__':
con = None
cur = None
employee = employee_info()
employee.emp()
|
fdf73fad63d98de302cbd95d4bd515c66cab9c93 | lemonad/advent-of-code | /2019-misc/december1.py | 1,578 | 3.609375 | 4 | """
December 1, Advent of Code 2019 (Jonas Nockert / @lemonad)
"""
import numpy as np
import pandas as pd
from common.puzzlesolver import PuzzleSolver
class Solver(PuzzleSolver):
def __init__(self, *args, **kwargs):
super(Solver, self).__init__(*args, **kwargs)
@staticmethod
def add_fuel_column(df):
"""Adds a column with the fuel cost for the previous column"""
s_col = df.iloc[:, -1]
n_cols = len(df.columns)
col_label = "iter-{:d}".format(n_cols)
df.insert(n_cols, col_label, ((s_col / 3).apply(np.floor) - 2).clip(0))
def solve_part_one(self):
df = pd.DataFrame(self.lines(conversion=int))
self.add_fuel_column(df)
return df.iloc[:, 1:].sum().sum().astype("int")
def solve_part_two(self):
df = pd.DataFrame(self.lines(conversion=int))
while df.iloc[:, -1].sum() > 0:
self.add_fuel_column(df)
return df.iloc[:, 1:].sum().sum().astype("int")
if __name__ == "__main__":
example_input = """
12
14
1969
100756
"""
s = Solver(from_str=example_input)
one = s.solve_part_one()
assert one == 2 + 2 + 654 + 33583
s = Solver(from_file="input/december1.input")
one = s.solve_part_one()
print(one)
assert one == 3372463
example_input = """
14
1969
100756
"""
s = Solver(from_str=example_input)
two = s.solve_part_two()
assert two == 2 + 966 + 50346
s = Solver(from_file="input/december1.input")
two = s.solve_part_two()
print(two)
assert two == 5055835
|
9df67cbc5b7b8a11f600233598b1c5a4e30ce2f6 | 369geofreeman/MITx_6.00.1x | /HackerRank/loops.py | 157 | 3.828125 | 4 | # Loops
# The provided code stub reads and integer, n, from STDIN. For all non-negative integers i<n, print i².
n = 10
for i in range(n):
print(i*i)
|
b4158154c8b0ef3356a9323b22fc9397e94d83ab | neveSZ/fatecsp-ads | /IAL-002/Listas/2-Seleção/08.py | 415 | 3.953125 | 4 | '''
Fornecidos os três segmentos de reta: a, b e c (a>0, b>0 e c>0), verificar
se podem formar um triangulo. Exibir a mensagem ‘formam’ ou ‘não formam’,
conforme o caso.
'''
a = float(input('a: '))
b = float(input('b: '))
c = float(input('c: '))
if (a < b+c) and (b < a+c) and (c < a+b):
if(c-b < a > b-c) and (c-a < b > a-c) and (b-a < c > a-b):
print('formam')
else:
print('nao formam')
|
d1759e52a738342069376c6b97504b310574d2af | shiveshsky/datastructures | /contest_IV/test.py | 588 | 3.953125 | 4 | def merge(common, row):
i=0
j=0
merged = []
if len(common)==0:
return row
while i<len(common) and j<len(row):
if common[i]==row[j]:
merged.append(common[i])
i+=1
j+=1
elif common[i]<row[j]:
i+=1
elif common[i]>row[j]:
j+=1
return merged
def common_matrix(mat):
common = []
for row in mat:
common = merge(common, row)
return common
if __name__ == "__main__":
print(common_matrix([[1, 2, 3, 4, 5],[2, 4, 5, 8, 10],[3, 5, 7, 9, 11],[1, 3, 5, 7, 9]])) |
661c6cb5b2eb5557461d98aa847dea82f0ff51ae | leforestier/naval | /naval/__init__.py | 2,855 | 3.921875 | 4 | """
---------------
Examples of use
---------------
Simple validation
=================
.. code:: python
>>> from naval import *
>>> address_schema = Schema(
['house number', Type(int), Range(1, 10000)],
['street', Type(str), Length(min=5, max=255)],
['zipcode', Type(str), Regex('\d{4,5}')],
['country', ('France', 'Germany', 'Spain')]
)
>>> address_schema.validate({
'house number': 12000,
'street': 'tapioca boulevard',
'country': 'Federal Kingdom of Portulombia'
})
...
ValidationError: {'house number': 'The maximum is 10000.', 'zipcode': 'Field is missing.', 'country': 'Incorrect value.'}
>>> address_schema.validate({
'house number': 17,
'street': 'rambla del Raval',
'zipcode': '08001',
'country': 'Spain'
})
{'country': 'Spain',
'house number': 17,
'street': 'rambla del Raval',
'zipcode': '08001'}
Validation and transformation
=============================
.. code:: python
>>> from naval import *
>>> from passlib.hash import bcrypt # we're going to use the passlib library to encrypt passwords
>>> registration_form = Schema(
['username', Type(str), Length(min=3, max=16)],
['password', Type(str)],
['password2'],
[
Assert(
(lambda d: d['password'] == d['password2']),
error_message = "Passwords don't match"
)
],
['password', lambda s: s.encode('utf-8'), bcrypt.encrypt, Save],
['password2', Delete],
['email', Email]
)
>>> registration_form.validate({
'email': 'the-king@example.com',
'username': 'TheKing',
'password': 'hackme',
'password2': 'hackme'
})
{'email': 'the-king@example.com',
'password': '$2a$12$JT2UlXP0REt3EX7kGIFGV.5uKPQJL4phDRpfcplW91sJAyB8RuKwm',
'username': 'TheKing'}
>>> registration_form.validate({
'username': 'TheKing',
'email': '@@@@@@@@@@',
'password': 'hackme',
'password2': 'saltme'
})
...
ValidationError: {'email': 'This is not a valid email address.', '*': "Passwords don't match"}
Internationalization
====================
Supply a ``lang`` keyword argument to the ``validate`` method to obtain translated error messages.
.. code:: python
>>> editor_schema.validate(
{ 'website': 'http://#' },
lang = 'fr'
)
...
ValidationError: {'name': 'Champ manquant.', 'website': "Ce n'est pas une url valide."}
"""
__author__ = "Benjamin Le Forestier (benjamin@leforestier.org)"
__version__ = '1.0.0'
from naval.core import *
from naval.util import Email, Domain, Url
|
c49303c4e1c367233c87d8208911ee793eb9f675 | r2dme/COMP-5005_FOP | /FOP/FOP/PracTest3/testAccounts.py | 887 | 3.59375 | 4 | from accounts import BankAccount
def balances():
print('\n#### Balances ####\n')
total = 0
for i in range(len(my_accounts)):
print("Name: ", my_accounts[i].name, "\tNumber: ", my_accounts[i].number, \
"\tBalance: ", my_accounts[i].balance)
total = total + my_accounts[i].balance
print("\t\t\t\t\tTotal: ", total)
savings = BankAccount('Savings','123456',3000)
cheque = BankAccount('Cheque','234567',300)
print('\n#### Bank Accounts ####\n')
my_accounts = []
account = BankAccount('Savings','123456',3000)
my_accounts.append(account)
account = BankAccount('Cheque','234567',300)
my_accounts.append(account)
balances()
my_accounts[0].deposit(100)
my_accounts[1].withdraw(30)
my_accounts[1].withdraw(1000)
my_accounts[0].add_interest()
my_accounts[1].add_interest()
my_accounts[0].apply_fees()
my_accounts[1].apply_fees()
balances()
|
8aaaf02ce647ff655fd97b32f75b00dd9a2392d0 | thumphries/python | /tree.py | 2,349 | 4.15625 | 4 | #!/usr/bin/env python
# tree.py
# very basic tree with traversals
import sys
class Tree(object):
def __init__(self):
self.root = None
def insert(self, value):
node = Node(value)
if (self.root == None):
self.root = node
else:
self.root.insert(node)
def list(self):
result = []
if (self.root):
self.root.inorder(result.append)
return result
def list_nonrec(self):
result = []
if (self.root):
self.root.inorder_nonrec(result.append)
return result
class Node(object):
def __init__(self, v):
self.value = v
self.left = None
self.right = None
def insert(self, node):
if (node.value > self.value):
self.insert_right(node)
elif (node.value < self.value):
self.insert_left(node)
else:
return
def insert_right(self, node):
if (self.right == None):
self.right = node
else:
self.right.insert(node)
def insert_left(self, node):
if (self.left == None):
self.left = node
else:
self.left.insert(node)
def inorder(self, fun):
if (self.left):
self.left.inorder(fun)
fun(self.value)
if (self.right):
self.right.inorder(fun)
def preorder(self, fun):
fun(self.value)
if (self.left):
self.left.preorder(fun)
if (self.right):
self.right.preorder(fun)
def postorder(self, fun):
if (self.left):
self.left.postorder(fun)
if (self.right):
self.right.postorder(fun)
fun(self.value)
def inorder_nonrec(self, fun):
stack = [self]
visited = {}
while (stack):
t = stack.pop()
if (t not in visited):
if (t.right):
stack.append(t.right)
visited[t] = 1
stack.append(t)
if (t.left):
stack.append(t.left)
else:
fun(t.value)
tree = Tree()
tree.insert(5)
tree.insert(1)
tree.insert(9)
tree.insert(100)
tree.insert(150)
tree.insert(1)
tree.insert(3)
tree.insert(6)
tree.insert(191)
print(tree.list_nonrec())
|
1d8eb937bc70b795ec6cea11d21e746a046f49b1 | iompku/adventcode2020 | /8/8.py | 2,284 | 3.5625 | 4 |
import string
f = open("input.txt")
valid = 0
code = []
i = 0
# parse input file, add line number, instruction, and number to a code list
for line in f:
list = [i]
list2 = line.split(' ')
list.append(list2[0])
list.append(int(list2[1].strip()))
code.append(list)
i += 1
#print(code)
#run the code, and keep track of every line ran
lineRan = []
redone = -1
acc = 0
line = []
codeLine = 0
lastLine = -1
old = ''
finished = False
linetoswap = -1
# this outer loop is part 2, testing every line of code that is nop
# or jmp and swapping it to the other to see if we can make it to the end
for test in code:
if (finished): #quit testing if we found the swap that works
break
if (test[1] == 'nop'):
#print("Trying line " + str(test[0]))
old = 'nop'
code[test[0]][1] = 'jmp'
elif (test[1] == 'jmp'):
#print("Trying line " + str(test[0]))
old = 'jmp'
code[test[0]][1] = 'nop'
else: # not swapping acc commands
continue
# important to reset these each time
codeLine = 0
acc = 0
lineRan = []
# run the code
while (True):
line = code[codeLine]
if line[0] in lineRan:
redone = line[0]
break
lineRan.append(line[0])
if (codeLine == 627): #we made it to the final line of code
print("Done!")
finished = True
linetoswap = test[0]
break
elif(line[1] == 'acc'):
acc += line[2]
codeLine += 1
#print(line, end=' ')
#print("acc = " + str(acc))
elif(line[1] == 'jmp'):
lastLine = codeLine
codeLine += line[2]
#print(line, end=' ')
#print('jmp to line ' + str(codeLine))
elif(line[1] == 'nop'):
lastLine = codeLine
codeLine += 1
# put code back to the way it was before
if (old == 'nop'):
code[test[0]][1] = 'nop'
elif (old == 'jmp'):
code[test[0]][1] = 'jmp'
#print(redone)
print("Acc = " + str(acc))
print("Line to swap: " + str(linetoswap))
#print(lastLine)
f.close()
|
e0c0310711e9d0c012b6e37a389dd8f503a1299c | Raxephion/Python-Gravity-Acceleration-Calculator | /Python Gravity Calculator.py | 718 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 16:48:26 2020
@author: Pierre-Henri Rossouw
This script calculates the gravity acceleration at any point in the known universe
up to 15 decimal places accuracy
"""
G = 6.673*10**-11
M_Input = input(" What is the mass of the planet/moon/star/asteroid/comet or other heavenly body? ")
d_Input = input("What is the radius of the object? ")
M = eval(M_Input)
d = eval(d_Input)
eg=9.8
g=(G*M)/d**2
ng=g/eg
print("The mass of your object is ", M, "kg")
print("The radius of your object is ", d, "metres")
print("The Gravity Acceleration for your point is: ", g," metres per second squared")
print("That means the gravity you are experiencing is ", ng , " times that of on Earth") |
9c1a8c50b355aca40d205d8ba6f3abca11585658 | jinwoo0710/python | /0507/rectArea.py | 458 | 3.625 | 4 |
def calcarea(r):
area = 3.14159 * r * r
return area
r = int(input("원의 반지름 : "))
print("반지름이", r , "인 원의 면적은", area, "입니다.")
def calcArea(b, h):
area = b * h
return area
base = int(input("밑변의 길이 : "))
height = int(input("높이의 길이 : "))
recArea = calcArea(base, height)
print("밑변과 높이가", base, height, "인 사각형의 면적은", recArea, "입니다.")
|
25ca6b41503b3c01b0ba71c5122fff0c471c89c5 | jacobbathan/python-examples | /ex8.12.py | 499 | 3.890625 | 4 | # exercise 8.12 ROT13 encryption
def rotate_word(string, rotations):
lower_string = string.lower()
num_string = []
new_string = ''
for char in lower_string:
num_char = ord(char) - 96 + rotations
num_string.append(num_char)
for num in num_string:
new_char = chr(96 + (num % 26))
new_string += new_char
print(new_string)
rotate_word('cheer',7) # expeceted result: jolly
rotate_word('melon', -10) # expected result: cubed
|
04151e7c95d448f0df7e8095d6e493a11aed80b9 | jackspicer1229/CSCI4446 | /logMap.py | 889 | 3.578125 | 4 | import matplotlib.pyplot as plt
m = input('Enter a value for m: ')
R = 3
x0 = 0.2
nArray = []
xNarray = []
xNPlusOneArray = []
for i in range (0,m):
x_n1 = R*x0*(1-x0)
xNarray.append(x0)
xNPlusOneArray.append(x_n1)
x0 = x_n1
nArray.append(i)
xNPlusTwoArray = xNPlusOneArray[1:m]
plt.figure(figsize=(12,4))
plt.suptitle("Logistic Maps using m = " + str(m) + " and R = " + str(R))
plt.subplot(131)
plt.plot(nArray, xNarray, 'ko', markersize=1)
plt.title("$X_n$ versus $n$")
plt.xlabel("n")
plt.ylabel("$X_n$")
plt.subplot(132)
plt.plot(xNarray, xNPlusOneArray, 'ko', markersize=1)
plt.title("$X_{n+1}$ versus $X_n$")
plt.xlabel("$X_n$")
plt.ylabel("$X_{n+1}$")
plt.subplot(133)
plt.plot(xNarray[0:m-1], xNPlusTwoArray, 'ko', markersize=1)
plt.title("$X_{n+2}$ versus $X_n$")
plt.xlabel("$X_n$")
plt.ylabel("$X_{n+2}$")
plt.tight_layout()
plt.subplots_adjust(top=0.85)
plt.show()
|
f3c747fc66dbaa4f8063afc769d1386eaaa605fb | Abhay123-art/python | /1_march.py | 639 | 3.8125 | 4 | #l1 = [1,2,3,"radi,cal"]
#print(li)
l1 = [2,6,7,[7,8,9]]
print(l1[3][2])
l1 =[1,2,3,4,5,6,7,8,9]
l2 =l1[3:7]
#print(l2)
#print(l1[-6:-2])
#both are same result is same first bnumber in slicing is called as inclusive and the last one is exclusive
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
#l2 = l1[2:8:2]
#print(l2)
print(l1[-3:3])
print(l1[0:5])
#print(l1[ :5])
#l2 = l1[-5:0:-1]
print(l1[-3:0:-1])
#for reverse printing
#first value always should be smaller
l1 = ["abhay", "abhay1", "abhay2", "abhay3"]
l1.append("abhay4")
print(l1)
l1.extend("abhay4")
print(l1)
l1.insert(0, "R S R")
print(l1)
|
24e8c230d92c7b1d0838c353956d4245210ea567 | josepotal/Udacity_programming_foundations | /lesson_6_advanced ideas/media.py | 828 | 3.5 | 4 | # file that defines the Class (keep it here)
import webbrowser
class Movie():
""" This class provides a way to store movie related information """ ## this is documentation creation we access to it "(media.Movie.__doc__)'
VALID_RATINGS = ["G","PG","PG-13","R"]
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
#Class
#Instance
#Constructor
#self: points to the object
#variables
#instance variables: (title,storyline, poster_image_url,trailer_youtube_url)
#instance method
#class variables: VALID_RATINGS
|
7170ad5bc198540b646528d8df4bda55833b4461 | markbromley/ml-experiments | /simple-linear-regression.py | 3,472 | 3.84375 | 4 | import math
import random
import numpy
import matplotlib.pyplot as plt
class SimpleLinearRegression(object):
'''
A basic implementation of simple linear regression.
Calculates coefficients b0 and b1, such that f(x) = b1x + b0.
Also provides estimate for coefficient of determination (e.g. r^2).
'''
ROUNDING_LENGTH = 3
def __init__(self, x, y):
assert len(x) != 0, "No data supplied."
assert len(x) == len(y), "Input vector must be same length as target vector"
self._x = sorted(x)
self._y = sorted(y)
self._x_mean = self._get_mean(self._x)
self._y_mean = self._get_mean(self._y)
def _get_b1(self):
numerator = 0
for idx, val in enumerate(self._x):
numerator += (self._x[idx] - self._x_mean) * (self._y[idx] - self._y_mean)
denominator = 0
for idx, val in enumerate(self._x):
denominator += math.pow((val - self._x_mean),2)
return float(numerator) / float(denominator)
def _get_b0(self):
return (self._y_mean - (self._get_b1() * self._x_mean))
def _get_mean(self, x):
return (sum(float(i) for i in x)) / float(len(x))
def _get_coeff_determination(self):
return float(self._get_ssr()) / float(self._get_ssto())
def _get_ssr(self):
ssr = 0
for x in self._x:
ssr += math.pow(self.predict(x) - self._y_mean, 2)
return ssr
def _get_ssto(self):
ssto = 0
for y in self._y:
ssto += math.pow(y - self._y_mean, 2)
return ssto
def predict(self, x):
'''
Returns a predicted value by the model, given an input value.
'''
return (self._get_b1() * float(x)) + self._get_b0()
def visualise(self):
'''
Visualises the original data and the model using matplotlib.
'''
# Titles
fig = plt.figure(0)
title = "Simple Linear Regression"
fig.canvas.set_window_title(title)
plt.title(title)
plt.xlabel("X values")
plt.ylabel("Y values")
axes = plt.gca()
axes.set_xlim([self._x[0] - 1, self._x[-1] + 1])
axes.set_ylim([self.predict(self._x[0]) - 1, self.predict(self._x[-1]) + 1])
# Original data
plt.scatter(self._x, self._y)
# The regression line
pred_y = [self.predict(x) for x in self._x]
plt.plot(self._x, pred_y, label="Model prediction")
# Coeff of determination
val = ("R^2 = {}").format(str(round(self._get_coeff_determination(),self.ROUNDING_LENGTH)))
plt.text(self._x[-1],self.predict(self._x[-1]),val)
plt.show()
@property
def b1(self):
''' B1 coefficient.'''
return self._get_b1()
@property
def b0(self):
'''B0 coefficient.'''
return self._get_b0()
@property
def r2(self):
''' Coefficient of Determination.'''
return self._get_coeff_determination()
if __name__ == "__main__":
# Fake data
n = 100
x = random.sample(range(1, 1000), n)
y = random.sample(range(1, 10000), n)
# Model
slr = SimpleLinearRegression(x, y)
print("B0 Coefficient: {}".format(str(round(slr.b0,slr.ROUNDING_LENGTH))))
print("B1 Coefficient: {}".format(str(round(slr.b1,slr.ROUNDING_LENGTH))))
print("Coefficient of Determination (R^2): {}".format(str(round(slr.r2,slr.ROUNDING_LENGTH))))
slr.visualise()
|
f478907f18288773da4f4c1fc2ca293f299bc504 | harish-515/Python-Projects | /ErrorDebugging/ExceptionHandling.py | 226 | 3.546875 | 4 | def divide(a,b):
try:
return a/b
except ZeroDivisionError:
return "Divison by zero in meaningless"
except:
return "Error while executing the divison"
print(divide(1,0)) |
710c76963499abcdccab800eb0f586a3657430b3 | BZukerman/StepikRepo | /Python_Programming/Basics and use/Occurrence_SSs.py | 1,211 | 4.21875 | 4 | #
# Вашей программе на вход подаются две строки s и t, состоящие из строчных
# латинских букв.
# Выведите одно число – количество вхождений строки t в строку s.
#
s, t = (input() for i in range(2)) # Ввод исходных данных
Len_s = len(s) # Длина исходной строки
# print("Len_s:", Len_s)
Len_t = len(t) # Длина заданной подстроки
# print("Len_t:", Len_t)
N = Len_s - Len_t + 1 # Подсчет счетчика циклов
# print("N:", N)
Count = 0 # Счетчик
for i in range(N): # Цикл по номеру символа в строке
Res = s.startswith(t, i, Len_s) # Проверка наличия подстроки, начиная с индекса
if Res: # Если True
Count = Count + 1 # Увеличение счетчика
# print("Count:", Count)
print(Count) # Печать результата |
f5519db96cf8b5bb12ae814c7d1247015dfbbaad | rajatpanwar/python | /FUNCTION/Add.py | 582 | 4.09375 | 4 | in theses exapmle we ll discuss about function
<------example1------->
n1=input("enter the first no")
n2=input("enter the second no")
ttal=n1+n2
print(ttal) //output is ---44
//bcoz of input function takke input from user as a string
<------example2----->
n1=int(input("enter the first no"))
n2=int(input("enter the second no"))
ttal=n1+n2
print(str(ttal)) //output is--8
<------example3----->
n1=str(5)
n2=int("7") //chnage the string into int
n3=float("8") //change input string to float
total=n2+n3
print("total is"+total) //output is ----15.0 in float
|
0466388b11f41ad9c59afb306db7b7a6b7f7a0da | Jfadelli/Intro-Python-II | /src/adv.py | 3,207 | 3.75 | 4 | from room import Room
from player import Player
from items import Item
# Rooms
outside = Room("Outside Cave Entrance", "North of you, the cabe mount beckons", [('shield')])
foyer = Room("Foyer", "Dim light filters in from the south. Dusty passages run north and east.",[('sword')])
overlook = Room("Grand Overlook", "A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm.")
narrow = Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""")
treasure = Room("Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south.""", [])
# Link rooms together
outside.n_to = foyer
foyer.s_to = outside
foyer.n_to = overlook
foyer.e_to = narrow
overlook.s_to = foyer
narrow.w_to = foyer
narrow.n_to = treasure
treasure.s_to = narrow
# Main
# Make a new player object that is currently in the 'outside' room.
player = Player('Player 1')
player.current_room = outside
## Items
sword = Item('sword', 'Unique Sword')
shield = Item('shield', 'Rare Shield')
# Write a loop that:
#
# * Prints the current room name
print(player.current_room.name)
# * Prints the current description (the textwrap module might be useful here).
print(player.current_room.description)
# * Waits for user input and decides what to do.
user = input('enter command: [move NSEW] [get/drop] [name item]:')
command = user.split(' ')[0]
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
if len(user.split(' ')) > 1:
action = user.split(' ')[1]
item_name = user.split(' ')[1]
while not command == 'q':
if command in {'n','s','e','w'}:
if hasattr(player.current_room, f'{command}_to'):
player.current_room = getattr(
player.current_room, f'{command}_to')
print(player.current_room)
user = input('choose command: N, S, W, E, --or-- q to quit: ')
command = user.split(' ')[0]
if command in {'i', 'get', 'drop'}:
if command == 'i':
print('PlayerName:', player.items)
elif command == 'get':
item = user.split(' ')[1]
if player.current_room.items.count(f'{item}') > 0:
print(player.current_room.items)
player.current_room.items.remove(f'{item}')
print(player.current_room.items)
else:
print('That item is not in this room.')
# elif command == 'drop'
# item
else:
print('cannot move in that direction')
user = input('choose direction: N, S, W, E --or-- q to quit: ')
command = user.split(' ')[0]
else:
print('What do you choose to do?')
user = input('choose direction: N, S, W, E --or-- q to quit: ')
command = user.split(' ')[0] |
eec22730259d4165b01fbf8707b5926b98b465a2 | benoitrosa/VTK_Useful_things | /grabVideo.py | 731 | 3.640625 | 4 | import os
from natsort import natsorted
class grabVideo:
"""
grabVideo is a simple class that will list all jpg files in a folder, sort them by natural order (i.e. 1 2 3 4 .. 10, and not 1 10 2 3 4 ...) and store the result
when getNextFile is queried, it will return the path to the next image file in the list. It loops when arriving at the end.
"""
def __init__(self, path):
self.folder = path
self.files = []
for file in os.listdir(self.folder):
if file.endswith(".jpg"):
self.files.append(file)
self.files = natsorted(self.files)
self.idx = 0
def getNextFile(self):
self.idx += 1
if (self.idx > len(self.files)):
self.idx = 0
return os.path.join(self.folder, self.files[self.idx])
|
e93d3094a36e01dba4266f745ae941b69f66f896 | SIDORESMO/crAssphage | /bin/location_db.py | 4,391 | 4.34375 | 4 | """
Create a location database for our data. This is a SQLite3 database that
has a single table with the following attributes:
0. latitude
1. longitude
2. locality: the name of the city, municipality, or province in utf-8 encoding
3. country: the name of the country in utf-8 encoding
4. ascii_locality: the name of the city, municipality, or province in pure ascii
5. ascii_country: the name of the country in pure ascii
NOTE:
The latitude and longitude are stored as REALs (ie. floats) and so you
may or may not need to convert them from str. I made this decision
because they are floating point numbers and there are some
GIS calculations we could potentially do using them.
"""
import os
import sys
import sqlite3
connection = None
def get_database_connection(dbfile='../data/localities.db'):
"""
Create a connection to the database
"""
global connection
if not connection:
connection = sqlite3.connect(dbfile)
return connection
def get_database_cursor(conn=None):
"""
Connect to the database and get a cursor
:param conn: the optional connection. We will make it if not provided
"""
if not conn:
conn = get_database_connection()
return conn.cursor()
def create_database(cursor=None):
"""
Create the database tables
:param cursor: the database cursor. If not provided we'll make one and return it
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute('''CREATE TABLE location (latitude real, longitude real, locality text, country text, ascii_locality text, ascii_country text)''')
get_database_connection().commit()
return cursor
def save_location(latitude, longitude, locality, country, ascii_locality, ascii_country, cursor=None):
"""
Insert something into the database
:param latitude: the latitude in decimal degrees (signed float)
:param longitude: the longitude in decimal degrees (signed float)
:param locality: the town or metropolitan area in utf-8 text
:param country: the country in utf-8
:param ascii_locality: the locality in ascii format
:param ascii_country: the country in ascii format
:param cursor: the database cursor. If not provided we'll make one. We return this
"""
if not cursor:
cursor = get_database_cursor()
# first check to see if it exists
cursor.execute("select * from location where latitude=? and longitude=?", (latitude, longitude))
result = cursor.fetchone()
if result:
sys.stderr.write("We already have an entry for {}, {}: {}, {}\n".format(result[0], result[1], result[4], result[5]))
return cursor
cursor.execute("insert into location values (?, ?, ?, ?, ?, ?)", (latitude, longitude, locality, country, ascii_locality, ascii_country))
get_database_connection().commit()
return cursor
def get_by_latlon(latitude, longitude, cursor=None):
"""
Get the location based on the latitude and longitude
:param latitude: the latitude in decimal degrees (signed float)
:param longitude: the longitude in decimal degrees (signed float)
:param cursor: the db cursor. We can get this
:return : the array of all data
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute("select * from location where latitude=? and longitude=?", (latitude, longitude))
return cursor.fetchone()
def get_by_ascii(ascii_locality, ascii_country, cursor=None):
"""
Get the lat lon based on the ascii location
:param ascii_locality: the locality in ascii format
:param ascii_country: the country in ascii format
:return : the array of all the data
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute("select * from location where ascii_locality=? and ascii_country=?", (ascii_locality, ascii_country))
return cursor.fetchone()
def get_by_locale(locality, country, cursor=None):
"""
Get the lat lon based on the ascii location
:param locality: the locality in ascii format
:param country: the country in ascii format
:return : the array of all the data
"""
if not cursor:
cursor = get_database_cursor()
cursor.execute("select * from location where locality=? and country=?", (locality, country))
return cursor.fetchone()
|
06b0dda1f51ea8f8816452f927bc08d0c436f2f8 | ztalarick/School | /eclipse-workspace/CS115A/hw6.py | 3,615 | 3.6875 | 4 | '''
Created on 10/16/17
@author: Zachary Talarick
Pledge: I pledge my honor that I have abided by the stevens honor system. ztalaric
CS115 - Hw 6
'''
# Number of bits for data in the run-length encoding format.
# The assignment refers to this as k.
COMPRESSED_BLOCK_SIZE = 5
# Number of bits for data in the original format.
MAX_RUN_LENGTH = 2 ** COMPRESSED_BLOCK_SIZE - 1
# Do not change the variables above.
# Write your functions here. You may use those variables in your code.
def isOdd(n):
'''Returns whether or not the integer argument is odd.'''
if n % 2 == 0:
return False
return True
def numToBinary(n):
'''Precondition: integer argument is non-negative.
Returns the string with the binary representation of non-negative integer n.
If n is 0, the empty string is returned. '''
if n == 0:
return ''
elif isOdd(n) == True:
return numToBinary(n // 2) + '1'
return numToBinary(n // 2) + '0'
def binaryToNum(s):
'''Precondition: s is a string of 0s and 1s.
Returns the integer corresponding to the binary representation in s.
Note: the empty string represents 0.'''
if s == '':
return 0
n = len(s)
return (int(s[0]) * (2 ** (n - 1))) + binaryToNum(s[1:])
def countRun(S, c, MAX_RUN_LENGTH):
'''
takes a string of 0s and ones, the character it is looking for and its max run length
returns the amount of 0s, 1s in a row
'''
if S == '':
return 0
if c == S[0]:
return 1 + countRun(S[1:MAX_RUN_LENGTH], c, MAX_RUN_LENGTH)
return 0
def compress(S):
'''
param s: string to compress
count the runs in s switching
from counting runs of zeros to counting
runs of ones
return compressed string
'''
def compress_help(S, c):
if S == '':
return ''
runlen = countRun(S, c, MAX_RUN_LENGTH)
runlenBinary = numToBinary(runlen)
zeros = '0' * (COMPRESSED_BLOCK_SIZE - len(runlenBinary))
if c == '1':
nextC = '0'
if c == '0':
nextC = '1'
return zeros + runlenBinary + compress_help(S[runlen:], nextC)
return compress_help(S, '0')
def uncompress(S):
'''
param S
in chuncks of COMPRESSED_BLOCK_SIZE
convert the binary representation of a number
in that block into that many 0s or 1s
switching from 0s to 1s
switching from decompressing zeros to decompressing ones
return decompressed string
'''
def uncompress_help(S, c):
if S == '':
return ''
if c == '0':
nextC = '1'
elif c == '1':
nextC = '0'
first5 = S[:COMPRESSED_BLOCK_SIZE]
binaryS = binaryToNum(first5) * c
return binaryS + uncompress_help(S[COMPRESSED_BLOCK_SIZE:], nextC)
return uncompress_help(S, '0')
def compression(S):
'''returns compressed size divided by its original size (length)'''
return len(compress(S)) / len(S)
'''
Largest number of bits able to be compressed:
worst case is 1010101010101 need 5 bits for each one so its 5 * 64 = 320
Compression Ratios:
Pictures that have a large amount of the same color in a row can be compressed very well, but pictures who have alternating colors are
difficult.
Professor Lai:
There always needs to be a minimum length string to identify a particular compression in my case it is 5 so even if the string needed to be
compressed is '0' then the returned string will need to be '00001'If there is a picture with less than 5 of a color in a row the compressed version will come out larger.
''' |
5cb988b9ba8bd176aa11f9437dce0d5ebec777f1 | Nalinswarup123/python | /class 7/duplicate in list.py | 235 | 3.875 | 4 | #wap wich reads list of int and return a new list bt eliminating the duplicate
#elements in the list
a=[1,2,5,2,4,1,3,6,6,6]
b=[]
for i in a:
for j in a:
if(i!=j and i not in b):
b.append(i)
print(b)
|
67abd7f38078b2ab9013e13fa458eb165675bfe6 | cavmp/200DaysofCode | /Day116-ColorGame.py | 1,730 | 3.9375 | 4 | import tkinter
import random
colours = ['Red', 'Blue', 'Green', 'Pink', 'Black',
'Yellow', 'Orange', 'White', 'Purple', 'Brown']
score = 0
timeleft = 30
def startGame(event):
if timeleft == 30:
countdown()
nextColour()
def nextColour():
global score
global timeleft
if timeleft > 0:
# makes the text entry box active
e.focus_set()
# if the colour typed matches the colour of the text
if e.get().lower() == colours[1].lower():
score += 1
# clears the text entry box when countdown is over
e.delete(0, tkinter.END)
random.shuffle(colours)
label.config(fg=str(colours[1]), text=str(colours[0]))
# update score
scoreLabel.config(text="Score: " + str(score))
def countdown():
global timeleft
if timeleft > 0:
timeleft -= 1
timeLabel.config(text="Time left: "
+ str(timeleft))
timeLabel.after(1000, countdown)
root = tkinter.Tk()
root.title("Color Game")
root.geometry("475x300")
instructions = tkinter.Label(root, text="\nType in the color"
" of the words!",
font=('Helvetica', 20))
instructions.pack()
scoreLabel = tkinter.Label(root, text="Type 'enter' to start",
font=('Helvetica', 15))
scoreLabel.pack()
timeLabel = tkinter.Label(root, text="\nTime left: " +
str(timeleft), font=('Helvetica', 15))
timeLabel.pack()
label = tkinter.Label(root, font=('Helvetica', 60))
label.pack()
e = tkinter.Entry(root)
root.bind('<Return>', startGame)
e.pack()
e.focus_set()
root.mainloop()
|
1907fb9ce3f2d374767d12baf72a9be27bd5ca92 | WooWooNursat/Python | /lab7/informatics/5/probB.py | 138 | 3.953125 | 4 | a = int(input())
b = int(input())
def power(a,b):
n = a
for i in range(1, b, 1):
n = n * a
return n
print(power(a, b)) |
11db5ce04015059387ed347f3a88d92492aa7d1d | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/cshjam001/question2.py | 165 | 3.90625 | 4 | x = eval(input("Enter the height of the triangle:\n"))
gap=(x-1)
for i in range(0,x*2-1,2):
print(' '*gap,end='')
print('*'*(i+1))
gap=gap-1
|
57e7f970237cd02907c7575587060fca5cbd2938 | mannhb/guessing-game | /guessing_game.py | 1,934 | 4.3125 | 4 | """
Python Web Development Techdegree
Project 1 - Number Guessing Game
--------------------------------
For this first project we will be using Workspaces.
NOTE: If you strongly prefer to work locally on your own computer, you can totally do that by clicking: File -> Download Workspace in the file menu after you fork the snapshot of this workspace.
"""
import random
def start_game():
# write your code inside this function.
print("------------------------------------")
print("Welcome to the Number Guessing Game!")
print("------------------------------------")
answer_number = random.randint(1, 10)
number_of_attempts = []
while True:
try:
number = input("Guess a number from 1 to 10: ")
if int(number) > 10 or int(number) < 1:
print("Please choose a number between 1 and 10. This will count as an attempt. Try again...")
number_of_attempts.append(number)
continue
elif int(number) > answer_number:
print("It's lower")
number_of_attempts.append(number)
continue
elif int(number) < answer_number:
print("It's higher")
number_of_attempts.append(number)
continue
elif int(number) == answer_number:
print("\nYes! You got it!")
number_of_attempts.append(number)
print("It took you {} attempt(s) to guess the correct answer!".format(len(number_of_attempts)))
break
except ValueError:
print("Uh Oh! That is not valid input. This will count as an attempt. Please try again...")
number_of_attempts.append(number)
continue
print("\nThe game has closed. Until next time!")
if __name__ == '__main__':
# Kick off the program by calling the start_game function.
start_game()
|
3d7bee213d74f57e3b7f3c47228afdc1e24e5f11 | AtushiMaeda/python_study | /bs/bs-select.py | 639 | 3.59375 | 4 | from bs4 import BeautifulSoup
# 対象となるHTML
html = """
<html><body>
<div id="maxim">
<h1>トルストイの名言</h1>
<ul class="sentences">
<li>汝の心に教えよ、心に学ぶな</li>
<li>謙虚な人はだれからも好かれる</li>
<li>強い人々は、いつも気取らない</li>
</ul>
</div>
</body></html>
"""
# HTMLを解析
soup = BeautifulSoup(html, 'html.parser')
# タイトル部分を取得
h1 = soup.select_one("div#maxim > h1").string
print("h1 =", h1)
# リスト部分を取得
li_list = soup.select("div#maxim > ul.sentences > li")
for li in li_list:
print("li =", li.string)
|
ad8567b2bbd0002e706a3766c6ac9b4941f2d040 | pradeepshetty1/python-Pandas-and-Numpy- | /Module2/7_example_sequence.py | 641 | 3.640625 | 4 |
l1 = list(range(10))
l2 = list('Edureka')
l3 = [1,2,3,4]
print(l1)
print(l2)
print(l3)
print(l1[3])
print(l2[3])
print(l3[3])
print "=========BREAK1============="
print (l2[-1])
print (l2[-2])
print(l2[2:4])
print(l2[1:-1])
print(l2[1:-1:2])
print "============BREAK2=========="
#print(l2[10])
print(l2[::-1])
print "============BREAK3=========="
#testString = 'malayalam'
testString = 'Test'
if testString == testString[::-1]:
print "We got a palindrome"
else:
print "It is not a palindrome"
print "======================"
testDel = list(range(10))
del testDel[0:3]
print (testDel)
print "======================"
|
502438a513af97ee68441cc575a3af8a003c1d04 | green-fox-academy/FKinga92 | /week-03/day-04/08string2.py | 293 | 4.03125 | 4 | # Given a string, compute recursively a new string where all the 'x' chars have been removed.
def x_remove(string1):
if string1 == "":
return string1
elif string1[0] == "x":
return "" + x_remove(string1[1:])
else:
return string1[0] + x_remove(string1[1:])
|
09e2980e78b9be4371783d44247230c09dc78e58 | ghardoim/seguranca-informacao | /gerawordlist.py | 147 | 3.96875 | 4 | import itertools
string = input("Digite: ")
resultado = itertools.permutations(string, len(string))
for char in resultado:
print("".join(char)) |
bc2620c39fc6077d302977dd2a68583717fd21ff | wszeborowskimateusz/cryptography-exam | /modulo.py | 2,014 | 3.609375 | 4 | import math
from functools import reduce
def count_divisors(a):
result = 0
for b in range(1, a + 1):
result += math.floor(a // b) - math.floor((a - 1) // b)
return result
def fast_pow(a, b):
c = 1
while b > 0:
if b % 2 != 0:
c *= a
a = a ** 2
b = b // 2
return c
def amount_of_bits(a):
if a == 0: return 1
return math.log(math.sqrt(a)) + 1
def sqrt(a, b):
if a == 1 or b == 1: return a
if b > amount_of_bits(a): return 1
l, p = 1, a
while l <= p -2:
s = math.floor((l + p) // 2)
if math.pow(s, b) <= a:
l = s
else:
p = s
return l
def nww(*args):
return reduce(lambda a, b: a * b // math.gcd(a, b), args)
def nwd(*args):
return reduce(lambda a, b: math.gcd(a, b), args)
# |ab| = nwd(a, b) * nww(a, b).
# ϕ(p^n) = p^n − p^(n−1)
# Jeśli liczby naturalne a, b są względnie pierwsze, to
# ϕ(ab) = ϕ(a)ϕ(b).
def euler(a):
result = 0
print(f"Calculating Euler function for {a}")
for i in range(2, a):
print(f"Trying {i}")
if nwd(i, a) == 1:
result += 1
return result
# https://www.alpertron.com.ar/ECM.HTM
def euler2(n):
print(f"Trying to calculate euler for {n}")
# Initialize result as n
result = n;
# Consider all prime factors
# of n and subtract their
# multiples from result
p = 2;
while(p * p <= n):
print(f"Checking some shity n = {n} and p = {p} and p^2 = {p*p}")
# Check if p is a
# prime factor.
if (n % p == 0):
# If yes, then
# update n and result
while (n % p == 0):
n = int(n / p);
result -= int(result / p);
p += 1;
# If n has a prime factor
# greater than sqrt(n)
# (There can be at-most
# one such prime factor)
if (n > 1):
result -= int(result / n);
return result;
|
292b7c6e3c2590565187245b0f661dd032b3713d | karthiklingasamy/Python_Sandbox | /B14_T2_DateTime_TimeDelta.py | 388 | 3.953125 | 4 | import datetime
tday=datetime.date.today() # to get current date
tdelta=datetime.timedelta(days=7)
print(tday+tdelta)
print(tday-tdelta)
# date2 = date1 + timedelta
# timedelta = date1+date2
print('--------------------')
bday=datetime.date(1993,9,13)
till_bday=bday-tday
print(till_bday)
print(till_bday.days)# only days
print(till_bday.total_seconds()) # To get seconds |
40be82bd52f0346646545e6cba10e0421e8a3ebf | czs108/LeetCode-Solutions | /Medium/323. Number of Connected Components in an Undirected Graph/solution (2).py | 1,026 | 3.75 | 4 | # 323. Number of Connected Components in an Undirected Graph
# Runtime: 316 ms, faster than 6.20% of Python3 online submissions for Number of Connected Components in an Undirected Graph.
# Memory Usage: 15.4 MB, less than 90.86% of Python3 online submissions for Number of Connected Components in an Undirected Graph.
class Solution:
# Disjoint Set Union
def __init__(self) -> None:
self._roots: list[int] = None
def countComponents(self, n: int, edges: list[list[int]]) -> int:
self._roots = [-1] * n
for a, b in edges:
self._union(a, b)
count = 0
for i in range(n):
if self._roots[i] < 0:
count += 1
return count
def _find(self, node: int) -> int:
while self._roots[node] >= 0:
node = self._roots[node]
return node
def _union(self, x: int, y: int) -> None:
root_x, root_y = self._find(x), self._find(y)
if root_x != root_y:
self._roots[root_x] = root_y |
47441e3fc76e87ffa2be38a8a35d264ef26941cb | CallMeSnacktime/100DaysofCodeProjects | /Day 29: Password Manager/main.py | 3,113 | 3.921875 | 4 | # Import shuffle, choice and randint methods to use them directly
from random import choice, randint, shuffle
from tkinter import *
from tkinter import messagebox
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
#Password Generator Project
def password():
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
password_list = []
# Randomly select characters in list comprehensions
pass_letters= [choice(letters) for _ in range(randint(8, 10))]
pass_symbols= [choice(symbols) for _ in range(randint(2, 4))]
pass_numbers= [choice(numbers) for _ in range(randint(2, 4))]
#Combine characters and shuffle them
password_list = pass_letters + pass_symbols + pass_numbers
shuffle(password_list)
password = "".join(password_list)
# Alter password field on UI
pass_text.delete(0, END)
pass_text.insert(END, f"{password}")
# ---------------------------- SAVE PASSWORD ------------------------------- #
def save():
site = site_text.get()
user = user_text.get()
password = pass_text.get()
if len(site)==0 or len(user) ==0 or len(password)==0:
messagebox.showinfo(title="Blank Field", message="Please don't leave any fields empty!")
else:
is_ok = messagebox.askokcancel(title=site, message=f"These are the details entered:\n Website: {site}\n Email: {user}\n Password: {password}\n It it ok to save?")
if is_ok:
with open("data.txt", "a") as file:
file.write(f"{site} | {user} | {password}\n")
pass_text.delete(0, END)
site_text.delete(0, END)
messagebox.showinfo(title="Success!!", message="Your credentials were successfully saved!")
# ---------------------------- UI SETUP ------------------------------- #
# Create new window
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(height=200, width=200)
lock_img = PhotoImage(file="logo.png")
canvas.create_image(100,100,image=lock_img)
canvas.grid(column=1, row=0)
# Labels
site_label = Label(text="Website:")
site_label.grid(column=0, row=1)
user_label = Label(text="Email/Username:")
user_label.grid(column=0, row=2)
pass_label = Label(text="Password:")
pass_label.grid(column=0, row=3)
# Entries
site_text = Entry(width=38)
site_text.focus()
site_text.grid(column=1, row=1, columnspan=2)
user_text = Entry(width=38)
user_text.insert(END, "fake@email.com")
user_text.grid(column=1, row=2, columnspan=2)
pass_text = Entry(width=21)
pass_text.grid(column=1, row=3)
# Buttons
add_button = Button(text="Add", width=36, command=save)
add_button.grid(column=1, row=4, columnspan=2)
gen_button = Button(text="Generate", command=password)
gen_button.grid(column=2, row=3,)
window.mainloop() |
38eea2ed68b89f09ce14a8e2f8595d46589af962 | DanielMalheiros/geekuniversity_programacao_em_python_essencial | /Exercicios/secao06_estruturas_de_repeticao/exercicio13.py | 389 | 3.96875 | 4 | """13- Faça um programa que leia um número inteiro positivo par N e imprima todos os números pares
de 0 até N em ordem crescente."""
n = int(input("Digite um número inteiro e positivo: "))
if n > 0:
if n % 2 == 0:
for x in range(n+1):
if x % 2 == 0:
print(x)
else:
print("Número inválido.")
else:
print("Número inválido.") |
6161942f00c7061bf014ebcbcd58f5c31aa5c3b9 | brett-davi5/Python-Numbers-Guessing-Game | /NumbersGuessingGame.py | 4,145 | 4 | 4 |
# coding: utf-8
# In[31]:
import random
def randomNumber():
number = random.randint(1, 100)
return number
# In[32]:
def game():
greeting()
global magicNumber
magicNumber = randomNumber()
global tries
tries = 10
while tries > 0:
userNumber = askForInput()
if(userNumber > magicNumber):
print("Your guess is too high. Try again")
tries = tries - 1
print("Remember, you have %d tries remaining.", tries)
if(tries <= 8):
hints()
elif(userNumber < magicNumber):
print("Your guess is too low. Try again")
tries = tries - 1
print("Remember, you have %d tries remaining.", tries)
else:
print("Congratulations! You guessed the right number!")
print("I'm sorry. You don't have any more tries.")
# In[33]:
def greeting():
print("Welcome to Brett's Guessing Game!")
print("Guess the number between 1 and 100")
print("You'll get 10 tries.")
print("If you don't guess the correct number after two guesses, you"
"can press '0' for a random hint.")
print("You get a maximum of 3 hints so use them wisely!")
print("Each hint costs 2 tries. Be cautious.")
print("Good luck!")
# In[34]:
def askForInput():
userValue = int(input("What is your guess?: "))
if(userValue < 0 or userValue > 100):
print("Please input a valid input")
else:
return userValue
# In[35]:
def hints():
userInput = input("Would you like any hints? [Y / N]")
if(userInput == "Y" or userInput == "y"):
print("Here are your hint options")
print(" 0 - Is the number odd or even?")
print(" 1 - The number is bigger than or equal the square of a number")
print(" 2 - The number is smaller than or equal the square of a number")
print(" 3 - Is the number a multiple of 5?")
print(" 4 - Is the number a multiple of 2?")
print(" 5 - Is the number a multiple of 3?")
hintInput = int(input("Press the number for each hint:"))
if(hintInput == 0):
oddEvenCheck()
if(hintInput == 1):
biggerSquareCheck()
if(hintInput == 2):
smallerSquareCheck()
if(hintInput == 3):
multipleFiveCheck()
if(hintInput == 4):
multipleTwoCheck()
if(hintInput == 5):
multipleThreeCheck()
# In[36]:
def oddEvenCheck():
tries = tries - 2
oddEvenCheckNumber = int(magicNumber % 2)
if(oddEvenCheckNumber == 0):
print("The number is even")
else:
print("The number is odd")
# In[37]:
def biggerSquareCheck():
square = 1
biggerSquare = square * square
while(biggerSquare < magicNumber):
square = square + 1
biggerSquare = square * square
square = square - 1
tries = tries - 2
print("The number is bigger than or equal to the square of the number %d", square)
# In[38]:
def smallerSquareCheck():
square = 10
smallerSquare = square * square
while(magicNumber < smallerSquare):
square = square - 1
smallerSquare = square * square
square = square + 1
tries = tries - 2
print("The number is smaller than or equal to the square of the number %d", square)
# In[39]:
def multipleFiveCheck():
tries = tries - 2
fiveCheck = False
fiveCheckNumber = magicNumber % 5
if(fiveCheckNumber == 0):
fiveCheck = True
print("The number is a multiple of five")
else:
print("The number is not a multiple of five")
# In[40]:
def multipleTwoCheck():
tries = tries - 2
twoCheckNumber = magicNumber % 2
if(twoCheckNumber == 0):
print("Your number is a multiple of two.")
else:
print("Your number is not a multiple of two.")
# In[41]:
def multipleThreeCheck():
tries = tries - 2
threeCheckNumber = magicNumber % 3
if(threeCheckNumber == 0):
print("Your number is a multiple of three.")
else:
print("Your number is not a multiple of three.")
# In[ ]:
game()
# In[ ]:
|
82da9d7705286605cb63bae7a533d9fa8ade39ad | ufukcbicici/phd_work | /tf_experiments/math_experiments.py | 168 | 3.546875 | 4 | import numpy as np
def a(n_, p_):
return 1.0 / (n_ * (np.log(n_)**p_))
sequence = []
p = -3.0
for n in range(2, 1000):
sequence.append(a(n, p))
print("X") |
b9023852a13e64e8a593ad684682a160782502c3 | cljacoby/leetcode | /src/majority-element/majority-element.py | 775 | 3.71875 | 4 | # https://leetcode.com/problems/majority-element
from collections import defaultdict
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
counts = defaultdict(int)
mx = (float('nan'), float('-inf'))
for num in nums:
counts[num] += 1
if counts[num] > mx[1]:
mx = (num, counts[num])
return mx[0]
if __name__ == "__main__":
sol = Solution()
tests = [
([2,2,1,1,1,2,2], 2),
([3,2,3], 3),
]
for (nums, solution) in tests:
result = sol.majorityElement(nums)
assert result == solution, \
f"result {result} != solution {solution}"
print("✅ All tests passed")
|
88ca3d7c6783ea7400c00e840f1a8be383f8d677 | ky822/assignment10 | /ssz225/project/functions.py | 2,115 | 3.984375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
def test_grades(grade_list):
"""Assuming list of grades given already sorted by DESCENDING date order:
Assign A, B, C, to 1, 0, -1 and compare the most recent grade to its past grade.
If the most recent grade has a higher value, the function returns 1;
if the most recent grade is lower, return -1;
if the grades are equal or if there is only one grade, return 0"""
grades_key = ['A','B','C']
values = [1, 0, -1]
d_grades = dict(zip(grades_key, values))
grades_int_list = [d_grades[grade] for grade in grade_list]
#if only 1 item in grade_list, then return 0
if len(grade_list) == 1:
return 0
current_grade = grades_int_list[0]
past_grade = grades_int_list[-1]
#return 1 if improving
if current_grade > past_grade:
return 1
#return -1 if declining
if current_grade < past_grade:
return -1
#return 0 i f stayed the same
if current_grade == past_grade:
return 0
def test_restaurant_grades(camis_id, df):
#for each restaurant examine if grade improves, declines, or stays the same over time
grade_list = []
restaurant_grade = df[df.CAMIS == camis_id].GRADE
for grade in restaurant_grade:
grade_list.append(grade)
test = test_grades(grade_list)
return test
#return 1 if improving, return -1 if declining, return 0 if stayed the same
#
def graph(df, location):
#convert grade date to date time
df['GRADE DATE'] = pd.to_datetime(df['GRADE DATE'])
grouped_df = df.groupby(['GRADE DATE','GRADE']).size().unstack()
plt.figure(figsize = (20,10))
plt.plot(grouped_df.index, grouped_df['A'], label = 'Grade A')
plt.plot(grouped_df.index, grouped_df['B'], label = 'Grade B')
plt.plot(grouped_df.index, grouped_df['C'], label = 'Grade C')
plt.title('Number of Restaurants with Each Grade in {} Over Time'.format(location))
plt.xlabel('Time')
plt.ylabel('Number of Restaurants')
plt.legend(loc = 'upper left')
plt.savefig('grade_improvement_{}.pdf'.format(location)) |
6a94a4a9548b2eacf8b1d534944e3aff89a9cb7a | rutujamalusare/py_vsc | /encode_decode.py | 467 | 4.03125 | 4 | a="h\te\tl\tl\to"
print(a)
print(a.expandtabs(1))
import base64
string= base64.b64encode(bytes("hello I am learning python",'utf-8'))
print(string)
string1= base64.b64decode(string)
print(string1)
string2= input("enter any string")
string2=base64.b64encode(bytes(string2,'utf-8'))
print(string2)
string3= base64.b64decode(string2)
print(string3)
#to remove prefix b which is printed on console.
print(string3.decode('utf-8'))
print(str(string3,'utf-8'))
|
74eb5edfde30fc5a710bd602641299cbf002fe15 | bonicim/technical_interviews_exposed | /src/algorithms/tree_questions/find_max_sum_binary_tree.py | 842 | 4.125 | 4 | """
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
"""
def find_max_sum_binary_tree(root):
def find_max(node):
nonlocal max_sum
if not node:
return 0
left_max = find_max(node.left)
right_max = find_max(node.right)
sum_at_node_as_starting_point = node.data + left_max + right_max
max_sum = max(max_sum, sum_at_node_as_starting_point)
max_at_node = node.data + max(left_max, right_max)
if max_at_node > 0:
return max_at_node
return 0
max_sum = float("-inf")
find_max(root)
return max_sum
|
72012b9cd32a7353ca6c3b0a219f8611542938d2 | jhuang292/leetcode-diary-August-23 | /hamming distance.py | 210 | 3.5 | 4 | class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
o = x ^ y
return sum(1 for i in range(32) if o & 1<<i)
|
7b73a9dde0dccdaf19434419c4ce16387f099588 | hyrdbyrd/ctf-route | /public/tasks-content/code.python.py | 124 | 3.53125 | 4 | def encrypt(text):
key = len(text)
res = []
for i in text:
res.append(ord(i) + (ord(i) % key))
key += 1
return res
|
d2517e2f45ddb7c97aa69d794ea9df63bb4fbdd6 | young31/Algorithm | /백준/10815.py | 351 | 3.609375 | 4 | from collections import defaultdict
def false():
return False
n = int(input())
arr = list(map(int, input().split()))
has = defaultdict(false)
for a in arr:
has[a] = True
m = int(input())
is_has = list(map(int, input().split()))
res = []
for i in is_has:
if has[i]:
res.append(1)
else:
res.append(0)
print(*res)
|
877eec6fc9d15bc5f3243489ceb7a50872342dfc | VladSemiletov/python_algorithms | /Task_4/4_1.py | 1,184 | 3.6875 | 4 | from timeit import timeit
def func_1(nums): # общая сложность - O(N)
new_arr = [] # O(1)
for i in range(len(nums)): # O(N) + O(1)
if nums[i] % 2 == 0: # O(1)
new_arr.append(i) # O(1)
return new_arr # O(1)
def func_2(nums):
new_arr = [i for i in range(len(nums)) if nums[i] % 2 == 0]
return new_arr
my_list = [i for i in range(1000)]
print(f'Time for func_1 is {timeit("func_1(my_list)", globals=globals())} seconds')
print(f'Time for func_2 is {timeit("func_2(my_list)", globals=globals())} seconds')
'''
Time for func_1 is 66.43496044899985 seconds
Time for func_2 is 50.44767693299946 seconds
Вывод: при малом числе элементов списка разница между двумя решениями почти не заметна. Но уже при len(nums) == 1000
видно, что list comprehension работает на 25% быстрее. Дополнительный аргумент в пользу этого решения - код становится
меньше в объеме, более лаконичным и читаемым.
'''
|
4a8300cf8992ec60296a10eb1d21d5179c7e2cc6 | hutor04/UiO | /in4110/assignment4/instapy/python_color2sepia.py | 666 | 3.515625 | 4 | import numpy as np
def python_color2sepia(img):
"""
Applies sepia filter.
Args:
img (numpy.ndarray): vectorized image.
Returns:
numpy.ndarray: vectorized sepia image.
"""
sepia_filter = [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]
height, width, channel = img.shape
sepia_image = np.zeros(shape=img.shape)
for i in range(height):
for j in range(width):
for idx, c in enumerate(sepia_filter):
new_color = sum([x * y for x, y in zip(c, img[i][j])])
sepia_image[i][j][idx] = new_color if new_color < 255 else 255
return sepia_image
|
d66330c6f9bc5b6fb1f77aa71112777435e46b80 | abhishekshetye/competitive | /python/max_network_rank.py | 922 | 3.609375 | 4 | '''
https://leetcode.com/problems/maximal-network-rank/
Store graph in map of set to optimzie the finding. Iterate through vertices and get the maximum rank.
'''
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
if len(roads) == 0:
return 0
graph = {}
for each in roads:
f, s = each[0], each[1]
if f in graph:
graph[f].add(s)
else:
graph[f] = {s}
if s in graph:
graph[s].add(f)
else:
graph[s] = {f}
ans = 0
for i in range(0, n):
for j in range(i + 1, n):
if i in graph and j in graph:
ans = max(ans, len(graph[i]) + len(graph[j]) - 1) if i in graph[j] else max(ans, len(graph[i]) + len(graph[j]))
return ans |
b896828b795f7e60af39e46d83f85b876747d7f4 | BhumikaReddy/3GRM | /Programming/Python/string1.py | 248 | 4 | 4 |
import string
a="the quick brown fox jumps over the lazy dog"
print(set(a))
b=list(string.ascii_lowercase)
print(set(b))
x=set(b)-set(a)
print(x)
if not x:
print("panagram")
else:
print("no")
#program to check whether a string is panagram or no
|
93b1481ff9af3956d4c341b08630d363a02dc19a | broepke/GTx | /part_3/4.5.11_reader.py | 2,580 | 4.21875 | 4 | # Recall in coding problem 4.4.3 that you wrote a function
# called "reader" that read a .cs1301 file and returned a
# list of lists.
#
# Let's revise that problem. Instead of a list of lists,
# that's return a dictionary of dictionaries.
#
# Write a function called "reader" that takes one parameter,
# a filename as a string corresponding to a .cs1301 file,
# and reads in that .cs1301 file.
#
# Each line of the .cs1301 file will have five items, each
# separated by a space: the first, third, and fourth will
# represent integers, the second will be a string, and the
# fifth will represent a float. (Note: when reading the
# file, these will all be strings; you can assume each of
# these strings can be converted to the corresponding data
# type, however.)
#
# The function should return a dictionary of dictionaries
# representing the file contents.
#
# The keys of the top-level dictionary should be the
# assignment names. Then, the value for each of those keys
# should be a dictionary with four keys: "number", "grade",
# "total", and "weight". The values corresponding to each of
# those four keys should be the values from the file,
# converted to the corresponding data types (ints or floats).
#
# For example, if the input file read:
#
# 1 exam_1 90 100 0.6
# 2 exam_2 95 100 0.4
#
# Then reader would return this dictionary of dictionaries:
#
# {"exam_1": {"number": 1, "grade": 90, "total": 100, "weight": 0.6},
# "exam_2": {"number": 2, "grade": 95, "total": 100, "weight": 0.4}}
#
# Hint: Although the end result is pretty different, this
# should only dictate a minor change to your original
# Problem 4.4.3 code!
# Write your function here!
def reader(file_name):
file_name = open(file_name, "r")
exam_dict = {}
line_dict = {}
for line in file_name:
line_list = line.split()
line_dict = {"number": int(line_list[0]), "grade": int(line_list[2]), "total": int(line_list[3]),
"weight": float(line_list[4])}
exam_dict[line_list[1]] = line_dict
file_name.close()
return exam_dict
# Below are some lines of code that will test your function.
# You can change the value of the variable(s) to test your
# function with different inputs.
#
# If your function works correctly, this will originally
# print (although the order of the keys may vary):
# {'assignment_1': {'total': 100, 'number': 1, 'grade': 85, 'weight': 0.25}, 'test_1': {'total': 100, 'number': 2, 'grade': 90, 'weight': 0.25}, 'exam_1': {'total': 100, 'number': 3, 'grade': 95, 'weight': 0.5}}
print(reader("sample.cs1301"))
|
ddd1e4686f67c0d1f78c5fac5e80d6ef7ed48801 | comojin1994/Algorithm_Study | /Uijeong/Python/Math2/1929.py | 392 | 3.75 | 4 | import sys
import math
input = sys.stdin.readline
def isPrime(number):
if number == 1: return False
sqrtN = math.floor(math.sqrt(number))
for j in range(2, sqrtN + 1):
if number % j == 0:
return False
return True
if __name__ == "__main__":
m, n = map(int, input().split())
for i in range(m, n + 1):
if isPrime(i):
print(i) |
2fe40dc6ca95a8805721d971074896c7d1a71b9e | PanPapag/A-Complete-Python-Guide-For-Beginners | /Functions_Files_and_Dictionaries/Functions_and_Tuples/Local_and_Global_variables/func_mutability.py | 266 | 3.6875 | 4 | def double(y):
y = 2 * y
def changeit(lst):
lst[0] = "New one"
y = 5
print("Initial y: ",y)
double(y)
print("Doubled y: ",y)
mylist = ["lets", "see", "what", "will", "change"]
print("Initial list: ",mylist)
changeit(mylist)
print("Changed list: ",mylist)
|
c57d75dd1d8b6c81cbea303908b19efbbdb7c5a1 | mattyoungberg/Notebook | /Notebook/note_utils.py | 1,340 | 4.15625 | 4 | import datetime
class Note:
"""
Container class for the notes instantiated by the user.
Attributes:
identifier:int -- unique identifier of the note
memo:string -- the actual content of the note
tags:list<string> -- tags for easy searching
creation_date:datetime.datetime -- date and time at which the note was created
"""
def __init__(self, identifier, tags, memo, creation_date=None):
self.identifier = identifier
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today() if creation_date is None else creation_date
self.path = None
self._write_note_file()
def _write_note_file(self):
"""Writes a note to a text file in a format that is easily parsed."""
payload = '\n'.join([str(self.identifier),
self.creation_date.strftime('%m/%d/%Y'),
', '.join(self.tags),
self.memo])
self.path = 'notes\\note_{}.txt'.format(self.identifier)
with open(self.path, 'w') as f:
f.write(payload)
def _match(self, param):
"""Determines is the string 'param' could be referring to any content within the note"""
pass
if __name__ == '__main__':
Note('Test note.', ['test'])
|
85ed0f8b501e9aa153b04b8287b3e4592e397fe5 | AngelosGeorgiou/PythonProjects | /ValidParenteses.py | 437 | 4.40625 | 4 | #Write a function called that takes a string of parentheses, and determines if
#the order of the parentheses is valid. The function should return true if the
#string is valid, and false if it's invalid.
def valid_parentheses(string):
total = 0
for letter in string:
if letter=='(':
total+=1
elif letter == ')':
total-=1
if total < 0:
return False
return total == 0 |
0911b1c6097e3d8c5ccf2519375fd31410d407fe | AdamZhouSE/pythonHomework | /Code/CodeRecords/2776/60594/289021.py | 1,007 | 3.640625 | 4 | def findAllConcatenatedWordsInADict(words):
def check_word(word, pre_dict):
if len(word) == 0:
return True
cur_dict = pre_dict
for index, c in enumerate(word):
cur_dict = cur_dict.get(c, None)
if cur_dict is None:
return False
if cur_dict.get('end', 0) == 1:
if check_word(word[index + 1:], pre_dict):
return True
return False
words.sort(key=lambda x: len(x))
ans = []
pre_dict = {}
for item in words:
if len(item) == 0:
continue
if check_word(item, pre_dict):
ans.append(item)
else:
# insert word
cur_dict = pre_dict
for c in item:
if cur_dict.get(c, None) is None:
cur_dict[c] = {}
cur_dict = cur_dict.get(c)
cur_dict['end'] = 1
return ans
oc=eval(input())
print(findAllConcatenatedWordsInADict(oc)) |
6e5dbd8ed889fa7f46828de030133acc5342d286 | danmohler/File-Sort | /FileSort.py | 6,493 | 4.1875 | 4 | # Author: Dan Mohler
# FileSort.py A program to sort files using account numbers
# Last modified 10/14/2021
# Python Version Python 3.7.4
# Application Notes
# Parameters are specified in the following order:
# fileDir, folderDir, optional parameters
# fileDir is the location of directory that contains files to be copied
# folderDir is the location of directory that contains subfolders to copy files
# -d is a flag that specifies debug mode
# file format
# "YYYY-MM-DD Name ACCOUNT_NUMBER"
import sys, argparse, sqlite3, shutil, os
class FileSort:
def __init__(self, year, folderDir, fileDir):
self.year = year
self.folderDir = folderDir
self.fileDir = fileDir
# set length of account numbers
self.ACCOUNT_LENGTH = 3
self.FILE_END_LENGTH = self.ACCOUNT_LENGTH + 1
# Minimum file length requires character, space, and account
self.MIN_FILE_LENGTH = self.ACCOUNT_LENGTH + 2
# Number of digits used to specify year
self.YEAR_LENGTH = 4
# Create dictionary to store file structure of disk
self.fileDB = {}
self.totalFiles = 0
self.ignoredFiles = 0
self.totalFolders = 0
self.accountFolders = 0
if not (self.InputValidation()):
sys.exit("Input validation failed")
def InputValidation(self):
# verify that directory exists to be parsed
if not (os.path.isdir(self.folderDir)):
print(f"{self.folderDir} is not a valid file directory.")
return False
# Verify that year is a number
if not self.year.isnumeric():
print(f"{self.year} is not a valid year.")
return False
return True
def ValidateAccountDir(self, basename):
# Function validates that output directory basename has proper
# formatting to match a year and an account
# Returns True if a valid output directory basename
# Returns False if not a a valid output directory basename
# verify that directory is sufficiently long
# and has proper "...Name ACCOUNT_NUMBER" end formatting
if (len(basename) < self.MIN_FILE_LENGTH):
return False
elif (basename[-self.FILE_END_LENGTH] != ' '):
return False
elif not (basename[-self.ACCOUNT_LENGTH:].isnumeric()):
return False
# Add folder if the year matches
if (basename[:self.YEAR_LENGTH] == self.year):
return True
# Add folder if it has no year
elif not (basename[:self.YEAR_LENGTH].isnumeric()):
return True
else:
return False
def ParseDir(self, directory=None):
# This function performs directory parsing
if directory is None:
directory = self.folderDir
endDir = os.path.basename(directory)
self.totalFolders += 1
if self.ValidateAccountDir(endDir):
numbers = endDir[-self.ACCOUNT_LENGTH:]
self.fileDB[numbers] = {
'full_directory': directory,
'basename': endDir
}
self.accountFolders += 1
# For every subdirectory (next sublevel), call function with new path
for item in os.listdir(directory):
nextDir = os.path.join(directory, item)
if os.path.isdir(nextDir):
self.ParseDir(nextDir)
return;
def FileValidate(self, directory, filename):
# Check if the file exists
if not os.path.isfile(os.path.join(directory, filename)):
return False
filenameNoExt = os.path.splitext(filename)[0]
if (len(filenameNoExt) < self.MIN_FILE_LENGTH):
return False
elif filenameNoExt[-self.FILE_END_LENGTH:-self.ACCOUNT_LENGTH] != ' ':
return False
accountNumber = filenameNoExt[-self.ACCOUNT_LENGTH:]
if not (accountNumber.isnumeric()):
return False
elif not (accountNumber in self.fileDB):
return False
# if file has year, require match, if not place in current year
if (filenameNoExt[:self.YEAR_LENGTH] == self.year):
return True
elif not (filenameNoExt[:self.YEAR_LENGTH].isnumeric()):
return True
else:
return False
def Deduplicate(self, filepath, filename):
i = 2
newFn = filename
fnNoExt = os.path.splitext(filename)[0]
ext = os.path.splitext(filename)[1]
fnNoAccount = fnNoExt[:-self.FILE_END_LENGTH]
fileEnd = fnNoExt[-self.FILE_END_LENGTH:]
# Check for existing file
while os.path.isfile(os.path.join(filepath, newFn)):
newFn = fnNoAccount + '-' + str(i) + fileEnd + ext
i += 1
return newFn
def FileMove(self):
# perform file move for each file in the filing directory
for filename in os.listdir(self.fileDir):
self.totalFiles += 1
if self.FileValidate(self.fileDir, filename):
fnNoExt = os.path.splitext(filename)[0]
fnAccount = fnNoExt[-self.ACCOUNT_LENGTH:]
# Get directory for file
destPath = self.fileDB[fnAccount]['full_directory']
destFilename = self.Deduplicate(destPath, filename)
shutil.move(os.path.join(self.fileDir, filename), os.path.join(destPath, destFilename))
else:
self.ignoredFiles += 1
if __name__ == '__main__':
# parser initialization
parser = argparse.ArgumentParser(
description = "Sorts files into folders based on account numbers."
)
# parameter specification
parser.add_argument('fileDir', help = "Directory of files to copy")
parser.add_argument('folderDir', help = "Directory to copy files to subfolders")
parser.add_argument('year', help = "Year to copy files")
# argument parsing
args = parser.parse_args()
print(f'Year:{args.year} Folder:{args.folderDir} File:{args.fileDir}')
filer = FileSort(args.year, args.folderDir, args.fileDir)
filer.ParseDir()
filer.FileMove()
print(f'{filer.accountFolders} account folders were found out of {filer.totalFolders} folders in directory.')
print(f'{filer.totalFiles-filer.ignoredFiles} of {filer.totalFiles} files were moved.')
print(f'{filer.ignoredFiles} files were ignored.')
|
72ab58328290a15315fbae6db97d8a01b8ea9688 | pengnam/DailyCodingProblemSolutions | /Problem24-BinaryTreeLocking.py | 1,549 | 4.125 | 4 | """
Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked.
Design a binary tree node class with the following methods:
is_locked, which returns whether the node is locked
lock, which attempts to lock the node. If it cannot be locked, then it should return false. Otherwise, it should lock it and return true.
unlock, which unlocks the node. If it cannot be unlocked, then it should return false. Otherwise, it should unlock it and return true.
"""
class BinaryTreeNode:
def __init__(self):
self.left = None
self.right = None
self.parent = None
self.locked = False
def checkAncestorsHaveLock(self):
curr = self.parent
while curr:
if curr.locked:
return True
return False
def checkDecendentsHaveLock(self):
#Should just use or
result = False
if not left:
result = self.left.checkDescendentsHaveLock()
if not result and not right:
result = self.right.checkDescdentsHaveLock()
return result
def lock(self):
if self.lock or self.checkAncestorsHaveLock()or self.checkDescendentsHaveLock():
return False
else:
self.lock = True
return True
def unlock(self):
if self.lock or self.checkAncestorsHaveLock()or self.checkDescendentsHaveLock():
return False
else:
self.lock = False
return True
|
0317cf338c2e03c6061a1a08273742e8ff43d234 | dahlan77/Pacman-Test-Dahlan | /pacman_test_dahlan.py | 3,817 | 3.625 | 4 | import csv
import math
import numpy as np
from matplotlib import pyplot as plt
import random
import pandas as pd
def loadcsvdataset(filename):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
headers = dataset[0]
dataset = dataset[1: len(dataset)]
return dataset, headers
dataset, headers = loadcsvdataset('advertising.csv')
print("Data Advertise")
print(headers)
print(dataset)
print("Dataset Size")
print(len(dataset), "X", len(dataset[0]))
dataset = np.array(dataset)
dataset = dataset.astype(float)
X = dataset[:,0:-3]
#taking columns with index 2 to 6 as features in X
Y = dataset[:, -1]
#taking the last column i.e. 'price per unit area' as target
one = np.ones((len(X),1))
X = np.append(one, X, axis=1)
#reshape Y to a column vector
Y = np.array(Y).reshape((len(Y),1))
print(X.shape)
print(Y.shape)
def train_test_split(X, Y, split):
#randomly assigning split% rows to training set and rest to test set
indices = np.array(range(len(X)))
train_size = round(split * len(X))
random.shuffle(indices)
train_indices = indices[0:train_size]
test_indices = indices[train_size:len(X)]
X_train = X[train_indices, :]
X_test = X[test_indices, :]
Y_train = Y[train_indices, :]
Y_test = Y[test_indices, :]
return X_train,Y_train, X_test, Y_test
split = 0.8
X_train, Y_train, X_test, Y_test = train_test_split(X, Y, split)
print ("TRAINING SET")
print("X_train.shape: ", X_train.shape)
print("Y_train.shape: ", Y_train.shape)
print("TESTING SET")
print("X_test.shape: ", X_test.shape)
print("Y_test.shape: ", Y_test.shape)
def normal_equation(X, Y):
beta = np.dot((np.linalg.inv(np.dot(X.T,X))), np.dot(X.T,Y))
return beta
def predict(X_test, beta):
return np.dot(X_test, beta)
beta = normal_equation(X_train, Y_train)
predictions = predict(X_test, beta)
print(predictions.shape)
def metrics(predictions, Y_test):
#calculating mean absolute error
mae = np.mean(np.abs(predictions-Y_test))
#calculating root mean square error
mse = np.square(np.subtract(Y_test,predictions)).mean()
rmse = math.sqrt(mse)
#calculating r_square
rss = np.sum(np.square((Y_test- predictions)))
mean = np.mean(Y_test)
sst = np.sum(np.square(Y_test-mean))
r_square = 1 - (rss/sst)
return mae, rmse, r_square
mae, rmse, r_square = metrics(predictions, Y_test)
print("Mean Absolute Error: ", mae)
print("Root Mean Square Error: ", rmse)
print("R square: ", r_square)
#GRADIENT DESCENT#
theta = np.zeros((2, 1))
m=200
def cost_function(X, Y, theta):
y_pred = np.dot(X, theta)
sqrd_error = (y_pred - Y) ** 2
cost = 1 / (2 * m) * np.sum(sqrd_error)
return cost
cost_function(X, Y, theta)
def gradient_descent(X, Y, theta, alpha, iter):
costs = []
for i in range(iter):
y_pred = np.dot(X, theta)
der = np.dot(X.transpose(), (y_pred - Y)) / m
theta -= alpha * der
costs.append(cost_function(X, Y, theta))
return theta, costs
theta, costs = gradient_descent(X, Y, theta, alpha=0.000038, iter=4000000)
print("theta = ",theta)
print("cost = ",costs[-1])
y_pred = np.dot(X, np.round(theta, 3))
dic = {'Sales (Actual)': Y.flatten(),
'Sales (Predicted)': np.round(y_pred, 1).flatten()}
df1 = pd.DataFrame(dic)
print(df1)
def predict(tv_ads):
X = np.array([1, tv_ads]).reshape(1, 2)
y_pred = np.dot(X, theta)
return y_pred[0, 0]
print(predict(220))
R_squared_gradient = 0.9 ** 2
MSE_gradient = ((Y - y_pred) ** 2).sum() / m
RMSE_gradient = np.sqrt(MSE_gradient)
print('R^2 Gradient: ', np.round(R_squared_gradient, 2))
print('RMSE Gradient: ', np.round(RMSE_gradient, 2))
print('MSE Gradient: ', np.round(MSE_gradient, 2)) |
d2997fd2c08bb747181e6f9eb6d9a7ddb5d7c7b3 | rubinshteyn89/Class_Spring | /Python/Lab_6/question2.py | 478 | 3.84375 | 4 | __author__ = 'ilya_rubinshteyn'
def question2():
n = 1
while n != 0:
n = eval(input("What range of numbers would you like to add? "))
if n < 0 or type(n) == float:
print("Invalid input")
continue
elif n > 0:
sum_of_n = n*(n+1)/2
print("The sum of the number range you selected is ",sum_of_n)
continue
elif n == 0:
break
if __name__ == '__main__':
question2() |
55a869884376329277c0ba158040ebace7c5c0e8 | deesaw/PythonD-005 | /Revise/11.py | 1,537 | 4.15625 | 4 | #-------------------------------------------------------------------------------
# Define a new function that simply print's out "Game Over!"...
#-------------------------------------------------------------------------------
def printIt():
print( "I am already good at Python!" )
# Now, lets call our new function...
printIt();
#simple function with single argument
def double1(num):
print (num+num)
double1(5)
#function with single argument and a default value
def double1(num=2):
print (num+num)
double1(5)
double1()
# function with multiple arguments
def sum(a=1,b=3):
print (a+b)
sum()
sum(3,5)
# function with multiple arguments of different types
# can you make this function work.
def wish(name,age):
print ("Hello, " + name + " you are " + age + " old")
#wish(India,65)
# function returning a value
# function returning multiple values
def average( numberList ):
numCount = 0
runningTotal = 0
for n in numberList:
numCount = numCount + 1
runningTotal = runningTotal + n
# Return the average and the number count
return runningTotal / numCount, numCount
# Test the average() function...
myNumbers = [5.0, 7.0, 8.0, 2.0]
theAverage, numberCount = average( myNumbers )
print( "The average of the list is " + str( theAverage ) + "." )
print( "The list contained " + str( numberCount ) + " numbers." )
# what if you don't know the order of the arguments
wish(age=65,name="India")
#this is called calling a function by keyword arguments
|
54af2a9a31e390ed35f054e1c74f6b74e0839821 | ParulProgrammingHub/assignment-1-AlfaizKhan | /python 1 (5).py | 152 | 3.859375 | 4 | days=int(input('enter no. of days'))
year=days/360
a=days%360
b=a//30
c=a%30
print 'no. of year=',year
print 'no. of months =',b
print 'no. of days=',c
|
3ef6c462b7d0a74903a2b78e1fb1e568b0784d85 | 2XL/Python4Everyone | /orientacionaobjetos/herenciamultiple.py | 434 | 3.609375 | 4 | class Terrestre:
def desplazar(self):
print "El animal anda"
class Acuatico:
def desplazar(self):
print "el animal nada"
# HERENCIA MULTIPLE
""" EN PYTHON A DIFERENCIA DE LOS OTROS LENGUAJES COMO JAVA O C... """
# de las uqe hereda separados por comas:
class Cocodrilo(Terrestre, Acuatico):
pass
c=Cocodrilo()
c.desplazar() # terrestre se encuentra mas a la izquierda por lo tanto se imprimira andar
|
60e2bd6949f95734302f3077df978b6cb662619f | userwithoutcode/HOMEWORKS | /hw2.1/homework_2.1.py | 1,712 | 3.8125 | 4 |
def get_file():
with open('homework_2.1.txt') as f:
cook_book = {}
for line in f:
dish_name = line.upper().strip()
contains = []
for i in range(int(f.readline())):
ingredient = f.readline().split("|")
ing_list = list(map(str.strip, ingredient))
contains.append({'ingridient_name': ing_list[0], 'quantity': int(ing_list[1]), 'measure': ing_list[2]})
cook_book[dish_name] = contains
f.readline()
return cook_book
def get_shop_list_by_dishes(cook_book, dishes, person_count):
# cook_book = get_file()
shop_list = {}
for dish in dishes:
for ingridient in cook_book[dish]:
new_shop_list_item = dict(ingridient)
new_shop_list_item['quantity'] *= person_count
if new_shop_list_item['ingridient_name'] not in shop_list:
shop_list[new_shop_list_item['ingridient_name']] = new_shop_list_item
else:
shop_list[new_shop_list_item['ingridient_name']]['quantity'] += new_shop_list_item['quantity']
return shop_list
def print_shop_list(shop_list):
# for shop_list_item in shop_list.values():
# print('{} {} {}'.format(shop_list_item['ingridient_name'], shop_list_item['quantity'], shop_list_item['measure']))
for shop_list_item in shop_list.values():
print('{ingridient_name} {quantity} {measure}'.format(**shop_list_item))
def create_shop_list():
cook_book = get_file()
dishes = input('Введите блюда в расчете на одного человека').upper().split(', ')
person_count = int(input('Введите количество человек'))
shop_list = get_shop_list_by_dishes(cook_book, dishes, person_count)
print_shop_list(shop_list)
create_shop_list()
|
aa01f663a9cb23c5e6a25eadfc5508cda20f116c | PrachiNayak89/Prachi-rampUp | /passwordGenerator.py | 711 | 4.15625 | 4 | #!/usr/bin/python
import random
import string
#This program will generate the strong password
def passwordGenerator(size):
char=string.ascii_uppercase+string.ascii_lowercase+string.digits+string.punctuation
generatedPw=(''.join((random.choice(char) for x in range(size))))
print 'Generated password :', generatedPw
return generatedPw;
userInput=None
while userInput!="exit":
try:
userInput=raw_input('Enter length of the password to be generated :')
if userInput=='exit':
break
userInput=int(userInput)
passwordGenerator(userInput) #calling the funcion
except ValueError:
print 'Please enter valid input!'
|
7243fbe58f8c3ce007a1e547c284767fcfa69db8 | evanwangxx/leetcode | /python/70_Climbing_Stairs.py | 378 | 3.765625 | 4 | # 70. Climbing Stairs
def climbStairs(n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
elif n == 2:
return 2
else:
r = list(range(n))
r[0] = 1
r[1] = 2
for i in range(2, n):
r[i] = r[i-2] + r[i-1]
return r[n-1]
for i in range(1, 10):
print(i, ": ", climbStairs(i))
|
547b5245b031f74864ec8d8f93e26d88f73b8909 | KellianT/Transport_TAM | /tam2.py | 7,768 | 3.75 | 4 | import sqlite3
import argparse
import sys
import urllib.request
from time import *
import logging
logging.basicConfig(
filename='tam.log',
level=logging.INFO,
format='%(asctime)s %(levelname)s - %(message)s',
datefmt='%d/%m/%Y %H:%M:%S',)
logging.info('Demarrage du programe')
def clear_rows(cursor):
""" This function does : Delete lines in table 'infoarret' for refresh
the line in the column before update.
cursor : Cursor is the bridge that connects Python and SQlite databases
and works under SQLite3 built-in package and It will be use to execute SQL
commands. It acts like a position indicator and will be mostly use to
retrieve data.
"""
cursor.execute("""DELETE FROM infoarret""")
logging.info('clear_rows: Efface les lignes dans la table')
def insert_csv_row(csv_row, cursor):
""" This function insert values in table 'infoarret'
cursor : Acts like a position indicator and will be use to
retrieve data.
csv_row : retrieve the lines on the csv file.
"""
cursor.execute("""INSERT INTO infoarret VALUES (?,?,?,?,?,?,?,?,?,?,?) """,
csv_row.strip().split(";"))
def load_csv(path, cursor):
""" This function load and read the csv file, and insert row in db file.
cursor : Acts like a position indicator and will be use to
retrieve data.
path : Source of the csv file.
"""
with open(path, "r") as f:
# ignore the header
f.readline()
line = f.readline()
# loop over the lines in the file
while line:
insert_csv_row(line, cursor)
line = f.readline()
logging.info('load_csv: Charge la base de données')
def remove_table(cursor):
"""This function remove table 'infoarret' if exist
for remove before update
cursor : Acts like a position indicator and will be use to
retrieve data.
"""
cursor.execute("""DROP TABLE IF EXISTS infoarret""")
logging.info('remove_table: la table est supprime')
def create_schema(cursor):
""" This function create table 'infoarret' if not exist
this table contains 11 columns and determinate the type.
cursor : Acts like a position indicator and will be use to
retrieve data.
"""
cursor.execute("""CREATE TABLE IF NOT EXISTS "infoarret" (
"course" INTEGER,
"stop_code" TEXT,
"stop_id" INTEGER,
"stop_name" TEXT,
"route_short_name" TEXT,
"trip_headsign" TEXT,
"direction_id" INTEGER,
"is_theorical" INTEGER,
"departure_time" TEXT,
"delay_sec" INTEGER,
"dest_arr_code" INTEGER
);""")
logging.info('create_schema: on cree les colonnes de la base')
def temps_arrive(horaire):
"""This function return time (sec) to time (min,sec)"""
logging.info("temps_arrive: Conversion du temps d'attente")
return strftime('%M min %S sec', gmtime(horaire))
def time_tram(database, cursor):
""" This function configure the argument time
request the database for recuperate the line in the column
(stop_name , trip_headsign and route_short_name) and return the request
cursor : Acts like a position indicator and will be use to
retrieve data.
database : Search in the connected SQlite database
"""
cursor.execute("""
SELECT * FROM infoarret
WHERE stop_name = ? AND trip_headsign = ? AND route_short_name = ?
""", (args.station, args.destination, args.ligne))
for row in cursor:
if args.fichier:
time_passage = str(f'Prochain passage de la ligne {row[4]} passant à {row[3]} vers {row[5]} départ dans : {temps_arrive(row[9])}\n')
with open("passage.txt", "a", encoding='utf8') as f:
f.writelines(time_passage)
else:
print(f'Prochain passage de la ligne {row[4]} passant à {row[3]} vers {row[5]} départ dans : {temps_arrive(row[9])}')
logging.info("time_tram: Affichage de la demande de l'utilisateur(argument time) ")
def next_tram(database, cursor):
"""The function configure the argument next
Request the database for recuperate line in the column stop_name
delay_sec and route_short_name.
Then it returns the next passes in min,sec, the line and the direction.
cursor : Acts like a position indicator and will be use to
retrieve data.
database : Search in the SQlite database.
"""
cursor.execute("""
SELECT * FROM infoarret
WHERE stop_name = ?
""", (args.station, ))
for row in cursor:
if args.fichier:
passage = str(f'Ligne {row[4]} vers {row [5]} départ dans : {temps_arrive(row[9])}\n')
with open("passage.txt", "a", encoding='utf8') as f:
f.writelines(str(passage))
else:
print(f'Ligne {row[4]} vers {row [5]} départ dans : {temps_arrive(row[9])}')
logging.info("next_tram: Affichage de la demande de l'utilisateur(argument next) ")
def update_db():
"""This function, retrieve the csv from url and download this csv file
"""
csv_url = 'https://data.montpellier3m.fr/sites/default/files/ressources/TAM_MMM_TpsReel.csv'
urllib.request.urlretrieve(csv_url, 'tam.csv')
logging.info('update_db: Mise a jour de la base de données')
parser = argparse.ArgumentParser("Script to interact with data from TAM API")
parser.add_argument("-l", "--ligne", type=str, help="entre ligne de tram")
parser.add_argument("-d", "--destination", type=str, help="entre destination")
parser.add_argument("-s", "--station", type=str, help="entre une station")
parser.add_argument("-c", "--currentdb", type=str, help="Use existing db")
parser.add_argument("action", nargs='?', help="next tram or time tram")
parser.add_argument("-f", "--fichier", action='store_true', help="create file")
args = parser.parse_args()
def main():
""" This function, is the MAIN function :
This function will check if the argument next or time has been entered by
the user:
If one of the two arguments was entered the program will continue and
display the results to the user.
If neither of the two arguments was entered by the user the program will
display an error message and close.
"""
logging.info('Demarrage de la fonction main')
if not args.action:
print("Error : il manque un argument action ('time' ou 'next')")
logging.warning('il manque un argument action')
return 1
if args.action == 'time':
if not args.station or not args.ligne or not args.destination:
print("Error: il manque la ligne et/ou la station et/ou la destination dans les arguments")
logging.warning('il manque la ligne et/ou la station et/ou la destination dans les arguments')
return 1
if args.action == 'next':
if not args.station:
print("Error: il manque la station dans les arguments")
logging.warning('il manque la station dans les arguments')
return 1
conn = sqlite3.connect('tam.db')
if not conn: # si format ne convient pas, si la base est corrompue...etc
print("Error : could not connect to database ")
logging.warning('impossible de se connecter à la base de données')
return 1
c = conn.cursor()
remove_table(c)
if args.currentdb:
create_schema(c)
load_csv(args.currentdb, c)
else:
update_db()
dl = 'tam.csv'
remove_table(c)
create_schema(c)
load_csv(dl, c)
if args.action == 'time':
time_tram('tam.db', c)
elif args.action == 'next':
next_tram('tam.db', c)
conn.commit()
conn.close()
logging.info('Programme fini !!!!!')
if __name__ == "__main__":
sys.exit(main())
|
66439ad629700d7baf8482321abe6344d0102219 | Sangita-Paul/substraction-using-2-s-compliment-python3- | /code1.py | 2,380 | 3.578125 | 4 | global jan
def hii():
new=list(b)
new[0]="1"
''.join(new)
print('-a')
print(new)
indexes = [index for index in range(len(new)) if new[index] == '1']
#print(indexes)
q=max(indexes)
#print(q)
i=1
for i in range(i,q):
if new[i]=='0':
new[i]='1'
else:
new[i]='0'
#print(new)
list1=new
str1=''.join(list1)
print("2's compliment of second number is:")
print(str1)
print('subtraction of 2 numbers is:')
c = bin(int(y,2) + int(str1,2))
#print(c)
yes=list(c)
#print(yes)
if c[2]=='1'and len(c)==19:
print('answer is POSITIVE number')
# print(yes)
ans=print(yes[3:])
else:
print('answer is NEGATIVE number')
indexes = [index for index in range(len(yes)) if yes[index] == '1']
#print(indexes)
me=max(indexes)# greatest number
#print(me)
j=2
for j in range(j,me):
if yes[j]=='0':
yes[j]='1'
else:
yes[j]='0'
ans=print(yes[2:])
print(ans)
print('answer in interger is:')
print(jan)
print('postive numbers are valid upto 32768')
x=int(input('enter the 1st number'))
a=int(input('enter the 2st number'))
jan=int(x)-int(a)
if (x>0) and (a>0):
print('number are positive')
y=bin(x)[2:].zfill(16)
print('x in binary is')
print(y)
b=bin(a)[2:].zfill(16)
print('a in binary is')
print(b)
hii()
elif (x>0) and (a<0):
print('2nd number is is negative')
print('plz enter postive number')
elif (x<0) and (a>0):
print('1st number is is negative')
print('plz enter postive number')
elif (x<0) and (a>0):
print('1st number is is negative')
print('plz enter postive number')
elif (x<0) and (a<0):
print('both number are negative')
print('plz enter postive number')
|
45ef956f03a8f532582877af71ecfaf185d5d001 | changjustin217/cmq | /Queue.py | 1,241 | 3.71875 | 4 | class Node(object):
def __init__(self, name, andrewID):
self.name = name
self.andrewID = andrewID
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return isinstance(other, Node) and self.name == other.name
def __repr__(self):
return self.name
class Queue(object):
def __init__(self, name, descriptions, location, index, category, course = None, coursenum = None):
self.name = name
self.descriptions = descriptions
self.location = location
self.course = course
self.coursenum = coursenum
self.list = []
self.index = index
self.category = category
def enq(self, person, index=None):
if (index == None):
self.list.append(person)
else:
if (index >= 0 and index <= len(list)):
self.list.insert(index, person)
def deq(self, person=None):
if (person == None):
self.list = self.list[1:]
if person in self.list:
self.list.remove(person)
def size(self):
return len(self.list)
def getQueueList(self):
return self.list
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return isinstance(other, Queue) and self.name == other.name
def __repr__(self):
return "Queue(" + self.name + ", " + str(self.list) + ")" |
323ae1f499dc0bbc7fbf4c00379151cf1da4ee88 | Jacob-Eckroth-School/362-InClassGit | /divisor.py | 436 | 4.03125 | 4 |
def divisors(num):
divisorsList = []
for i in range(num,0,-1):
if(num%i == 0):
divisorsList.append(i)
print(divisorsList)
def getUserInput():
userInput = input("Please enter a positive integer:")
while(not userInput.isdigit()):
print("Incorrect input, please enter a integer >=0")
userInput = input("Please enter a positive integer:")
divisors(int(userInput))
getUserInput() |
d8d3ade8bb8e90a44230e709f177a33328595192 | JoseCaarlos/Python | /Seção 09 - Comprehensions/list_comprehension_pt1.py | 1,393 | 4.5625 | 5 | """
List Comprehension
- Utilizando List Comprehension nos podemos gerar novas listas com dados processaos a partir de
de outro iteravel
# Sintaxe da List Comprehension
[ dado for dado in iterável ]
# Exemplos
numeros = [1, 2, 3, 4, 5]
resp = [numero * 10 for numero in numeros]
print(resp)
res = [numero / 2 for numero in numeros]
print(res)
Para entender o que está acontecendo devemos dividir a expressão em duas partes:
- A primeira parte: for numero in numeros
- A segunda parte: numero * 10
numeros = [1, 2, 3, 4, 5]
def potencia(numero):
return numero**2
res = [potencia(numero) for numero in numeros]
print(res)
# List Comprehension versos Loop
# Loop
numeros = [1, 2, 3, 4, 5]
numeros_dobrados = []
for num in numeros:
numeros_dobrado = num * 2
numeros_dobrados.append(numeros_dobrado)
print(numeros_dobrados)
# List Comprehension
print([numero * 2 for numero in numeros])
"""
# Outros Exemplos
# 1
nome = 'Geek University'
print([letra.upper() for letra in nome])
# 2
def caixa_alt(nome):
nome = nome.replace(nome[0], nome[0].upper())
return nome
amigos = ['maria', 'julia', 'pedro', 'guilherme', 'vanessa']
print([caixa_alt(amigo) for amigo in amigos])
# 3
print([numero * 3 for numero in range(1, 10)])
# 4
print([bool(valor) for valor in [0, [], '', True, 1, 3.14]])
# 5
print([str(numero) for numero in [1, 2, 3, 4, 5]])
|
82f9f34c4eccafa9249c3a0e0d70fff7a0bab805 | hkXCIX/Fire-Maze | /dfs.py | 2,607 | 3.609375 | 4 | from mazeGen import arrayToTree
import numpy as np
from collections import deque
import copy
def dfs(maze, start, goal, mlen):
# keep a grid that marks where it was already explored
visited = np.zeros((mlen, mlen))
# DFS uses stack
stack = deque()
# starts at (0,0)
stack.append(start)
# while stack is not empty
while stack:
# current position
x, y = stack.pop()
# out of boundary, explore another position in stack
if x >= mlen or y >= mlen or x < 0 or y < 0 or visited[x, y] == 1:
continue
# if it reached the goal, there is a path
if (x, y) == goal:
return True
# skip if the cell is visited or blocked/fired
if visited[x, y] == 1 or maze[x, y] >= 1:
continue
# if the cell is not visited and is empty
elif visited[x, y] == 0 and maze[x, y] == 0:
visited[x, y] = 1
# stack right/down at last, because our goal is on the right bottom corner.
stack.append((x-1, y)) # left
stack.append((x, y-1)) # up
stack.append((x, y+1)) # down
stack.append((x+1, y)) # right
# if no existing path is found
return False
# for path marking
def dfs_graph(main_maze, start, goal, mlen):
maze = copy.deepcopy(main_maze)
# Initializes the stack with start cell (0,0) and no path yet
stack = deque([[start, ""]])
# keeps track of visited cells
visited = set()
# makes 2D array into graph
tree = arrayToTree(maze)
# while stack is not empty
while stack:
# current position traversing
tuples = stack.pop()
node, path = tuples
(x, y) = node
# if it reached the goal, return the path
if node == goal:
return path
# if x, y out of boundar, ignore
if x >= mlen or y >= mlen or x < 0 or y < 0:
continue
# if cell is blocked, ignore
if maze[x, y] >= 1:
continue
# if cell is unvisited and empty,
# visit and add neighbor nodes and append path
elif maze[x, y] == 0 and node not in visited:
visited.add(node)
for movement, neighborElements in tree[node]:
# path = current path + new movement, doing it outside the append broke it randomly
stack.append((neighborElements, path + movement))
# if no path is found
return "No such path from S to G exists"
|
a8d6c60913ca016dc44c6fac9d1eb877ce7c2759 | kyungtae92/Keras | /keras20_2_load.py | 1,740 | 3.5 | 4 | #1. 데이터
import numpy as np
x = np.array(range(1, 101)) # 1~100
y = np.array(range(1, 101))
print(x)
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=66, test_size=0.4, shuffle=False) # 6:4 / 섞기 싫으면 shuffle=False / default=True
x_test, x_val, y_test, y_val = train_test_split(x_test, y_test, random_state=66, test_size=0.5, shuffle=False) # 6:2:2
print(x_train)
print(x_test)
print(x_val)
#2. 모델구성
from keras.models import load_model
from keras.layers import Dense
model = load_model("./save/savetest01.h5")
# 저장한 모델에 모델 추가 가능, 단 레이어의 이름을 겹치게 하면 안됨
model.add(Dense(50, name='demse_100000'))
model.add(Dense(1, name='dense_200000'))
model.summary()
#3. 훈련
# model.compile(loss='mse', optimizer='adam', metrics=['accuracy'])
model.compile(loss='mse', optimizer='adam', metrics=['mse'])
# model.fit(x_train, y_train, epochs=100, batch_size=1)
model.fit(x_train, y_train, epochs=100, batch_size=1, validation_data=(x_val, y_val)) # validation은 검증(머신 자체가 평가하는 것)
#4. 평가 예측
loss, mse = model.evaluate(x_test, y_test, batch_size=1) # a[0], a[1] / evaluate를 반환하게 되면 loss, acc 를 반환
print("mse : ", mse)
y_predict = model.predict(x_test)
print(y_predict)
# RMSE 구하는 수식
from sklearn.metrics import mean_squared_error
def RMSE(y_test, y_predict):
return np.sqrt(mean_squared_error(y_test, y_predict))
print("RMSE : ", RMSE(y_test, y_predict))
# R2 구하기
from sklearn.metrics import r2_score
r2_y_predict = r2_score(y_test, y_predict)
print("R2 : ", r2_y_predict)
|
345d65578b93626830179f13c4f0c51fc800dab2 | GlinkaG/pp1 | /02-ControlStructures/Zad15.py | 84 | 3.8125 | 4 | x = int(input("Podaj x: "))
for i in range(1, 11):
print(f"{x}x{i}={x*i}")
|
78a5feed364a9fe45b8bb171fced1b6594ee02fe | gkarwchan/algorithms | /standard-algorithms/single-linked-list/linkedlist.py | 969 | 3.78125 | 4 | from node import Node
class LinkedList:
def __init__(self):
self.tail = None
self.head = None
self.size = 0
def append(self, data):
if self.tail:
self.tail.next = Node(data)
self.tail = self.tail.next
else:
self.head = Node(data)
self.tail = self.head
self.size += 1
def iter(self):
current = self.head
while current:
val = current.data
current = current.next
yield val
def delete(self, data):
current = self.head
prev = self.head
while current.data != data:
prev = current
current = current.next
if current:
prev.next = current.next
self.size -= 1
def contains(self, data):
current = self.head
while current and current.data != data:
current = current.next
return current != None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.