blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
181f9bb8e3876bd15fcb91b2ac9b6da02669ce40 | titusjan/pepeye | /examples/small.py | 552 | 3.546875 | 4 | from __future__ import print_function
from time import sleep
def myfun1():
print (" myfun1")
sleep(0.25)
myfun3()
def myfun2(n):
print (" myfun2")
sleep(0.15)
if n == 0:
return
else:
myfun3()
myfun2(n-1)
def myfun3():
print (" myfun3")
sleep(0.05)
myfun4()
def myfun4():
print (" myfun4")
sleep(0.003)
def main():
print ("main")
for i in range(10):
myfun1()
myfun2(15)
if __name__ == "__main__":
main()
|
bf533cf98e56396f5e9696ac237af5cf4586d06a | harsha-94/harsha-project | /harsha-project/data_stream/twitter/tweet.py | 1,110 | 3.609375 | 4 | __author__ = 'thecreator232'
from exceptions import UserNotFoundException
class Tweet(object):
def __init__(self, tweet):
self.tweet = tweet
@staticmethod
def text(self):
"""Returns the text of a tweet.
Returns:
unicode formatted string.
"""
return self.tweet.get("text", "")
@staticmethod
def hashtag(self):
""" Returns a list of hashtags associated with the tweet.
Returns:
List of hashtags.
"""
return self.tweet.get("entities").get("hashtags", [])
@staticmethod
def username(self):
"""Returns the user name of the person or entity that published the tweet.
Raises UserNotFoundException if username is not present in the tweet.
Returns:
unicode formatted string .
"""
try:
self.username = self.tweet.get("user").get("name", False)
if not self.username:
raise AttributeError
return self.username
except AttributeError:
raise UserNotFoundException
|
660848ae5488cb9326331d9aa4ac4aab71d73632 | Kpsmile/Learn-Python | /Basic_Programming/ListsComprehension_basics.py | 951 | 4.125 | 4 | sentence='My Name is Kp Singh'
def eg_lc(sentence):
vowel='a,e,i,o,u'
return''.join(l for l in sentence if l not in vowel)
print"List comprehension is" + eg_lc(sentence)
"""square of only even numbers in the list
def square_map(arr):
return map(lambda x: x**2, arr)
print ["List comprehension is" ]+ square_map(range(1,11))"""
"""square of only even numbers in the list"""
def even_fil(arr):
return str(filter(lambda x:x is not None ,map(lambda x:x**2 if x%2==0 else None, arr)))
print "square of only even numbers in the list is :" + even_fil(range(1,11))
#Method 3: List comprehension:
def square_even_lc(arr):
return str([i**2 for i in arr if i%2==0])
print "square of only even numbers in the list is :"+square_even_lc(range(1,11))
"""
Counting the occurrences of one item in a list
"""
l=['q','a','q', 1,3,1,2,3]
res=[[x,l.count(x)] for x in set(l)]
res_1=[[x,l.count(x)] for x in (l)]
print res
print res_1 |
832de19c8b9ab75f412d3f0ebc57f6791bc0d15f | Kpsmile/Learn-Python | /Basic_Programming/Collections.py | 1,580 | 4.53125 | 5 | a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
"""
Sorting a List of Lists or Tuples
This is a little more complicated, but still pretty easy, so don't fret!
Both the sorted function and the sort function take in a keyword argument called key.
What key does is it provides a way to specify a function that returns what you would like your items
sorted by. The function gets an "invisible" argument passed to it that represents an item in the list,
and returns
a value that you would like to be the item's "key" for sorting.
So, taking a new list, let's test it out by sorting by the first item in each sub-list
"""
def getkey(item):
return item[1]
l=[[1,30],[4,21],[3,7]]
res=sorted(l, key=getkey)
print(res)
"""
Sorting a List (or Tuple) of Custom Python Objects
"""
class Custom(object):
def __init__(self, name, number):
self.name=name
self.number=number
def __repr__(self):
"""
the __repr__ function tells Python how we want the object to be represented as.
it tells the interpreter how to display the object when it is printed to the screen.
"""
return'{}: {} {}'.format(self.__class__.__name__,
self.name,
self.number)
Customlist=[Custom('abc',10),Custom('xyz',10),Custom('jklm',10),Custom('qrs',10)]
def getkey(item):
return item.name
results=sorted(Customlist, key=getkey)
result_rev=sorted(Customlist, key=getkey,reverse=True)
print(results)
print(result_rev)
|
d9b3cbdec02329fadaa14cab8a17bd253a14469a | supermitch/Advent-of-Code | /2016/21/twenty_one.py | 3,185 | 3.609375 | 4 | from collections import deque
def parse(line):
parts = line.split()
if 'move' in parts:
return ('move', int(parts[2]), int(parts[5]))
elif 'swap letter' in line:
return ('swap', parts[2], parts[5])
elif 'swap position' in line:
return ('swap_pos', int(parts[2]), int(parts[5]))
elif 'reverse' in parts:
return ('rev', int(parts[2]), int(parts[4]))
elif parts[1] in ('left', 'right'):
return (parts[1], int(parts[2]), None)
elif 'on' in parts: # 'rotate based on...'
return ('rot', parts[-1], None)
def run(rule, input, reverse=False):
act, a, b = rule
d = deque(input)
if act == 'move':
l = list(input)
char_a = l.pop(a) # Can't pop(index) a deque!
l.insert(b, char_a)
d = deque(l)
elif act == 'swap': # Same when reversed
idx_a = d.index(a)
idx_b = d.index(b)
d[idx_a], d[idx_b] = d[idx_b], d[idx_a]
elif act == 'swap_pos': # Same when reversed
d[a], d[b] = d[b], d[a]
elif act == 'rev': # Same when reversed
b += 1 # Range is inclusive
l = input[:a] + input[a:b][::-1] + input[b:]
d = deque(l) # Can't slice a deque!
elif act == 'left':
d.rotate(a if reverse else -a)
elif act == 'right':
d.rotate(-a if reverse else a)
elif act == 'rot':
idx_a = d.index(a)
if reverse: # For an 8 char string only!
n = { # Each end position had only 1 possible starting point
0: -1,
1: -1,
2: 2,
3: -2,
4: 1,
5: -3,
6: 0,
7: -4,
}[idx_a]
d.rotate(n)
else: # To scramble we can calculate result
n = 1 + idx_a + (1 if idx_a >= 4 else 0)
d.rotate(n)
return ''.join(d)
def main():
input = 'abcde'
test = [
'swap position 4 with position 0',
'swap letter d with letter b',
'reverse positions 0 through 4',
'rotate left 1 step',
'move position 1 to position 4',
'move position 3 to position 0',
'rotate based on position of letter b',
'rotate based on position of letter d',
]
test_rules = [parse(l.strip()) for l in test]
assert run(test_rules[0], 'abcde') == 'ebcda'
assert run(test_rules[1], 'ebcda') == 'edcba'
assert run(test_rules[2], 'edcba') == 'abcde'
assert run(test_rules[3], 'abcde') == 'bcdea'
assert run(test_rules[4], 'bcdea') == 'bdeac'
assert run(test_rules[5], 'bdeac') == 'abdec'
assert run(test_rules[6], 'abdec') == 'ecabd'
assert run(test_rules[7], 'ecabd') == 'decab'
with open('input.txt', 'r') as f:
rules = [parse(l.strip()) for l in f]
password = 'abcdefgh'
for rule in rules:
password = run(rule, password)
print('Part A: {} - Scrambled password'.format(password))
password = 'fbgdceah'
for rule in rules[::-1]:
password = run(rule, password, reverse=True)
print('Part B: {} - Unscrambled password'.format(password))
if __name__ == '__main__':
main()
|
49f3e309c00eb4717e7485595e5c2cbc745ec112 | supermitch/Advent-of-Code | /2017/23/twenty_three.py | 523 | 3.671875 | 4 | #!/usr/bin/env python
def not_prime(n):
for i in range(2, n): # Ignoring 1 * n
if n % i == 0:
return True
return False
def run(debug=True):
if debug:
b = 65
c = 65
return (b - 2) * (c - 2)
else:
return sum(not_prime(b) for b in range(106500, 123500 + 1, 17))
def main():
print('Part A: {} - `Mul` count w/ debug on'.format(run(True)))
print('Part B: {} - Register h w/ debug off'.format(run(False)))
if __name__ == '__main__':
main()
|
6d07ddc90e53979b46f87fe9e4cf48a602499476 | supermitch/Advent-of-Code | /2020/05/five.py | 829 | 3.53125 | 4 | def seat_id(seat):
rows = list(range(128))
for k in seat[:7]:
n = len(rows)
if k == 'F':
rows = rows[:n // 2]
elif k == 'B':
rows = rows[n // 2:]
cols = list(range(8))
for k in seat[7:]:
n = len(cols)
if k == 'L':
cols = cols[:n // 2]
elif k == 'R':
cols = cols[n // 2:]
return rows[0] * 8 + cols[0]
def main():
with open('input.txt') as f:
data = [x.strip() for x in f]
part_a = max(seat_id(x) for x in data)
all_seats = sorted([seat_id(x) for x in data])
missing = set(range(all_seats[0], all_seats[-1])) - set(all_seats)
part_b = missing.pop()
print(f'Part A: {part_a} - Maximum seat ID')
print(f'Part B: {part_b} - My seat ID')
if __name__ == '__main__':
main()
|
f30a4352bf060c56a1e1f623da96e35eeb6671ad | supermitch/Advent-of-Code | /2017/06/six.py | 789 | 3.75 | 4 | def reallocate(memory):
n = len(memory)
blocks = max(memory)
i = memory.index(blocks) # Returns first high bank
memory[i] = 0 # Reset current bank
while blocks > 0:
memory[(i + 1) % n] += 1
blocks -= 1
i += 1
return memory
def redistribute(memory):
count = 0
seen = set()
while True:
seen.add(memory.__str__())
memory = reallocate(memory)
count += 1
if memory.__str__() in seen:
return count, memory
def main():
memory = [4, 1, 15, 12, 0, 9, 9, 5, 5, 8, 7, 3, 14, 5, 12, 3]
count_a, state = redistribute(memory)
print('Part A: {}'.format(count_a))
count_b, _ = redistribute(state)
print('Part B: {}'.format(count_b))
if __name__ == '__main__':
main()
|
1b238cbf45478268d686289cdcf11751401b07c0 | supermitch/Advent-of-Code | /2019/03/three.py | 1,852 | 3.921875 | 4 | #!/usr/bin/env python
deltas = {
'R': (1, 0),
'L': (-1, 0),
'U': (0, 1),
'D': (0, -1),
}
def get_steps(moves, grid, junctions):
""" Calculate the steps it takes to get to each junction. """
x, y = 0, 0
steps = 0
taken = {}
for d, dist in moves:
dx, dy = deltas[d]
for i in range(1, dist + 1):
steps += 1
coord = (x + dx * i, y + dy * i)
if coord in junctions:
taken[coord] = steps
x = x + dx * i
y = y + dy * i
return taken
def trace_path(moves):
""" Follow the path and populate coordinates in a grid. """
x, y = 0, 0
grid = {(x, y): 'o'}
for d, dist in moves:
dx, dy = deltas[d]
for i in range(1, dist + 1):
grid[(x + dx * i, y + dy * i)] = '.'
x = x + dx * i
y = y + dy * i
return grid
def main():
with open('input.txt') as f:
one = [(x[0], int(x[1:])) for x in next(f).split(',')]
two = [(x[0], int(x[1:])) for x in next(f).split(',')]
g_one = trace_path(one)
g_two = trace_path(two)
junctions = []
max_manhattan = float('inf')
for coord in g_one:
if coord == (0, 0):
continue
if coord in g_two:
junctions.append(coord)
manhattan = abs(coord[0]) + abs(coord[1])
max_manhattan = min(max_manhattan, manhattan)
print(f'Part A: {max_manhattan} - Distance to nearest intersection')
steps_one = get_steps(one, g_one, junctions)
steps_two = get_steps(two, g_two, junctions)
min_steps = float('inf')
for coord, steps in steps_one.items():
total = steps + steps_two[coord]
min_steps = min(total, min_steps)
print(f'Part B: {min_steps} - Minimum steps to an intersection')
if __name__ == '__main__':
main()
|
7535941f17a2579cfa862b4587e7603e6d425a22 | aakashpatel12345/FDMMLTraining | /CreatingMyOwnLinearRegressor4.py | 1,727 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 18:16:35 2020
@author: Aakash
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv("./Datasets/admissions.csv")
#create independent and dependent variables
x=np.array(data["TOEFL Score"])
y=np.array(data["CGPA"])
def gradient_descent(x,y,learning_rate=0.0001,num_iterations = 10):
m_curr = 0
b_curr = 0
n = len(y)
for i in range(num_iterations):
y_pred = (m_curr*x) + b_curr
#list comprehension
cost = (1/(2*n)) * sum(val ** 2 for val in (y-y_pred))
m_grad = -(1/n) * sum(x*(y-y_pred))
b_grad = -(1/n) * sum(y-y_pred)
m_curr = m_curr - (learning_rate*m_grad)
b_curr = b_curr - (learning_rate*b_grad)
''' print ("The gradient in this iteration is {}".format(m_curr))
print("The y_intercept in this iteration is {}".format(b_curr))
print("This is iteration number {} and it costs {}".format(i, cost))'''
return m_curr,b_curr,y_pred
#need to account for multiple independent variables
#multiple m's
#increase learning rate as algorithm proceeds - maybe
#
mCurrent, bCurrent, y_pred_train = gradient_descent(x,y)
'''#for training set
#y_pred = mCurrent*x_train + bCurrent
plt.scatter(x_train,y_train, c = "red")
plt.plot(x_train,y_pred, c = "blue") #model line of best fit'''
'''#for testing set
#y_pred = mCurrent*x_train + bCurrent
plt.scatter(x_test,y_test, c = "red")
plt.plot(x_train,y_pred, c = "blue") #same as before'''
plt.scatter(x,y, c = "blue")
plt.plot(x,y_pred_train, c = "red") |
c986753668e3402c48f04c040db3b6f2b600a5a6 | craignicol/adventofcode | /2022/day.13.py | 3,284 | 3.609375 | 4 | #!/usr/bin/env python3
def execute():
with open('2022/input/day.13.txt') as inp:
lines = inp.readlines()
data = [l for l in lines]
is_in_order, is_correct, score = check_order(data)
return is_correct, score, decoder_key(data)
tests_failed = 0
tests_executed = 0
def verify(a, b):
global tests_executed
global tests_failed
tests_executed += 1
if (a == b):
print("✓")
return
tests_failed += 1
print (locals())
sample_input = """[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
""".splitlines()
def is_ordered(first, second):
if first is None or second is None:
return False
for i in range(len(first)):
if i >= len(second):
return False
elif type(first[i]) == int and type(second[i]) == int:
if first[i] != second[i]:
return first[i] < second[i]
elif type(first[i]) == list and type(second[i]) == list:
result = is_ordered(first[i], second[i])
if result is not None:
return result
elif type(first[i]) == int and type(second[i]) == list:
result = is_ordered([first[i]], second[i])
if result is not None:
return result
elif type(first[i]) == list and type(second[i]) == int:
result = is_ordered(first[i], [second[i]])
if result is not None:
return result
else:
return False
return None if len(first) == len(second) else True
def check_order(input):
is_in_order = [False]
pairs = [None]
first, second = None, None
for line in input:
if line.startswith("["):
if first is None:
first = eval(line)
elif second is None:
second = eval(line)
if line.strip() == "":
is_in_order.append(is_ordered(first, second))
pairs.append((first, second))
first, second = None, None
is_in_order.append(is_ordered(first, second)) # EOL
pairs.append((first, second))
return is_in_order, [x for x, i in enumerate(is_in_order) if i], sum([x for x, i in enumerate(is_in_order) if i])
def decoder_key(input):
before_2 = 1
before_6 = 2 # we know 2 is before 6
for line in input:
if line.startswith("["):
first = eval(line)
if is_ordered(first, [[2]]):
before_2 += 1
if is_ordered(first, [[6]]):
before_6 += 1
return before_2 * before_6
def test_cases():
is_in_order, _, score = check_order(sample_input)
verify(len(is_in_order), 9)
verify(is_in_order[1], True)
verify(is_in_order[2], True)
verify(is_in_order[3], False)
verify(is_in_order[4], True)
verify(is_in_order[5], False)
verify(is_in_order[6], True)
verify(is_in_order[7], False)
verify(is_in_order[8], False)
verify(score, 13)
verify(decoder_key(sample_input), 140)
print("Failed {} out of {} tests. ".format(tests_failed, tests_executed))
if __name__ == "__main__":
test_cases()
print(execute()) |
5bbd579a75b947034e9bd1c8fde3f05bcb311315 | craignicol/adventofcode | /2020/day.8.py | 1,831 | 3.578125 | 4 | #!/usr/bin/env python3
example = """nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6"""
def execute():
with open('2020/input/8.txt') as inp:
lines = inp.readlines()
code = [l.strip() for l in lines if len(l.strip()) > 0]
return run_until_loop_or_exit(code)["accumulator"], flip_until_halt(code)
tests_failed = 0
tests_executed = 0
def verify(a, b):
global tests_executed
global tests_failed
tests_executed += 1
if (a == b):
print("✓")
return
tests_failed += 1
print (locals())
uncorrupt = {
"jmp": "nop",
"nop": "jmp",
"acc": "acc"
}
def run_until_loop_or_exit(code, flip=None):
# For Part 2, flip n-th instruction
accumulator = 0
pos = 0
seen_positions = set()
possibly_corrupt = 0
while(pos not in seen_positions and pos < len(code)):
seen_positions.add(pos)
(command, value) = code[pos].split()
if possibly_corrupt == flip:
command = uncorrupt[command]
if command == "nop":
pos += 1
possibly_corrupt += 1
elif command == "acc":
pos += 1
accumulator += int(value)
elif command == "jmp":
pos += int(value)
possibly_corrupt += 1
halting = pos not in seen_positions
return locals()
def flip_until_halt(code):
for i in range(len(code)):
result = run_until_loop_or_exit(code, i)
if result["halting"]:
return result["accumulator"]
return None
def test_cases():
verify(run_until_loop_or_exit(example.splitlines())["accumulator"], 5)
verify(flip_until_halt(example.splitlines()), 8)
print("Failed {} out of {} tests. ".format(tests_failed, tests_executed))
if __name__ == "__main__":
test_cases()
print(execute()) |
3bb34ee077779049883bb8b24e9a3919cac6ccab | craignicol/adventofcode | /2015/day.9.py | 2,084 | 3.921875 | 4 | #!/usr/bin/env python3
def execute():
with open('2015/input/9.txt') as inp:
lines = inp.readlines()
data = create_graph([l.strip() for l in lines if len(l.strip()) > 0])
return shortest_distance(data), longest_distance(data)
tests_failed = 0
tests_executed = 0
distances = """London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141""".splitlines()
def verify(a, b):
global tests_executed
global tests_failed
tests_executed += 1
if (a == b):
print("✓")
return
tests_failed += 1
print (locals())
def create_graph(distances):
graph = {}
for line in distances:
parts = line.split()
if parts[0] not in graph:
graph[parts[0]] = {}
if parts[2] not in graph:
graph[parts[2]] = {}
graph[parts[0]][parts[2]] = int(parts[4])
graph[parts[2]][parts[0]] = int(parts[4])
return graph
def shortest_route_from(graph, current, distance, visited):
if len(visited) == len(graph):
yield distance
else:
for next in graph[current]:
if next not in visited:
yield from shortest_route_from(graph, next, distance + graph[current][next], visited | {next})
def shortest_route(graph, start):
return min(shortest_route_from(graph, start, 0, set([start])))
def shortest_distance(graph):
return min(shortest_route(graph, start) for start in graph)
def longest_route(graph, start):
return max(shortest_route_from(graph, start, 0, set([start])))
def longest_distance(graph):
return max(longest_route(graph, start) for start in graph)
def test_cases():
verify(create_graph(distances), {'London': {'Dublin': 464, 'Belfast': 518}, 'Dublin': {'London': 464, 'Belfast': 141}, 'Belfast': {'London': 518, 'Dublin': 141}})
verify(shortest_distance(create_graph(distances)), 605)
verify(longest_distance(create_graph(distances)), 982)
print("Failed {} out of {} tests. ".format(tests_failed, tests_executed))
if __name__ == "__main__":
test_cases()
print(execute()) |
04f9c78547a4933543f5cc523883668eca04a5bd | craignicol/adventofcode | /2022/day.3.py | 1,859 | 3.53125 | 4 | #!/usr/bin/env python3
def execute():
with open('2022/input/day.3.txt') as inp:
lines = inp.readlines()
data = [l.strip() for l in lines if len(l.strip()) > 0]
return total_priority(data), total_badge_priority(data)
tests_failed = 0
tests_executed = 0
sample_input = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".strip().splitlines()
def verify(a, b):
global tests_executed
global tests_failed
tests_executed += 1
if (a == b):
print("✓")
return
tests_failed += 1
print (locals())
def common_item(s):
comp1, comp2 = set(s[:len(s)//2]), set(s[len(s)//2:])
return comp1.intersection(comp2).pop()
def priority(c):
return ord(c) - ord('a') + 1 if ord(c) >= ord('a') else ord(c) - ord('A') + 27
def total_priority(data):
return sum([priority(common_item(s)) for s in data])
def find_badge(data):
return set(data[0]).intersection(set(data[1])).intersection(set(data[2])).pop()
def total_badge_priority(data):
return sum([priority(find_badge(data[i:i+3])) for i in range(0, len(data), 3)])
def test_cases():
verify(common_item(sample_input[0]), "p")
verify(common_item(sample_input[1]), "L")
verify(common_item(sample_input[2]), "P")
verify(common_item(sample_input[3]), "v")
verify(common_item(sample_input[4]), "t")
verify(common_item(sample_input[5]), "s")
verify(priority("p"), 16)
verify(priority("L"), 38)
verify(priority("P"), 42)
verify(priority("v"), 22)
verify(priority("t"), 20)
verify(priority("s"), 19)
verify(total_priority(sample_input), 157)
verify(find_badge(sample_input[0:3]), "r")
verify(find_badge(sample_input[3:6]), "Z")
verify(total_badge_priority(sample_input), 70)
print("Failed {} out of {} tests. ".format(tests_failed, tests_executed))
if __name__ == "__main__":
test_cases()
print(execute()) |
526467e551c21f70ecd9cc7a09f42db83f74c965 | craignicol/adventofcode | /2021/day.13.py | 2,159 | 3.5 | 4 | #!/usr/bin/env python3
def execute():
with open('./input/day.13.txt') as inp:
lines = inp.readlines()
data = [l.strip() for l in lines if len(l.strip()) > 0]
paper = fold_paper(parse_origami(data))
render(paper)
return count_dots(paper)
tests_failed = 0
tests_executed = 0
def verify(a, b):
global tests_executed
global tests_failed
tests_executed += 1
if (a == b):
print("✓")
return
tests_failed += 1
print (locals())
example1 = """6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0
fold along y=7
fold along x=5""".splitlines()
def parse_origami(lines):
dots = set()
folds = []
for line in lines:
if line.count(',') == 1:
dots.add(tuple(map(int, line.split(','))))
elif line.startswith('fold'):
folds.append(line.split(' ')[-1].split('='))
return dots, folds
def fold_paper(origami):
dots, folds = origami
new_dots = set()
for (axis, pos) in folds:
for (x,y) in dots:
pos = int(pos)
if axis == 'y':
new_dots.add((x, y if y < pos else pos + pos - y))
elif axis == 'x':
new_dots.add((x if x < pos else pos + pos - x, y))
dots = new_dots
print(len(dots))
# render((dots, folds))
new_dots = set()
return dots, folds
def render(origami):
dots, _ = origami
min_x = min(d[0] for d in dots)
max_x = max(d[0] for d in dots)
min_y = min(d[1] for d in dots)
max_y = max(d[1] for d in dots)
for y in range(min_y, max_y + 1):
for x in range(min_x, max_x + 1):
if (x,y) in dots:
print('#', end='')
else:
print('.', end='')
print()
def count_dots(origami):
dots, _ = origami
return len(dots)
def test_cases():
verify(count_dots(parse_origami(example1)), 18)
verify(count_dots(fold_paper(parse_origami(example1))), 16)
print("Failed {} out of {} tests. ".format(tests_failed, tests_executed))
if __name__ == "__main__":
test_cases()
print(execute()) |
7e33ff5032f25a4a6963b7bfb42a72597dc96d4e | 59090939/ClassProjects | /Programming220/homeowrk10/CardSOLUTION.py | 706 | 3.515625 | 4 | # CardSOLUTION.py
# Author: RoxAnn H. Stalvey
# Modified by Pharr
class Card:
def __init__(self, value, suit):
if value >= 1 and value <= 13:
self.value = int(value)
else:
self.value = 1
if self.validSuit(suit):
self.suit = suit
else:
self.suit = "Spades"
def getFaceValue(self):
return self.value
def getSuit(self):
return self.suit
def validSuit(self, suit):
suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
return suit in suits
def __str__(self):
values = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"]
return str(values[self.value-1]) + " of " + self.suit
|
8f7b4c6fb7836cffe5535ac1dec6cc55e8f90808 | 59090939/ClassProjects | /Programming220/salarytable.py | 518 | 3.890625 | 4 | def main():
startyear = input("What year did you start teaching? ")
currentyear = input("Up to what year would you like to calulate your salary? ")
salary = input("What was your starting salary? ")
percent = input("What is the percent increase of your annual salary? ")
years = currentyear - startyear
for i in range (years):
startyear = startyear + 1
salary = (percent / 100.0) * salary + salary
print "$%.02f" %salary, "is your salary by the year", startyear
main()
|
8ef71a1e59510cec01da5391765d439d40272f28 | 59090939/ClassProjects | /Programming220/ch. 2/conversion(cu-ml).py | 381 | 4.09375 | 4 | ## Conversion.py
## David Schirduan
## This code converts cups (input) to ml (output)
def main():
print "This program converts cups to Ml."
units = raw_input ("what are the resultant units: ")
cups = input ("How many cups does the recipe require: ")
ounces = cups * 8
milliliters = ounces * 29.57
print "This ie equal to ", milliliters, units
main()
|
eb79d415a647e67158ab5061466868ee339e626f | 59090939/ClassProjects | /Programming220/ch. 2/lab2/convertable.py | 350 | 4.0625 | 4 | # convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell (actually Zelle; see p. 28)
def main():
celsius = 0
for i in range(11):
fahrenheit = (9.0 / 5.0) * celsius + 32
print celsius,"degrees in Celsius is", fahrenheit, "degrees Fahrenheit."
celsius = celsius + 10
main()
|
ae990b74675bc00138a6d6daf574aefa7181342b | wildfox24/Python | /klek_learn.py | 858 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
class Square(object):
width=0
height=0
def __init__(self, width, height):
self.width=width
self.height=height
def area(self):
return self.width * self.height
@staticmethod
def get_area(width, height):
return width * height
class Cube(Square):
z=0
def __init__(self, width, height, z):
#Square.__init__(self, width, height)
super(Cube, self).__init__(width, height)
self.z=z
def volume(self):
return self.area() * self.z
def main():
sq=Square(100, 40)
#sq.width=100
#sq.height=40
#print sq.area()
#print Square.get_area(100,40)
cb=Cube(100, 40, 5)
print "Площадь: " + str(cb.area())
print "Объем: " + str(cb.volume())
return 0
if __name__ == '__main__' :
sys.exit( main() )
|
8a3abf1a0099ab461244f251316de824c2012c0c | fernandotonon/Estrutura_Dados | /memoria.py | 1,405 | 3.9375 | 4 | class No:
def __init__(self, dado):
self.dado = dado
self.prox = None
def getDado(self):
return self.dado
def setDado(self, dado):
self.dado = dado
def getProx(self):
return self.prox
def setProx(self, prox):
self.prox = prox
class ListaEncadeada:
def __init__(self):
self.cabeca=None
def __str__(self):
txt='['
noAtual = self.cabeca
while noAtual != None:
txt = txt+str(noAtual.getDado())
if noAtual.getProx() != None:
txt = txt + ', '
noAtual=noAtual.getProx()
txt = txt + ']'
return txt
def isEmpty(self):
return self.cabeca == None
#Adicionar novo nó no início
def add(self, elemento):
elemento.setProx(self.cabeca)
self.cabeca = elemento
#Contar o tamanho
def contar(self):
contador = 0
elemento = self.cabeca
while elemento != None:
contador = contador + 1
elemento = elemento.getProx()
return contador
lista = ListaEncadeada()
lista.add(No("Fernando"))
lista.add(No("José"))
lista.add(No("José"))
print (lista)
print (lista.contar())
#Verificar se existe um determinado valor na lista
#Remover um nó da lista
#Adicionar um nó em uma posição específica da lista |
88783965e0dd86b8a91c436d16b4f89267cdfa26 | surya-lights/Python_Cracks | /Random.py | 383 | 3.921875 | 4 | # To import random numbers within the range of 1 to 100
import random
print(random.randrange(1, 100))
# Conversion of numbers
x = 5 # int
y = 7.2 # float
z = 4j # complex
# convert from int to float:
a = float(x)
# convert from float to int:
b = int(y)
# convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
|
3cace7075d865c99c2efb281d09234af707aff73 | surya-lights/Python_Cracks | /loop types.py | 409 | 3.859375 | 4 | # Inner loop
nums = [1, 2, 3]
for num in nums:
for letter in 'abc':
print(letter, nums)
# Build in function Range
for i in range(10):
print(i)
for i in range(1, 11):
print(i)
# While loop
x = 0
while x < 10:
print(x)
x += 1
# Break
x = 0
while x < 10:
if x := 5:
breakpoint()
print(x)
x += 1
# Infinite loop
a = 0
while True:
print(a)
a += 1
|
50febd52f27da540cc858944a37969ed932090c6 | surya-lights/Python_Cracks | /math.py | 293 | 4.15625 | 4 | # To find the highest or lowest value in an iteration
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
# To get the positive value of specified number using abs() function
x = abs(-98.3)
print(x)
# Return the value of 5 to the power of 4 is (same as 5*5*5*5):
x = pow(5, 4)
print(x)
|
0aee5541a76e0bca960fb14ebeb7177802d35c11 | surya-lights/Python_Cracks | /Key Func.py | 333 | 3.890625 | 4 | # Keys
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. keys())
# To show values
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. values())
# To display items
student = {'name': 'charles', 'age': 25, 'course': ['math', 'Biology']}
print(student. items())
|
72b3fa8b3d95a06f0c5f03e9f5601f43ba3ee843 | ajamesl/Exercises | /exercises1.py | 1,830 | 3.6875 | 4 | import math
c = "Come"
d = "home"
print c + " " + d
for i in range(10):
print "Hello"
for i in range (10):
print i
for i in range(1,11):
print i
for i in range(1,21):
print i**2
for i in range(1,100):
if i**2 < 1000:
print i**2
for i in range(1,200):
if i%3.0 == 0 and i%5.0 == 0:
print i
s = 0
for i in range(1,101):
s = s + i
print s
z = 0
for i in range(1,101):
z = z + i**2
print z
print s**2 - z
for i in range(0,101):
if i%3.0 == 0 and i%5.0 == 0:
print "fizzbuzz"
elif i%3.0 == 0:
print "fizz"
elif i%5.0 == 0:
print "buzz"
else:
print i
x = 113
z = 0
for i in range(2,x):
if x%i == 0:
z += 1
if z > 0:
print str(x) + " is not a prime number."
else:
print str(x) + " is a prime number."
primesFound = 0
number = 0
while primesFound < 100:
prime = True
for i in range(2, number):
if number % i == 0:
prime = False
break
if prime:
print(number)
primesFound += 1
number += 1
n = 102
for i in range (1,n):
l = 1
for j in range(1,i):
l*=j
print str(n - 2) + " factorial is equal to " + str(l)
e = 0.0
n = 102
for i in range (1,n):
l = 1
for j in range(1,i):
l*=j
e += 1/l
print "e is equal to " + str(e)
print "The error on e is equal to " + str(e - math.e)
s = 0.0
a = 100
for i in range(1,a):
n = 2.0*i + 1.0
s += 1.0/n
print s
s = 0.0
a = 1000
for i in range(0,a):
s += ((-1.0)**i)/((2.0*i) + 1.0)
print "Pi is equal to " + str(s*4)
print "With an error of " + str(s*4 - math.pi)
g = 1.0
h = 1.0
m = 100
for i in range(1,m):
j = g + h
g = h
h = j
n3 = j
g = 1.0
h = 1.0
m = 101
for i in range(1,m):
j = g + h
g = h
h = j
n4 = j
print n4/n3
|
f8bbfd6363010700b233934b7392629138d29e66 | sanazjamloo/algorithms | /mergeSort.py | 1,395 | 4.4375 | 4 | def merge_sort(list):
"""
Sorts a list in ascending order
Returns a new sorted List
Divide: Find the midpoint of the list and divide into sublists
Conquer: Recursively sort the sublists created in previous step
Combine: Merge the sorted sublists created in previous step
Takes O(n log n) time and O(n) space
"""
#Stopping condition of the recursion
if len(list) <= 1:
return List
left_half, right_half = split(list)
left = merge_sort(left_half)
right = merge_sort(right_half)
return merge(left, right)
def split(list):
"""
Divide the unsorted list at midpoint into sublists
Returns two sublists - left and right_half
Takes overal O(log n) time
"""
# // for floor operation
mid = len(list) //2
left = list[:mid]
right = list[mid:]
return left, right
def merge (left, right):
"""
Merges two lists (left and right), sorting them in the process
Returns a new merged list
Runs in overall O(n) time
"""
l = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
l.append(left[i])
i+ = 1
else:
l.append(right[j])
j+ = 1
return l
|
a5630e21ec26ed53258db76f7a138f3fc520373e | hemanthsoma/BigData | /Assignment01/prime_numbers.py | 213 | 3.625 | 4 | def primeNumbers(limit):
for i in range(2,limit+1):
for j in range(2,i):
if i%j==0:
break
else:
print(i)
limit = int(input())
primeNumbers(limit) |
1a60361248c7c4e56f5b5ee3ab04c0945ed94b2a | hemanthsoma/BigData | /Assignment02/ReverseInteger.py | 118 | 3.75 | 4 | number=int(input())
rev=0
while number!=0:
digit=number%10
rev=(rev*10)+digit
number//=10
print(rev) |
e60dddb767568b9c23308441b7c7016f6fc64554 | hemanthsoma/BigData | /Assignment02/ConvertTempCentToFahren.py | 113 | 3.75 | 4 | c = int(input('Enter temperature in Centrigrade'))
f = ((9*c)/5)+32
print('Temperature in Fahrenheit is: ',f)
|
c6b77a3fd1fa2d9140df334354dde84a3e58036a | hemanthsoma/BigData | /Assignment02/LinearSearch.py | 239 | 4.03125 | 4 | List=[1,2,3,4,5,6,7,8]
flag=0
search=int(input('Enter num to search'))
for i in range(len(List)):
if List[i]==search:
print('Element is found')
flag=1
break
if flag==0:
print('Element is not found') |
5febd76579e8ba3ba0619081584e7b1f0db970c0 | hemanthsoma/BigData | /Assignment01/sumOfMultiples.py | 251 | 3.71875 | 4 | def sumOfMultiplesOf3and5(limit):
l = []
i = 1
while True:
l.extend([3*i,5*i])
if 3*i==limit or 5*i==limit:
break
i+=1
return sum(l)
limit = int(input())
print(sumOfMultiplesOf3and5(limit)) |
8486feacc41df6f6930874661fddedee07114648 | Mahoro752/PROGRAM-THAT-ACCEPTS-THE-DIFFERENCE-OF-NUMBERS | /Defference of any number.py | 209 | 4.03125 | 4 | first_number = int(input("Enter first Number: "))
second_number = int(input("Enter Second number: "))
x = first_number - second_number
print()
print("The Diffrence between first and second number is: ", x) |
73631147ca4cc0322de2a68a36290502ee230907 | ytgeng99/algorithms | /Pythonfundamentals/FooAndBar.py | 1,040 | 4.25 | 4 | '''Write a program that prints all the prime numbers and all the perfect squares for all numbers between 100 and 100000.
For all numbers between 100 and 100000 test that number for whether it is prime or a perfect square. If it is a prime number print "Foo". If it is a perfect square print "Bar". If it is neither print "FooBar". Do not use the python math library for this exercise. For example, if the number you are evaluating is 25, you will have to figure out if it is a perfect square. It is, so print "Bar".'''
for i in range(100, 100001):
if i == 1:
prime = False
perfect_square = True
else:
prime = True
perfect_square = False
for j in range(2, i):
if i%j == 0:
prime = False
if j**2 == i:
perfect_square = True
if j*2 > i or j**2 > i:
break
if not prime and not perfect_square:
print i, 'FooBar'
elif prime:
print i, 'Foo'
elif perfect_square:
print i, 'Bar'
|
44a002f5ed28792f31033331f79f49b24d6bc3ef | ytgeng99/algorithms | /Pythonfundamentals/TypeList.py | 1,320 | 4.375 | 4 | '''Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.'''
l = ['magical unicorns',19,'hello',98.98,'world']
'''l = [2,3,1,7,4,12]
l = ['magical','unicorns']
l = []'''
new_str_list = []
sum = 0
str_items = 0
num_items = 0
for item in l:
if type(item) == str:
new_str_list.append(item)
str_items += 1
elif type(item) == int or type(item) == float:
sum += item
num_items += 1
if (str_items == 0 and num_items == 0):
print 'The array you entered is empty'
elif (str_items > 0 and num_items > 0):
print 'The array you entered is of mixed type'
elif (str_items != 0 and num_items == 0):
print 'The array you entered is of string type'
elif (str_items == 0 and num_items != 0):
print 'The array you entered is of number type'
if (str_items != 0):
print 'String:', ' '.join(new_str_list)
if (num_items != 0):
print 'Sum:', sum |
478c988bb167a129631e2c8b0f3d07c51b65574b | Sacharya1/Basic-Python-Tutorials | /runnerUp.py | 600 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 6 19:10:34 2019
@author: SampadAcharya
"""
if __name__ == '__main__':
n = 5
arr = [-7,-7,-7,-7,-6]
index=[]
def indexVal(arr, maxVal,n):
for i in range(n):
if arr[i]==maxVal:
# print(i)
m=i
index.append(m)
return index
maxVal=max(arr)
indexRange=indexVal(arr, maxVal,n)
#print((indexRange))
for i in range(len(indexRange)):
arr[indexRange[i]]=-200
newArr=arr
#print(newArr)
runnerUp=max(newArr)
print(runnerUp)
|
a0f8368674545ca6a45d715afbc9bbaadf062c08 | huynguyen120390/CrackingCodingProblem | /ArrayandStrings/return_permutationStrings.py | 1,337 | 3.75 | 4 | def __is_permutation(string1, string2):
if len(string1) != len(string2):
return False
set = {}
#stock chars of string1 with positive occurency
for i, v in enumerate(string1):
v = v.lower()
if v not in set:
set[v] = 1
else:
set[v] += 1
#stock chars of string2 with negative occurency, if new char occurs means not permutation-> return False
for i, v in enumerate(string2):
v = v.lower()
if v not in set:
return False
else:
set[v] -= 1
#if stocking chars from two strings is done, and no return False, check if any occurence > 0, if yes -> return False
for v in set:
if set[v] > 0:
return False
return True
def return_permutations(piece,longString):
n = len(longString)
np = len(piece)
if np > n:
return None
permutationDict = {}
for i in range(n-(np-1)):
comparee = longString[i:i+np]
if __is_permutation(piece,comparee):
if comparee not in permutationDict:
permutationDict[comparee] = []
permutationDict[comparee].append(i)
return permutationDict
if __name__ == "__main__":
print(__is_permutation("tagc","tgat"))
print(return_permutations("tagc","atgc"))
|
ff1ce1557342706b401042efc6b213e0e1bbd9ef | chrisgzf/AoC | /2019/Day06_Part2.py | 1,047 | 3.515625 | 4 | from collections import defaultdict
with open("Day06_Input") as f:
orbits = f.readlines()
orbits = list(map(lambda x: x.strip(), orbits))
print(len(orbits))
edges = defaultdict(list)
vertices = set()
for orbit in orbits:
orbitee, orbiter = orbit.split(")")
edges[orbiter].append(orbitee)
vertices.add(orbitee)
vertices.add(orbiter)
def search_root(orbiter, traversed):
# i cannot write a DFS properly gg
if edges[orbiter] == []:
return False
results = []
traversed = traversed.copy()
for edge in edges[orbiter]:
if edge == "COM":
traversed.append(orbiter)
results.append(traversed)
else:
traversed.append(orbiter)
results.append(search_root(edge, traversed))
if any(results):
return list(filter(None, results))[0]
else:
return False
san_com = set(search_root("SAN", list()))
you_com = set(search_root("YOU", list()))
common = san_com & you_com
print(len((san_com - common) | (you_com - common)) - 2) |
569202e0b336f912e1e9dbfa29a5f2aea7c8f2b5 | JiHoon-JK/Sparta_py | /list.py | 290 | 3.609375 | 4 | a = ['사과','감','감','배','사과','포도','딸기','사과','배']
def count_list(a_list):
result={}
for element in a_list:
if element in result:
result[element] += 1
else:
result[element] = 1
return result
print(count_list(a)) |
c8bc084cc06c30404dbb8d5cd6653dd74d007405 | KatePavlovska/python-laboratory | /laboratory1&2update/Lab2_Task2_calculation_pavlovska_km_93.py | 640 | 4.25 | 4 | print("Павловська Катерина. КМ-93. Варіант 14. ")
print("Task2: Given an integer N (> 0), which is a degree of 2: N = 2K. Finding an integer K is an exponent of this degree.")
print()
import re
re_integer = re.compile("^[-+]?\d+$")
def validator(pattern, promt):
text = input(promt)
while not bool(pattern.match(text)):
text = input(promt)
return text
number = int( validator( re_integer, "Input number: "))
counter = 0
while number % 2 == 0:
number /= 2
counter += 1
if number != 1:
print("This number is not a power of 2!")
else:
print("This number is", counter, " power")
|
2e1addf3b25bf2df65ff1bcf6d223d5b5520e32b | KatePavlovska/python-laboratory | /laboratory1/task2.py | 1,125 | 4.09375 | 4 | print('Павловська Катерина. КМ-93. Варіант №14.')
print('You are welcomed by the guessing program')
Petails=int(input("Number of petails: "))
while Petails<=3:
print("The given values are incorrect, which flower does not exist, please try again")
Petails=int(input("Number of petals: "))
Version=int(input("If you want to start guessing with likes press - 1, if with dislikes press - 2"))
if Version==1:
print('You started guessing with loves')
elif Version==2:
print('You started guessing with dislikes')
while Version!=1 and Version!=2:
print("You have entered an incorrect value if you want to start guessing with likes press-1, if with dislikes press-2 ")
Version = int(input("If you want to start guessing with likes press - 1, if with dislikes press - 2"))
if Petails//2==0 and Version==1:
print('Your result of divination does not like')
elif Petails//2!=0 and Version==1:
print("Your divination result loves")
elif Petails//2==0 and Version==2:
print('Your divination result loves')
elif Petails//2!=0 and Version==2:
print('Your divination result loves')
print("The end") |
7b573852d78943dc327ecdb8d9a87fb987dffae9 | fingerroll/wip | /strobogrammatic-number-II/s1.py | 847 | 3.5 | 4 | # Forget '00' can be a number
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
sbg = ['69', '88','11', '96', '00']
if n == 0:
return []
if n == 1:
return ['0', '8', '1']
if n == 2:
return sbg[:4]
def dfs(n):
if n == 1:
return ['0', '8', '1']
if n == 2:
return sbg
ret = []
res = dfs(n - 2)
for s in res:
for w in sbg:
ret.append(w[0] + s + w[1])
return ret
res = dfs(n)
# remove sbgs with '0' in front
res = [s for s in res if not s.startswith('0')]
return res
|
25e72fea728d1df3fef1c0a0378c355144ed4536 | fingerroll/wip | /count-univalue-subtree/s1.py | 1,285 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
def dfs(root):
if root.left is None and root.right is None:
return 1, True
left_count, right_count = 0, 0
including_left, including_right, including_root = True, True, True
if root.left is not None:
left_count, including_left = dfs(root.left)
if root.val != root.left.val or not including_left:
including_root = False
if root.right is not None:
right_count, including_right = dfs(root.right)
if root.val != root.right.val or not including_right:
including_root = False
if including_root:
count = left_count + right_count + 1
else:
count = left_count + right_count
return count, including_root
count, _= dfs(root)
return count
|
92c83d1a0b882aa143205809bfecbbaeac395118 | karishma347/gas-modules | /bisection.py | 477 | 3.65625 | 4 | # a python module to calculate bisection method
# Karishma Bharti, Srisha Rao M V, IISc, July 2020
# Global conventions and variables
# a,b are guessing values
# func is the function
def bis(a,b,func):
if (func(a) * func(b)>=0):
print("wrong assumption")
return
c=a
while((b-a)>=0.01):
c= (a+b)/2
if(func(c) == 0.0):
break
if(func(c)*func(a)<0):
b=c
else:
a=c
return (a+b)/2 |
661937904645917e033c55f797121b6a05a543d0 | dm-fedorov/python3book | /2-ed/ch12/class_fun.py | 779 | 3.734375 | 4 | # class_fun.py
# Обновленная функция, которая обрабатывает объект типа (класса) Address.
# Вывести адрес на экран:
def print_address(address):
print(address.name)
if len(address.line1) > 0:
print(address.line1)
if len(address.line2) > 0:
print(address.line2)
print(address.city + ", " + address.zip)
# Определяем "шаблон" (класс) для адреса
class Address:
pass
# Создаем экземпляр (объект) класса (типа) Address:
home = Address()
# Задаем поля объекта:
home.name = "Иван Иванов"
home.line1 = "Улица"
home.line2 = "Район"
home.city = "СПб"
home.zip = "50125"
print_address(home)
|
e7c5bc523427257158b6eab611d28d05775c7962 | dm-fedorov/python3book | /3-ed/ch4/mypr.py | 221 | 3.59375 | 4 | # mypr.py
def func(x):
return x ** 2 + 7
#x = int(input("Введите значение: "))
#print(func(x))
if __name__ == "__main__":
x = int(input("Введите значение: "))
print(func(x))
|
746562d02ebf880a258e307948343b656e417076 | dm-fedorov/python3book | /3-ed/ch10/exception_08.py | 258 | 3.6875 | 4 | # exception_08.py
try:
x = int(input("Введите число: "))
print(5/x)
except ZeroDivisionError:
print("Ошибка деления на ноль!!!")
except ValueError:
print("Ошибка преобразования типа!!!")
|
21a2fbe709284990b8d486f7aabd79ddc269d4bf | AlexChesser/CIT590 | /04-travellingsalesman/cities.py | 2,041 | 4.28125 | 4 | def read_cities(file_name)
"""Read in the cities from the given file_name, and return them as a list
of four-tuples: [(state, city, latitude, longitude), ...] Use this as your
initial road_map, that is, the cycle Alabama → Alaska → Arizona → ... → Wyoming → Alabama."""
pass
def print_cities(road_map)
"""Prints a list of cities, along with their locations. Print only one or
two digits after the decimal point."""
pass
def compute_total_distance(road_map)
"""Returns, as a floating point number, the sum of the distances of all
the connections in the road_map. Remember that it's a cycle, so that (for example)
in the initial road_map, Wyoming connects to Alabama.."""
pass
def swap_adjacent_cities(road_map, index)
"""Take the city at location index in the road_map, and the city at location
index+1 (or at 0, if index refers to the last element in the list), swap their
positions in the road_map, compute the new total distance, and return the tuple
(new_road_map, new_total_distance)."""
pass
def swap_cities(road_map, index1, index2)
"""Take the city at location index in the road_map, and the city at location
index2, swap their positions in the road_map, compute the new total distance, and
return the tuple (new_road_map, new_total_distance). Allow the possibility that index1=index2,
and handle this case correctly."""
pass
def find_best_cycle(road_map)
"""Using a combination of swap_cities and swap_adjacent_cities, try 10000 swaps,
and each time keep the best cycle found so far. After 10000 swaps, return the best cycle found
so far."""
pass
def print_map(road_map)
"""Prints, in an easily understandable format, the cities and their connections,
along with the cost for each connection and the total cost."""
pass
def main()
"""Reads in and prints out the city data, then creates the "best"
cycle and prints it out."""
pass
if __name__ == '__main__':
main() |
5b4f1d86618af532f251f8c6381cc351196dd215 | VictorMacleury/Questionario | /Questionario.py | 1,689 | 4.03125 | 4 | print()
print('Digite a letra respectiva à resposta que você considera como correta.')
print()
perguntas = {
'pergunta 1' : {
'pergunta' : 'Quanto é 1 + 1?',
'respostas' : {'a' : '1', 'b' : '2', 'c' : '3', 'd' : '4' },
'resposta certa' : 'b',
},
'pergunta 2' : {
'pergunta' : 'Quanto é 10 + 1?',
'respostas' : {'a': '11', 'b': '22', 'c': '13', 'd': '6'},
'resposta certa' : 'a',
},
'pergunta 3' : {
'pergunta' : 'Quanto é 2 * 2?',
'respostas' : {'a': '8', 'b': '22', 'c': '3', 'd': '4'},
'resposta certa' : 'd',
},
'pergunta 4' : {
'pergunta' : 'Quanto é 4 / 2?',
'respostas' : {'a': '3', 'b': '4', 'c': '2', 'd': '0'},
'resposta certa' : 'c',
},
'pergunta 5' : {
'pergunta' : 'Quanto é 0 + 0?',
'respostas' : {'a': '0', 'b': '2', 'c': '3', 'd': '4'},
'resposta certa' : 'a',
},
}
respostas_certas = 0
for pk, pv in perguntas.items():
print(f'{pk}: {pv["pergunta"]}')
print('Respostas: ')
for rk, rv in pv['respostas'].items():
print(f'{rk} : {rv}')
resposta_usuario = input('Sua resposta: ')
print()
if resposta_usuario == pv['resposta certa']:
respostas_certas += 1
qnt_perguntas = len(perguntas)
porcentagem_acerto = respostas_certas / qnt_perguntas * 100
print()
print(f'Você acertou {respostas_certas} respostas!')
print()
print(f'Sua porcentagem de acerto foi {porcentagem_acerto}%!')
print()
if porcentagem_acerto >= 70:
print('Você está aprovado!')
else:
print('Você está reprovado!')
|
0f723850be01c3ca714cabe90672bc83cbfe09ee | mrbilal4972/Number-Guessing-Game | /main.py | 1,076 | 4.09375 | 4 | import random
randNo = random.randint(1,100)
userGuess = None
totalGuesses = 0
# Loop runs until guess matched
while randNo!=userGuess:
try: # Try box handle the invalid input from user, like: alphbet or special character
userGuess = int(input("Guess the number between 1 to 100: "))
if randNo != userGuess:
if userGuess>randNo:
print("Your guess is wrong, Select the smaller number")
else:
print("Your guess is wrong, Select the Larger number")
else:
print("Congratulations!! Your guess is correct")
totalGuesses += 1
except Exception as e:
print("Invalid Input!! Please Enter Valid Number")
print(f'''you got the correct answer after "{totalGuesses}" Guesses''')
# If Highest score was made it will stored in file hiScore.txt
with open("hiScore.txt") as f:
prevScore = int(f.read())
if totalGuesses<prevScore:
print("you Broke the Highest Score")
newScore = str(totalGuesses)
with open("hiScore.txt", 'w') as f:
f.write(newScore) |
d6395521d2f7816d6d0329e8feefad2e373a2397 | ml4026/Assignment1-Answer | /RLalgs/pi.py | 4,432 | 3.84375 | 4 | import numpy as np
from RLalgs.utils import action_evaluation
def policy_iteration(env, gamma, max_iteration, theta):
"""
Implement Policy iteration algorithm.
Inputs:
env: OpenAI Gym environment.
env.P: dictionary
P[state][action] is list of tuples. Each tuple contains probability, nextstate, reward, terminal
probability: float
nextstate: int
reward: float
terminal: boolean
env.nS: int
number of states
env.nA: int
number of actions
gamma: float
Discount factor.
max_iteration: int
The maximum number of iterations to run before stopping.
theta: float
The threshold of convergence.
Outputs:
V: numpy.ndarray
policy: numpy.ndarray
numIterations: int
"""
V = np.zeros(env.nS)
policy = np.zeros(env.nS, dtype = np.int32)
policy_stable = False
numIterations = 0
while not policy_stable and numIterations < max_iteration:
#Implement it with function policy_evaluation and policy_improvement
############################
# YOUR CODE STARTS HERE
V = policy_evaluation(env, policy, gamma, theta)
policy, policy_stable = policy_improvement(env, V, policy, gamma)
# YOUR CODE ENDS HERE
############################
numIterations += 1
return V, policy, numIterations
def policy_evaluation(env, policy, gamma, theta):
"""
Evaluate the value function from a given policy.
Inputs:
env: OpenAI Gym environment.
env.P: dictionary
env.nS: int
number of states
env.nA: int
number of actions
gamma: float
Discount factor.
policy: numpy.ndarray
The policy to evaluate. Maps states to actions.
theta: float
The threshold of convergence.
Outputs:
V: numpy.ndarray
The value function from the given policy.
"""
############################
# YOUR CODE STARTS HERE
V = np.zeros(env.nS)
delta = theta
while delta >= theta:
delta = 0
for s in range(env.nS):
temp = V[s]
t_V = 0
models = env.P[s][policy[s]]
for model in models:
prob, next_state, reward, terminal = model
t_V += prob * (reward + gamma * V[next_state])
V[s] = t_V
delta = max(delta, abs(temp - V[s]))
# YOUR CODE ENDS HERE
############################
return V
def policy_improvement(env, value_from_policy, policy, gamma):
"""
Given the value function from policy, improve the policy.
Inputs:
env: OpenAI Gym environment
env.P: dictionary
P[state][action] is tuples with (probability, nextstate, reward, terminal)
probability: float
nextstate: int
reward: float
terminal: boolean
env.nS: int
number of states
env.nA: int
number of actions
value_from_policy: numpy.ndarray
The value calculated from the policy
policy: numpy.ndarray
The previous policy.
gamma: float
Discount factor.
Outputs:
new policy: numpy.ndarray
An array of integers. Each integer is the optimal action to take
in that state according to the environment dynamics and the
given value function.
policy_stable: boolean
True if the "optimal" policy is found, otherwise false
"""
############################
# YOUR CODE STARTS HERE
policy_stable = True
for s in range(env.nS):
temp = policy[s]
q = np.zeros(env.nA)
for a in range(env.nA):
models = env.P[s][a]
for model in models:
prob, next_state, reward, terminal = model
q[a] += prob * (reward + gamma * value_from_policy[next_state])
policy[s] = np.argmax(q)
if temp != policy[s]:
policy_stable = False
# YOUR CODE ENDS HERE
############################
return policy, policy_stable |
93081ee785e71c16e56f78767a316b99038b4b25 | Nerhox1983/studio_python | /capitulo02/Reto0203.py | 920 | 3.734375 | 4 | #Ejercicio 2.1. Aplicando las reglas matemáticas de asociatividad, decidir cuáles de las siguientes
#expresiones son iguales entre sí:
import FuncionesNumeros02
Numero10 = 10.0
Numero100 = 100.0
Numero1000 = 1000.0
resultado1 = FuncionesNumeros02.CalcularReto0201PuntoA(Numero10, Numero100, Numero1000)
resultado2 = FuncionesNumeros02.CalcularReto0201PuntoB(Numero10, Numero100, Numero1000)
resultado3 = FuncionesNumeros02.CalcularReto0201PuntoC(Numero10, Numero100, Numero1000)
resultado4 = FuncionesNumeros02.CalcularReto0201PuntoD(Numero10, Numero100, Numero1000)
resultado5 = FuncionesNumeros02.CalcularReto0201PuntoE(Numero100)
resultado6 = FuncionesNumeros02.CalcularReto0201PuntoF(Numero100)
print ("Resultado1=> ", resultado1)
print ("Resultado2=> ", resultado2)
print ("Resultado3=> ", resultado3)
print ("Resultado4=> ", resultado4)
print ("Resultado5=> ", resultado5)
print ("Resultado6=> ", resultado6) |
6c094694aa448680ad878943075247641e79d744 | ooobsidian/shu_spider | /thread.py | 532 | 3.6875 | 4 | # coding=utf-8
import threading
import time
class myThread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
def run(self):
time.sleep(2)
print('Thread {} is running.'.format(self.i))
time.sleep(2)
return
if __name__ == '__main__':
print "进入一页"
threads = []
for i in range(1, 6):
t = myThread(i)
t.start()
threads.append(t)
for t in threads:
t.join()
print '进入下一页' |
c8721544d8d9cb6e3835f59d2a7bd14a36dee70b | dortmans/ComputerVision | /VideoCapture.py | 1,521 | 3.609375 | 4 | import numpy as np
import cv2
#we are capturing image from the standard cameras
# 0,1,2,... (since we are using the laptop capera , we use 0 , else we use 1,2..)
#Note: we need to create a VideoCapture object to capture video in OpenCV
cap = cv2.VideoCapture(0) #this will create a streaming video via the lappy cam
#we can apply processing on this video frame/frame and apply computations accordingly
#we are interesting in caputuring camera frames from several cameras in the setup
#and detect the objects and their location, output as a matrix,as give
# plotting in a graph
#Challenges:
#Trigerring frame capture at the same time from these cameras
#Converting them in to unified co-ordinates
#providing a 3D view of these objects
#plot the orientation of these objects in this unified co-ordinate system
#Detection
# 1. detect robots using red circles mounted on these cameras
# 2. detect by learning the shape of these robots by training negative
# and positive images
# 3. Proximity information specific to individual cameras
while True:
#Capturing the images frames by frames
ret,frame = cap.read() #the read method of the VideoCapture Object
#returns a frame
#we convert each frame into a grayscale
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
#displaying the resulting frame
cv2.imshow('frame',gray)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindows()
for i in range(1,4):
cv2.waitKey(1)
|
024213abf18bf6c878a42111c221612f12cce7b3 | dortmans/ComputerVision | /trainCV/gaussianBlue_Color.py | 953 | 3.5 | 4 | #Gaussian Blur Example using scipy
#Color
#We individually apply the filter to individual channels
from PIL import Image
from numpy import *
from scipy.ndimage import filters
from pylab import *
im = array(Image.open("riaz.jpg"))
#Note: Here is the standard deviation value
#more the sigma , more the blur
blur2 = zeros(im.shape)
for i in range(3):
blur2[:,:,i] = filters.gaussian_filter(im[:,:,i],2)
blur2 = uint8(blur2)
blur5 = zeros(im.shape)
for i in range(3):
blur5[:,:,i] = filters.gaussian_filter(im[:,:,i],5)
blur5 = uint8(blur5)
blur10 = zeros(im.shape)
for i in range(3):
blur10[:,:,i] = filters.gaussian_filter(im[:,:,i],10)
blur10 = uint8(blur10)
figure("BW Gaussain Blur")
plt.subplot(141)
plt.title("Original Image")
plt.imshow(im)
plt.subplot(142)
plt.title("Blur : 2")
plt.imshow(blur2)
plt.subplot(143)
plt.title("Blur : 5")
plt.imshow(blur5)
plt.subplot(144)
plt.title("Blur : 10")
plt.imshow(blur10)
show()
|
8ae0d4ef38c6072949606f126e9ba9ae16f9a183 | dortmans/ComputerVision | /trainCV/unsharp_mask.py | 526 | 3.515625 | 4 | #Program to demonstrate unsharp masking
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
from scipy.ndimage import filters
im = np.array(Image.open("lena_noisy.png").convert("L"))
blur = filters.gaussian_filter(im,10)
sharp = im - blur
plt.figure("Unsharp masking Example")
plt.gray()
plt.subplot(131)
plt.title("Original")
plt.imshow(im)
plt.subplot(132)
plt.title("Gaussian Blur Image")
plt.imshow(blur)
plt.subplot(133)
plt.title("Blur Subtracted Image")
plt.imshow(sharp)
plt.show()
|
40db83e086d8857643c10447811873e55740797b | kajalubale/PythonTutorial | /While loop in python.py | 535 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# Assuming code inside for and while loop is same
# Both While and for loop takes almost equal time
# As both converted into same machine code
# So you can use any thing which is convenient |
a991a9d07955fe00dad9a2b46fd32503121249e8 | kajalubale/PythonTutorial | /For loop in python.py | 1,891 | 4.71875 | 5 |
################### For Loop Tutorial ###############
# A List
list1 = ['Vivek', 'Larry', 'Carry', 'Marie']
# To print all elements in list
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can do same thing easily using for loop
# for loop runs len(list1) times
# each time item is equal to one elemrnt of list from starting
for item in list1:
print(item)
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can iterate tuple, list of lists, dictionary,
# and many more containers using for loop
# Examples :
# Iterating tuple
list1 = ('Vivek', 'Larry', 'Carry', 'Marie')
for item in list1:
print(item)
# Output :
# Vivek
# Larry
# Carry
# Marie
# Iterating a list of lists
list1 = [["Vivek", 1], ["Larry", 2],
["Carry", 6], ["Marie", 250]]
for item in list1:
print(item)
# Output :
# ['Vivek', 1]
# ['Larry', 2]
# ['Carry', 6]
# ['Marie', 250]
# Iterating a dictionary
dict1 = dict(list1)
print(dict1)
# Output :
# {'Vivek': 1, 'Larry': 2, 'Carry': 6, 'Marie': 250}
for item in dict1:
print(item) # It will print only keys
# Output :
# Vivek
# Larry
# Carry
# Marie
# to print both key and value while iterating dictionary
for item, lollypop in dict1.items():
print(item, "and lolly is ", lollypop)
# Output :
# Vivek and lolly is 1
# Larry and lolly is 2
# Carry and lolly is 6
# Marie and lolly is 250
# Quiz time :
# Ques : Create a list if item in list is numerical
# and number is greater than 6
# Solution
items = [int, float, "HaERRY", 5, 3, 3, 22, 21, 64, 23, 233, 23, 6]
for item in items:
if str(item).isnumeric() and item >= 6:
print(item)
# Remember str(item).isnumeric() is correct
# item.isnumeric() is wrong
# Output :
# 22
# 21
# 64
# 23
# 233
# 23
# 6
|
2a3ca27dd93b4c29a43526fa2894f79f38280b82 | kajalubale/PythonTutorial | /41.join function.py | 971 | 4.34375 | 4 | # What is the join method in Python?
# "Join is a function in Python, that returns a string by joining the elements of an iterable,
# using a string or character of our choice."
# In the case of join function, the iterable can be a list, dictionary, set, tuple, or even a string itself.
# The string that separates the iterations could be anything.
# It could just be a comma or a full-length string.
# We can even use a blank space or newline character (/n ) instead of a string.
lis = ["john","cena","khali","randy","ortan","sheamus","jinder mahal"]
# suppose i want to write like john and cena and khali and so no , then we write it as
# for item in lis:
# print(item,"and", end="")# end it used to ignore new line
# simply we can use join method
a = " and ".join(lis)
print(a)
b = " , ".join(lis)
print(b)
#output :
# john and cena and khali and randy and ortan and sheamus and jinder mahal
# john , cena , khali , randy , ortan , sheamus , jinder mahal |
767fc168ca7b5c78be91f3aa94302fc009d73e49 | kajalubale/PythonTutorial | /35.Recursion.py | 1,457 | 4.5625 | 5 | # Recursion: Using Function inside the function, is known as recursion
def print_2(str):
print("This is",str)
print_2("kajal")
# output: This is kajal
# but if i used print_2("str") inside the function it shows Recursion error.
# def print_2(str):
# print_2(str)
# print("This is",str)
# print_2("kajal")
# output : [Previous line repeated 996 more times]
# RecursionError: maximum recursion depth exceeded
# Factorial program using Recursive and iterative
# n!= n*n-1*n-2*n-3......1
# n!=n*(n-1)!
def factorial_iterative(n):
'''
:param n: integer
:return: n * n-1 * n-2.....1
'''
fac=1
for i in range(n):
fac=fac*(i+1)
return fac
def factorial_Recursion(n):
'''
:param n: Integer
:return: n * n-1 *n-2.....1
'''
if n==1:
return 1;
else:
return n * factorial_Recursion(n-1)
# 5 * factorial_Recursion(4)
# 5 * 4 * factorial_Recursion(3)
# 5 * 4 * 3 * factorial_Recursion(2)
# 5 * 4 * 3 * 2 * factorial_Recursion(1)
# 0 1 1 2 3 5 8 13
def fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
number=int(input("Enter the number:"))
print("Factorial using iterative : ",factorial_iterative(number))
print("Factorial using Recursion : ",factorial_Recursion(number))
print("Fibonacci of number : ",fibonacci(number)) |
08e1c60124239203af2859a726c052e5775c2836 | alin719/cs221-project | /tokenscanner.py | 21,454 | 3.578125 | 4 | """
* File: tokenscanner.cpp
* ----------------------
* Implementation for the TokenScanner class.
*
* @version 2014/10/08
* - removed 'using namespace' statement
"""
import string
"""
* File: tokenscanner.h
* --------------------
* This file exports a <code>TokenScanner</code> class that divides
* a string into individual logical units called <b><i>tokens</i></b>.
"""
#ifndef _tokenscanner_h
#define _tokenscanner_h
#include <iostream>
#include <string>
#include "private/tokenpatch.h"
"""
* Type: TokenType
* ---------------
* This enumerated type defines the values of the
* <code>getTokenType</code> method.
"""
class TokenType:
SEPARATOR = 0
WORD = 1
NUMBER = 2
STRING = 3
OPERATOR = 4
"""
* Class: TokenScanner
* -------------------
* This class divides a string into individual tokens. The typical
* use of the <code>TokenScanner</code> class is illustrated by the
* following pattern, which reads the tokens in the string variable
* <code>input</code>:
*
*<pre>
* TokenScanner scanner(input);
* while (scanner.hasMoreTokens()):
* string token = scanner.nextToken();
* ... process the token ...
*
*</pre>
*
* The <code>TokenScanner</code> class exports several additional methods
* that give clients more control over its behavior. Those methods are
* described individually in the documentation.
"""
class TokenScanner:
"""
* Constructor: TokenScanner
* Usage: TokenScanner scanner;
* TokenScanner scanner(str);
* TokenScanner scanner(infile);
* ------------------------------------
* Initializes a scanner object. The initial token stream comes from
* the specified string or input stream, if supplied. The default
* constructor creates a scanner with an empty token stream.
"""
def TokenScanner():
initScanner()
setInput("")
def TokenScanner(std::string str):
initScanner()
setInput(str)
def TokenScanner(std::istream & infile):
initScanner()
setInput(infile)
"""
* Destructor: ~TokenScanner
* -------------------------
* Deallocates the storage associated with this scanner.
"""
virtual ~TokenScanner()
"""
* Method: setInput
* Usage: scanner.setInput(str)
* scanner.setInput(infile)
* --------------------------------
* Sets the token stream for this scanner to the specified string or
* input stream. Any previous token stream is discarded.
"""
def setInput(std::string str)
def setInput(std::istream & infile)
"""
* Method: hasMoreTokens
* Usage: if (scanner.hasMoreTokens()) ...
* ---------------------------------------
* Returns <code>true</code> if there are additional tokens for this
* scanner to read.
"""
bool hasMoreTokens()
"""
* Method: nextToken
* Usage: token = scanner.nextToken()
* -----------------------------------
* Returns the next token from this scanner. If <code>nextToken</code>
* is called when no tokens are available, it returns the empty string.
"""
std::string nextToken()
"""
* Method: saveToken
* Usage: scanner.saveToken(token)
* --------------------------------
* Pushes the specified token back into this scanner's input stream.
* On the next call to <code>nextToken</code>, the scanner will return
* the saved token without reading any additional characters from the
* token stream.
"""
def saveToken(std::string token)
"""
* Method: getPosition
* Usage: int pos = scanner.getPosition()
* ---------------------------------------
* Returns the current position of the scanner in the input stream.
* If <code>saveToken</code> has been called, this position corresponds
* to the beginning of the saved token. If <code>saveToken</code> is
* called more than once, <code>getPosition</code> returns -1.
"""
int getPosition() const
"""
* Method: ignoreWhitespace
* Usage: scanner.ignoreWhitespace()
* ----------------------------------
* Tells the scanner to ignore whitespace characters. By default,
* the <code>nextToken</code> method treats whitespace characters
* (typically spaces and tabs) just like any other punctuation mark
* and returns them as single-character tokens.
* Calling
*
*<pre>
* scanner.ignoreWhitespace()
*</pre>
*
* changes this behavior so that the scanner ignore whitespace characters.
"""
def ignoreWhitespace()
"""
* Method: ignoreComments
* Usage: scanner.ignoreComments()
* --------------------------------
* Tells the scanner to ignore comments. The scanner package recognizes
* both the slash-star and slash-slash comment format from the C-based
* family of languages. Calling
*
*<pre>
* scanner.ignoreComments()
*</pre>
*
* sets the parser to ignore comments.
"""
def ignoreComments()
"""
* Method: scanNumbers
* Usage: scanner.scanNumbers()
* -----------------------------
* Controls how the scanner treats tokens that begin with a digit. By
* default, the <code>nextToken</code> method treats numbers and letters
* identically and therefore does not provide any special processing for
* numbers. Calling
*
*<pre>
* scanner.scanNumbers()
*</pre>
*
* changes this behavior so that <code>nextToken</code> returns the
* longest substring that can be interpreted as a real number.
"""
def scanNumbers()
"""
* Method: scanStrings
* Usage: scanner.scanStrings()
* -----------------------------
* Controls how the scanner treats tokens enclosed in quotation marks. By
* default, quotation marks (either single or double) are treated just like
* any other punctuation character. Calling
*
*<pre>
* scanner.scanStrings()
*</pre>
*
* changes this assumption so that <code>nextToken</code> returns a single
* token consisting of all characters through the matching quotation mark.
* The quotation marks are returned as part of the scanned token so that
* clients can differentiate strings from other token types.
"""
def scanStrings()
"""
* Method: addWordCharacters
* Usage: scanner.addWordCharacters(str)
* --------------------------------------
* Adds the characters in <code>str</code> to the set of characters
* legal in a <code>WORD</code> token. For example, calling
* <code>addWordCharacters("_")</code> adds the underscore to the
* set of characters that are accepted as part of a word.
"""
def addWordCharacters(std::string str)
"""
* Method: isWordCharacter
* Usage: if (scanner.isWordCharacter(ch)) ...
* -------------------------------------------
* Returns <code>true</code> if the character is valid in a word.
"""
bool isWordCharacter(char ch) const
"""
* Method: addOperator
* Usage: scanner.addOperator(op)
* -------------------------------
* Defines a new multicharacter operator. Whenever you call
* <code>nextToken</code> when the input stream contains operator
* characters, the scanner returns the longest possible operator
* string that can be read at that point.
"""
def addOperator(std::string op)
"""
* Method: verifyToken
* Usage: scanner.verifyToken(expected)
* -------------------------------------
* Reads the next token and makes sure it matches the string
* <code>expected</code>. If it does not, <code>verifyToken</code>
* throws an error.
"""
def verifyToken(std::string expected)
"""
* Method: getTokenType
* Usage: TokenType type = scanner.getTokenType(token)
* ----------------------------------------------------
* Returns the type of this token. This type will match one of the
* following enumerated type constants: <code>EOF</code>,
* <code>SEPARATOR</code>, <code>WORD</code>, <code>NUMBER</code>,
* <code>STRING</code>, or <code>OPERATOR</code>.
"""
TokenType getTokenType(std::string token) const
"""
* Method: getChar
* Usage: int ch = scanner.getChar()
* ----------------------------------
* Reads the next character from the scanner input stream.
"""
def getChar():
return isp.get()
"""
* Method: ungetChar
* Usage: scanner.ungetChar(ch)
* -----------------------------
* Pushes the character <code>ch</code> back into the scanner stream.
* The character must match the one that was read.
"""
def ungetChar(int ch):
"""
* Method: getStringValue
* Usage: string str = scanner.getStringValue(token)
* --------------------------------------------------
* Returns the string value of a token. This value is formed by removing
* any surrounding quotation marks and replacing escape sequences by the
* appropriate characters.
"""
std::string getStringValue(std::string token) const
""" Private section"""
"""*********************************************************************/
""" Note: Everything below this point in the file is logically part """
""" of the implementation and should not be of interest to clients. """
"""*********************************************************************/
"""
* Private type: StringCell
* ------------------------
* This type is used to construct linked lists of cells, which are used
* to represent both the stack of saved tokens and the set of defined
* operators. These types cannot use the Stack and Lexicon classes
* directly because tokenscanner.h is an extremely low-level interface,
* and doing so would create circular dependencies in the .h files.
"""
class StringCell:
def __init__():
strr
link
class NumberScannerState:
INITIAL_STATE = 0
BEFORE_DECIMAL_POINT = 1
AFTER_DECIMAL_POINT = 2
STARTING_EXPONENT = 3
FOUND_EXPONENT_SIGN = 4
SCANNING_EXPONENT = 5
FINAL_STATE = 6
buffer """ The original argument string"""
isp """ The input stream for tokens """
bool stringInputFlag """ Flag indicating string input"""
bool ignoreWhitespaceFlag """ Scanner ignores whitespace """
bool ignoreCommentsFlag """ Scanner ignores comments """
bool scanNumbersFlag """ Scanner parses numbers """
bool scanStringsFlag """ Scanner parses strings """
std::string wordChars """ Additional word characters """
StringCell *savedTokens """ Stack of saved tokens """
StringCell *operators """ List of multichar operators """
""" Private method prototypes"""
def initScanner()
def skipSpaces()
std::string scanWord()
std::string scanNumber()
def scanString():
std::string token = ""
char delim = isp->get()
token += delim
escape = False
while (true):
int ch = isp->get()
if (ch == EOF) error("scanString: found unterminated string")
if (ch == delim and not escape) break
escape = (ch == '\\') and not escape
token += ch
return token + delim
bool isOperator(std::string op)
bool isOperatorPrefix(std::string op)
def setInput(strr):
stringInputFlag = true
buffer = strr
isp = new std::istringstream(buffer)
savedTokens = NULL
def setInput(std::istream & infile):
stringInputFlag = false
isp = &infile
savedTokens = NULL
bool def hasMoreTokens():
std::string token = nextToken()
saveToken(token)
return (token != "")
std::string def nextToken():
if (self.savedTokens != NULL):
cp = self.savedTokens
token = cp.strr
savedTokens = cp.link
# delete cp ??
return token
while (true):
if (ignoreWhitespaceFlag):
skipSpaces()
ch = self.isp.get()
if (ch == '/' and ignoreCommentsFlag):
ch = isp.get()
if (ch == '/'):
while (true):
ch = isp.get()
if (ch == '\n' or ch == '\r' or ch == EOF) break
continue
else if (ch == '*'):
int prev = EOF
while (true):
ch = isp->get()
if (ch == EOF or (prev == '*' and ch == '/')) break
prev = ch
continue
if (ch != EOF) isp->unget()
ch = '/'
if (ch == EOF) return ""
if ((ch == '"' or ch == '\'') and scanStringsFlag):
isp->unget()
return scanString()
if (ch.isdigit() and scanNumbersFlag):
isp.unget()
return scanNumber()
if (isWordCharacter(ch)):
isp.unget()
return scanWord()
std::string op = std::string(1, ch)
while (isOperatorPrefix(op)):
ch = isp->get()
if (ch == EOF) break
op += ch
while (op.length() > 1 and not isOperator(op)):
isp->unget()
op.erase(op.length() - 1, 1)
return op
def saveToken(token):
cp = StringCell()
cp.strr = token
cp.link = savedTokens
savedTokens = cp
def ignoreWhitespace():
ignoreWhitespaceFlag = true
def ignoreComments():
ignoreCommentsFlag = true
def scanNumbers():
scanNumbersFlag = true
def scanStrings():
scanStringsFlag = true
def addWordCharacters(str):
wordChars += str
def addOperator(op):
cp = StringCell()
cp.strr = op
cp.link = operators
operators = cp
def getPosition() const:
if (savedTokens == NULL):
return int(isp->tellg())
else:
return int(isp->tellg()) - savedTokens->str.length()
def isWordCharacter(ch):
return ch.isalnum or wordChars.find(ch) != std::string::npos
def verifyToken(std::string expected):
std::string token = nextToken()
if (token != expected):
error("def verifyToken: Found \"" + token + "\"" +
" when expecting \"" + expected + "\"")
def getTokenType(token):
if (token == ""):
return TokenType(EOF)
char ch = token[0]
if (isspace(ch)):
return self.SEPARATOR
if (ch == '"' or (ch == '\'' and token.length() > 1)):
return self.STRING
if (ch.isdigit()):
return self.NUMBER
if (isWordCharacter(ch)):
return self.WORD
return OPERATOR
def getStringValue(token):
strr = ""
start = 0
finish = len(token)
if (finish > 1 and (token[0] == '"' or token[0] == '\'')):
start = 1
finish -= 1
for i in xrange(start, finish):
char ch = token[i]
if (ch == '\\'):
ch = token[++i]
if (ch.isdigit() or ch == 'x'):
int base = 8
if (ch == 'x'):
base = 16
i++
int result = 0
int digit = 0
while (i < finish):
ch = token[i]
if (ch.isdigit()):
digit = ch - '0'
else if (ch.isalpha()):
digit = ch.toupper() - 'A' + 10
else:
digit = base
if (digit >= base) break
result = base * result + digit
i++
ch = char(result)
i--
else:
switchDict = {
'a': '\a',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
'"': '"',
'\'': '\'',
'\\': '\\'
}
ch = switchDict[ch]
strr += ch
return strr;
def ungetChar(int):
isp->unget();
""" Private methods"""
def initScanner():
ignoreWhitespaceFlag = false;
ignoreCommentsFlag = false;
scanNumbersFlag = false;
scanStringsFlag = false;
operators = NULL;
"""
* Implementation notes: skipSpaces
* --------------------------------
* Advances the position of the scanner until the current character is
* not a whitespace character.
"""
def skipSpaces():
while (true):
int ch = isp->get();
if (ch == EOF) return;
if (not isspace(ch)):
isp->unget();
return;
"""
* Implementation notes: scanWord
* ------------------------------
* Reads characters until the scanner reaches the end of a sequence
* of word characters.
"""
def scanWord():
token = "";
while (true):
ch = isp->get();
if (ch == EOF) break;
if (not isWordCharacter(ch)):
isp->unget();
break;
token += char(ch);
return token;
"""
* Implementation notes: scanNumber
* --------------------------------
* Reads characters until the scanner reaches the end of a legal number.
* The function operates by simulating what computer scientists
* call a finite-state machine. The program uses the variable
* <code>state</code> to record the history of the process and
* determine what characters would be legal at this point in time.
"""
std::string def scanNumber():
std::string token = "";
NumberScannerState state = NumberScannerState.INITIAL_STATE;
while (state != FINAL_STATE):
int ch = isp->get();
switch (state):
case NumberScannerState.INITIAL_STATE:
if (not ch.isdigit()):
error("def scanNumber: internal error: illegal call");
state = NumberScannerState.BEFORE_DECIMAL_POINT;
break;
case NumberScannerState.BEFORE_DECIMAL_POINT:
if (ch == '.'):
state = NumberScannerState.AFTER_DECIMAL_POINT;
else if (ch == 'E' or ch == 'e'):
state = NumberScannerState.STARTING_EXPONENT;
else if (not ch.isdigit()):
if (ch != EOF) isp->unget();
state = NumberScannerState.FINAL_STATE;
break;
case NumberScannerState.AFTER_DECIMAL_POINT:
if (ch == 'E' or ch == 'e'):
state = NumberScannerState.STARTING_EXPONENT;
else if (not ch.isdigit()):
if (ch != EOF) isp->unget();
state = NumberScannerState.FINAL_STATE;
break;
case NumberScannerState.STARTING_EXPONENT:
if (ch == '+' or ch == '-'):
state = NumberScannerState.FOUND_EXPONENT_SIGN;
else if (ch.isdigit()):
state = NumberScannerState.SCANNING_EXPONENT;
else:
if (ch != EOF) isp->unget();
isp->unget();
state = NumberScannerState.FINAL_STATE;
break;
case NumberScannerState.FOUND_EXPONENT_SIGN:
if (ch.isdigit()):
state = NumberScannerState.SCANNING_EXPONENT;
else:
if (ch != EOF) isp->unget();
isp->unget();
isp->unget();
state = NumberScannerState.FINAL_STATE;
break;
case NumberScannerState.SCANNING_EXPONENT:
if (not ch.isdigit()):
if (ch != EOF) isp->unget();
state = NumberScannerState.FINAL_STATE;
break;
default:
state = NumberScannerState.FINAL_STATE;
break;
if (state != NumberScannerState.FINAL_STATE):
token += char(ch);
return token;
"""
* Implementation notes: scanString
* --------------------------------
* Reads and returns a quoted string from the scanner, continuing until
* it scans the matching delimiter. The scanner generates an error if
* there is no closing quotation mark before the end of the input.
"""
"""
* Implementation notes: isOperator, isOperatorPrefix
* --------------------------------------------------
* These methods search the list of operators and return true if the
* specified operator is either in the list or a prefix of an operator
* in the list, respectively. This code could be made considerably more
* efficient by implementing operators as a trie.
"""
def isOperator(std::string op):
for (StringCell *cp = operators; cp != NULL; cp = cp->link):
if (op == cp->str) return true;
return false;
def isOperatorPrefix(std::string op):
for (StringCell *cp = operators; cp != NULL; cp = cp->link):
if (startsWith(cp->str, op)) return true;
return false;
|
da7bb658e7fbd4f41c8c8bc95977a90d5c0e8e04 | mondler/leetcode | /codes_python/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py | 1,851 | 3.96875 | 4 | # https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/
#
# 452. Minimum Number of Arrows to Burst Balloons
# Medium
#
# 706
#
# 38
#
# Add to List
#
# Share
# There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.
#
# An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.
#
# Example:
#
# Input:
# [[10,16], [2,8], [1,6], [7,12]]
#
# Output:
# 2
#
# Explanation:
# One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
#
#
# Accepted
# 53,441
# Submissions
# 110,902
# %%
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
n = len(points)
if n <= 1:
return n
points.sort(key=lambda a: a[1]) # sort by endpoint
count = 1
curr_st, curr_end = points[0]
for i in range(1, n):
next_st = points[i][0]
if next_st > curr_end:
count += 1
curr_st, curr_end = next_st, points[i][1]
return count
# %%
points = [[10, 16], [2, 8], [1, 6], [7, 12]]
Solution().findMinArrowShots(points)
|
1e852d48e55224e0054364b0ea6379f21e7f922c | mondler/leetcode | /codes_python/0098_Validate_Binary_Search_Tree.py | 3,211 | 4.25 | 4 | # https://leetcode.com/problems/validate-binary-search-tree/
# 98. Validate Binary Search Tree
# Medium
#
# 3220
#
# 458
#
# Add to List
#
# Share
# Given a binary tree, determine if it is a valid binary search tree(BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
#
#
# Example 1:
#
# 2
# / \
# 1 3
#
# Input: [2,1,3]
# Output: true
# Example 2:
#
# 5
# / \
# 1 4
# / \
# 3 6
#
# Input: [5,1,4,null,null,3,6]
# Output: false
# Explanation: The root node's value is 5 but its right child's value is 4.
# Accepted
# 601,578
# Submissions
# 2,212,734
# %%
def add(x: float, y: float) -> float:
return x + y
add(3, 4)
# %% divide and couquer
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def isValidNode(node: TreeNode, lower, upper) -> bool:
if not(node):
return True
if (upper is not None) and (node.val >= upper):
return False
if (lower is not None) and (node.val <= lower):
return False
validate_left = isValidNode(node.left, lower, node.val)
validate_right = isValidNode(node.right, node.val, upper)
return (validate_left and validate_right)
return isValidNode(root, None, None)
# %% in order search all nodes, and evaluate values
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not(root):
return True
storage = []
self.inOrder(root, storage)
for i in range(1, len(storage)):
if storage[i] <= storage[i - 1]:
return False
return True
# store nodes in binary search tree from low to high (left to right)
def inOrder(self, root, storage):
if root is None:
return
self.inOrder(root.left, storage)
storage.append(root.val)
self.inOrder(root.right, storage)
# %% evaluate during in order search of all nodes; best in this case
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
prev = None
def inOrder(root):
# assign nonlocal so that its value is changed properly
nonlocal prev
# search nodes in binary search tree from low to high
if not(root):
return True
if not(inOrder(root.left)):
# if rank order breaks on left tree, return False immediately
return False
if (prev is not None) and (root.val <= prev):
# return false when rank order breaks
return False
prev = root.val
return inOrder(root.right)
return inOrder(root)
# %% test cases
a = TreeNode(2)
b = TreeNode(1)
c = TreeNode(3)
a.left = b
a.right = c
Solution().isValidBST(a)
|
060eb25956088487b27ab6fe31077f73b6691857 | mondler/leetcode | /codes_python/0006_ZigZag_Conversion.py | 1,866 | 4.15625 | 4 | # 6. ZigZag Conversion
# Medium
#
# 2362
#
# 5830
#
# Add to List
#
# Share
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and make this conversion given a number of rows:
#
# string convert(string s, int numRows);
#
#
# Example 1:
#
# Input: s = "PAYPALISHIRING", numRows = 3
# Output: "PAHNAPLSIIGYIR"
# Example 2:
#
# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:
# P I N
# A L S I G
# Y A H R
# P I
# Example 3:
#
# Input: s = "A", numRows = 1
# Output: "A"
#
#
# Constraints:
#
# 1 <= s.length <= 1000
# s consists of English letters (lower-case and upper-case), ',' and '.'.
# 1 <= numRows <= 1000
class Solution:
def convert(self, s: str, numRows: int) -> str:
if (numRows == 1) or (numRows > len(s)):
return s
rows = [''] * numRows
row = 0
increment = 1
for c in s:
rows[row] += c
row += increment
if (row == (numRows - 1)) or (row == 0):
increment *= -1
return ''.join(rows)
def convert2(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for i in range(numRows)]
n = len(s)
for i in range(n):
j = i % (2 * numRows - 2)
if j < numRows:
rows[j].append(s[i])
else:
rows[2 * numRows - 2 - j].append(s[i])
sNew = [row[i] for row in rows for i in range(len(row))]
return ''.join(sNew)
# s = "PAYPALISHIRING"
s = "ABCDEFG"
numRows = 3
Solution().convert(s, numRows)
|
50b1e950818bf56fc22197c075e2d69cd6604e84 | mondler/leetcode | /codes_python/0093_Restore_IP_Addresses.py | 2,289 | 3.59375 | 4 | # https://leetcode.com/problems/restore-ip-addresses/description/
# 93. Restore IP Addresses
# Medium
#
# 1032
#
# 460
#
# Add to List
#
# Share
# Given a string containing only digits, restore it by returning all possible valid IP address combinations.
#
# Example:
#
# Input: "25525511135"
# Output: ["255.255.11.135", "255.255.111.35"]
# Accepted
# 176,544
# Submissions
# 517,275
# %% DFS + Backtracking ~44ms
class Solution(object):
valid_filed = {str(i) for i in range(256)}
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
# s = "25525511135"
n = len(s)
if n == 0:
return []
ans = set()
address = ['' for _ in range(4)]
def DFS(address, i_string, i_field):
# looking at i_string to fill in i_filed of address
if i_field == 4:
if i_string == n:
ans.add('.'.join(address))
return
for j in range(3):
if i_string + j + 1 <= n:
item = s[i_string:i_string + j + 1]
if item in self.valid_filed:
address[i_field] = item
DFS(address, i_string + j + 1, i_field + 1)
DFS(address, 0, 0)
return [item for item in ans]
# %% DFS ~80ms
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
# s = "25525511135"
n = len(s)
ans = set()
valid_filed = {str(i) for i in range(256)}
address = []
def DFS(address, i):
# print(address, i)
if len(address) == 4:
if i == n:
ans.add('.'.join(address))
return
for j in range(3):
# print('here')
if i + j + 1 <= n:
item = s[i:i + j + 1]
if item in valid_filed:
address.append(item)
DFS(address, i + j + 1)
del address[-1]
DFS(address, 0)
return [item for item in ans]
# %%
s = "010010"
s[4:10]
len(s)
Solution().restoreIpAddresses(s)
|
48a7ced84d9937622fe9a9d1bad59a127789a204 | mondler/leetcode | /codes_python/0435_Non-overlapping_Intervals.py | 2,914 | 4.09375 | 4 | # https://leetcode.com/problems/non-overlapping-intervals/description/
#
# 435. Non-overlapping Intervals
# Medium
#
# 782
#
# 28
#
# Add to List
#
# Share
# Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
#
#
#
# Example 1:
#
# Input: [[1,2],[2,3],[3,4],[1,3]]
# Output: 1
# Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
# Example 2:
#
# Input: [[1,2],[1,2],[1,2]]
# Output: 2
# Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
# Example 3:
#
# Input: [[1,2],[2,3]]
# Output: 0
# Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
#
#
# Note:
#
# You may assume the interval's end point is always bigger than its start point.
# Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
# Accepted
# 58,970
# Submissions
# 139,649
# %% count maximum number of intervals to keep
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
n = len(intervals)
if n == 0:
return 0
intervals.sort(key=lambda a: a[1]) # sort all by end point
count = 1 # automatically include the first one
i = 1
curr_st, curr_end = intervals[0]
# for interval in intervals[1:]:
# if (interval[0] >= curr_end):
# count += 1
# curr_st, curr_end = interval
while i < n:
next_start = intervals[i][0]
if (curr_st < next_start >= curr_end):
count += 1
curr_st = next_start
curr_end = intervals[i][1]
i += 1
return n - count
# %% count number of intervals to remove
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
n = len(intervals)
if n == 0:
return 0
intervals.sort(key=lambda a: (a[1], a[0])) # sort all by end point
count = 0 # count of interval to be removed
curr_st, curr_end = intervals[0]
for i in range(1, n):
next_start = intervals[i][0]
if next_start < curr_end: # if next item's start lower than previous end
count += 1
else:
curr_st, curr_end = intervals[i]
return count
# %%
intervals = [[1, 2], [2, 3], [3, 4], [1, 3]]
Solution().eraseOverlapIntervals(intervals)
intervals = [[1, 2], [1, 2], [1, 2]]
Solution().eraseOverlapIntervals(intervals)
intervals = [[1, 2], [2, 3]]
Solution().eraseOverlapIntervals(intervals)
intervals = [[0, 2], [1, 3], [2, 4], [3, 5], [4, 6]]
Solution().eraseOverlapIntervals(intervals)
|
da765a0a6123eb2623100ace81ff60feec44138f | mondler/leetcode | /codes_python/0074_search_a_2_d_matrix.py | 1,673 | 3.828125 | 4 | #
# @lc app=leetcode id=74 lang=python3
#
# [74] Search a 2D Matrix
#
# https://leetcode.com/problems/search-a-2d-matrix/description/
#
# algorithms
# Medium (45.32%)
# Likes: 8267
# Dislikes: 285
# Total Accepted: 856.7K
# Total Submissions: 1.9M
# Testcase Example: '[[1,3,5,7],[10,11,16,20],[23,30,34,60]]\n3'
#
# Write an efficient algorithm that searches for a value target in an m x n
# integer matrix matrix. This matrix has the following properties:
#
#
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than the last integer of the
# previous row.
#
#
#
# Example 1:
#
#
# Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
# Output: true
#
#
# Example 2:
#
#
# Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
# Output: false
#
#
#
# Constraints:
#
#
# m == matrix.length
# n == matrix[i].length
# 1 <= m, n <= 100
# -10^4 <= matrix[i][j], target <= 10^4
#
#
#
# @lc code=start
# from calendar import c
class Solution:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
# treat 2D array as 1D array
r, c = len(matrix), len(matrix[0])
low, high = 0, r * c - 1
while low <= high:
mid = low + (high - low) // 2
m, n = mid // c, mid % c
num = matrix[m][n]
if num == target:
return True
elif num > target:
high = mid - 1
else:
low = mid + 1
return False
# @lc code=end
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]]
target = 5
print(Solution().searchMatrix(matrix, target))
|
826f7fa5964a0e98a70f4f28b80a6c9d90ad9e32 | mondler/leetcode | /codes_python/0139_Word_Break.py | 1,881 | 3.78125 | 4 | # 139. Word Break
# Medium
#
# 8835
#
# 404
#
# Add to List
#
# Share
# Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
#
# Note that the same word in the dictionary may be reused multiple times in the segmentation.
#
#
#
# Example 1:
#
# Input: s = "leetcode", wordDict = ["leet","code"]
# Output: true
# Explanation: Return true because "leetcode" can be segmented as "leet code".
# Example 2:
#
# Input: s = "applepenapple", wordDict = ["apple","pen"]
# Output: true
# Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
# Note that you are allowed to reuse a dictionary word.
# Example 3:
#
# Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
# Output: false
#
#
# Constraints:
#
# 1 <= s.length <= 300
# 1 <= wordDict.length <= 1000
# 1 <= wordDict[i].length <= 20
# s and wordDict[i] consist of only lowercase English letters.
# All the strings of wordDict are unique.
# Accepted
# 938,570
# Submissions
# 2,151,276
# %%
# DP: find if substrings can be broken in segments from wordDict
class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
def canBreak(s, memory, wordDict):
if s in memory:
return memory[s]
if s in wordDict:
memory[s] = True
return True
for i in range(1, len(s)):
r = s[i:]
if r in wordDict and canBreak(s[0:i], memory, wordDict):
memory[s] = True
print(memory)
return True
memory[s] = False
return False
return canBreak(s, {}, wordDict)
# %%
s = "applepenapple"
wordDict = ["apple", "pen"]
print(Solution().wordBreak('applepenapple', wordDict))
|
502900e5c65ea2c9ba230f5b063fa2f679d34ee5 | mondler/leetcode | /codes_python/0611_Valid_Triangle_Number.py | 1,443 | 3.765625 | 4 | # 611. Valid Triangle Number
# Medium
#
# 2074
#
# 134
#
# Add to List
#
# Share
# Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
#
#
#
# Example 1:
#
# Input: nums = [2,2,3,4]
# Output: 3
# Explanation: Valid combinations are:
# 2,3,4 (using the first 2)
# 2,3,4 (using the second 2)
# 2,2,3
# Example 2:
#
# Input: nums = [4,2,3,4]
# Output: 4
#
#
# Constraints:
#
# 1 <= nums.length <= 1000
# 0 <= nums[i] <= 1000
# Accepted
# 119,606
# Submissions
# 243,331
# %%
class Solution:
def triangleNumber(self, nums: list[int]) -> int:
# nums = [4, 3, 1, 2]
res = 0
l = len(nums)
if l < 3:
return res
nums.sort(reverse=True)
# a <= b <= c, need a + b > c
for loc_c, c in enumerate(nums):
# for loc_b in range(loc_c + 1, l - 1):
loc_b = loc_c + 1
loc_a = l - 1
while (loc_b < loc_a):
b = nums[loc_b]
a = nums[loc_a]
if (a + b > c):
res += loc_a - loc_b
loc_b += 1
else:
loc_a -= 1
return res
# %%
nums = [2, 2, 3, 4]
print(Solution().triangleNumber(nums))
nums = [4, 2, 3, 4]
print(Solution().triangleNumber(nums))
nums = [20, 10, 3, 2, 1]
print(Solution().triangleNumber(nums))
|
4d04a766fc39870a8c8ea190150eced1325d39b8 | ohmahgawditbob/py-projects | /kinetic_energy_calculator.py | 201 | 3.875 | 4 | import math
vel = float(input("Velocity (m/s): "))
mass = float(input("Mass (kg): "))
energy_kinetic = 0.5*mass*(math.pow(vel, 2))
print("The Kinetic Energy is " + str(energy_kinetic) + " Joules.")
|
69c3d6752d504a08cf06c2ad8374e823f4e3f206 | srankur/PythonUtil | /MultiProcess/MultiThreading.py | 602 | 3.5625 | 4 | import time
import threading
def calc_square(num):
print("Calculating squares")
for n in num:
print("Square", n*n)
def calc_cube(num):
print("Calculating Cubes")
for n in num:
print ("cube", n*n*n)
number = [1,2,3,4]
t = time.time()
t1 = threading.Thread(target = calc_square,args=(range(10),))
#t2 = threading.Thread(target = calc_cube, args = (range(10),))
t1.start()
#t2.start()
t1.join()
#t2.join()
print (" Thread Done in : ", time.time()-t )
start = time.time()
calc_square(range(10))
#calc_cube(range(10))
print (" Seq Done in : ", time.time()- start )
|
d7fbbf8edf9b1748f59f7269641cb14a9f65529f | jakubna/IML-MAI20Z | /w1/algorithms/dbscan.py | 2,771 | 3.671875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors
def find_eps(x):
""" this function aims to plot the epsilon by calculating the distance to the nearest two points and index.
the optimal value will be found at the point of maximum curvature
x: normalized input variables
"""
neigh = NearestNeighbors(n_neighbors=2)
nbrs = neigh.fit(x)
distances, indices = nbrs.kneighbors(x)
distances = np.sort(distances, axis=0)
distances = distances[:, 1]
plt.plot(distances)
plt.show()
def dbscan_(x, df, eps=0.5):
""" this functions aims to clusterize the dataset using sklearn DBSCAN using different metrics and algorithms
and returns the original dataframe with labels of each metric-algorithm
and a dataframe with results (columns = metric, algorithm, number of clusters, number of estimated
noise points.
x: normalized input variables
df: original dataframe with variables and true labels
eps: optimal epsilon (obtained by the graph using find_eps function
min_s: minimal number of samples in one cluster """
metrics_ = ['euclidean', 'cosine', 'l1', 'l2', 'manhattan']
algo = ['auto', 'ball_tree', 'kd_tree', 'brute']
metrics_list = []
algorithms_list = []
clusters_list = []
noise_list = []
for metric in metrics_: # iterating to combine every metric with all algorithms
for method in algo:
ma = metric+method
if ma != 'cosineball_tree' and ma != 'cosinekd_tree': # cosine can't deal wth ball_tree and kd_tree algrtms
db = DBSCAN(eps=eps, min_samples=int(np.log(len(x))), metric=metric, algorithm=method).fit(x)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
df[metric+'-'+method] = labels
# labels_true = Y
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) # taking off the noise points
n_noise_ = list(labels).count(-1)
metrics_list.append(metric)
algorithms_list.append(method)
clusters_list.append(n_clusters_)
noise_list.append(n_noise_)
df_results = pd.DataFrame(columns=['Metric', 'Algorithm', 'Estimated Clusters', 'Estimated noise points'])
df_results['Metric'] = metrics_list
df_results['Algorithm'] = algorithms_list
df_results['Estimated Clusters'] = clusters_list
df_results['Estimated noise points'] = noise_list
return df_results, df
|
8e910da5e978a08b5be147fac493495144b76be2 | basu-sanjana1619/python_projects | /lists_to_dic.py | 146 | 3.65625 | 4 | #convert list to dictionary
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
dic = {}
for k,v in zip(keys,values):
dic[k] = v
print(dic)
|
4decf52cae21f429395dbb079c3bada56f7bf326 | basu-sanjana1619/python_projects | /gender_predictor.py | 683 | 4.21875 | 4 | #It is a fun program which will tell a user whether she is having a girl or a boy.
test1 = input("Are you craving spicy food? (Y/N) :")
test2 = input("Are you craving sweets? (Y/N) :")
test3 = input("Are you suffering from extreme morning sickeness or hyperemesis (Y/N) :")
test4 = input("Is the baby's heart rate above 150 beats per minute? (Y/N) :")
if test1.upper() == "N" and test2.upper() == "N" and test3.upper() == "Y" and test4.upper() == "Y":
print("CONGRATS!..Its a GIRL!..YAYYY")
elif test1.upper() == "Y" and test2.upper() == "Y" and test3.upper() == "Y" and test4.upper() == "Y":
print("CONGRATS!..Its a GIRL!..YAYYY")
else:
print("CONGRATS!..Its a BOY!..YAYYY")
|
8d37f294b27d2b0438b78c4ac726170312cd32d2 | yousufahmad/Stock-Price-Predictor | /python-stock-predictor.py | 2,554 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 15:33:08 2019
@author: yousuf
"""
import numpy as np
from datetime import datetime
from sklearn.linear_model import LinearRegression
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
'''
predictLinear takes in a ticker, a start date, and the number
of days in the future and computes a prediction of the stock
price in the future using linear regression
'''
def predictLinear(ticker, start_date, days_in_future):
end = datetime.now()
#Retrieves stock data using Pandas Datareader
df = web.DataReader(ticker, "yahoo", start_date, end)
df.to_csv(ticker + "_history.csv")
#Retrieve close values of the stock for every single day
close_vals = df['Close'].values
#Make a list of numbers that correspond to a date
#ex: 0 -> 1/1/2017, 1 -> 1/2/2017
dates = np.arange(len(df))
plt.plot(dates, close_vals)
#Generate matrix to feed into linear regression algorithm
Mat = np.zeros((len(dates), 2))
#first column is a vector of ones
Mat[:, 0] = np.ones(len(dates))
#second column is our dates(x dates)
Mat[:, 1] = dates
#Generate linear regression model
model = LinearRegression().fit(Mat, close_vals)
coeffs = model.coef_
intercept = model.intercept_
#graphing data
a = np.linspace(0, len(Mat), 10000)
b = model.intercept_ + coeffs[1]*a
plt.title('Linear Regression Model for ' + ticker + 'starting at ' +
start_date.strftime('%m-%d-%y'))
plt.ylabel('Price ($)')
plt.xlabel('Date')
plt.plot(dates, close_vals, color='b')
plt.plot(a, b, color='r')
plt.show()
#Compute prediction using computed coefficients
# y = b + ax
# x is the number of days in the future
# b is the intercept
# a is coeffs[1]
# y is the prediction
prediction = intercept + coeffs[1] * (len(dates) + days_in_future - 1)
return prediction
ticker = input("Enter a list of tickers separated by commas: ")
ticker_array = ticker.split(', ')
print(ticker_array)
start_date = input("Enter a date (MM-DD-YYYY): ")
start_date = datetime.strptime(start_date, '%m-%d-%Y')
days_in_future = int(input("Enter the number of days in the future: "))
for elem in ticker_array:
prediction = predictLinear(elem, start_date, days_in_future)
print(elem + " price in " + str(days_in_future) + " days will be $"
+ str(round(prediction, 2)) + " according to this model")
|
7ca7431e7c1c9fc28e859181da989f6d81b293b4 | thegrafico/coding-challenges | /python_challenge/zigzag2.py | 651 | 3.859375 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows
like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
================================================
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
P I N
A L S I G
Y A H R
P I
=================================================
"""
class Solution:
def convert(self, s: str, numRowns:int) ->str:
pass
#-- Test
if __name__ == "__main__":
solution = Solution()
test = "PAYPALISHIRING"
numRows = 5
solution.convert(test, numRows) |
6d1df73ee15581838b77a690311b9189489e537d | thegrafico/coding-challenges | /python_challenge/statistist_10days/day_1_quartiles_range.py | 1,678 | 3.78125 | 4 | # tam = input()
# values = input()
values = '6 12 8 10 20 16'
frequency = '5 4 3 2 1 5'
values = values.split()
frequency = frequency.split()
values = [float(x) for x in values]
frequency = [float(x) for x in frequency]
# print(values)
# print(frequency)
index_median = 0
def create_list(values, frequency):
arr = []
for i in range(len(values)):
for freq in range(int(frequency[i])):
arr.append(values[i])
return arr
#===================================================
def get_median_index(values):
for i in range(len(values)):
if (i+1) == ( len(values) // 2):
if len(values)%2 == 0:
return i
else:
return i + 1
#====================================================
values = create_list(values, frequency)
values.sort()
# print(values)
for i in range(len(values)):
if (i+1) == ( len(values) // 2):
if len(values)%2 == 0:
median = (values[i] + values[i + 1]) // 2
index_median = i
arr_lef = values[:index_median + 1]
else:
median = values[i + 1]
index_median = i + 1
arr_lef = values[:index_median]
arr_rigth = values[index_median + 1:]
#Q1
q1_index = get_median_index(arr_lef)
if len(arr_lef) % 2 == 0:
q1 = (arr_lef[q1_index] + arr_lef[q1_index + 1]) //2
else:
q1 = arr_lef[q1_index]
#Q2
q2 = median
#Q3
q3_index = get_median_index(arr_rigth)
if len(arr_lef) % 2 == 0:
q3 = (arr_rigth[q3_index] + arr_rigth[q3_index + 1]) //2
else:
q3 = arr_rigth[q3_index]
# print(arr_lef)
# print(arr_rigth)
# print(q1)
# print(q2)
# print(q3)
print( round(q3-q1,1) )
|
bdde0bdf932547d4fc2e02379deebe6e47fa22ae | cookcodeblog/python_work | /ch08/describe_city.py | 307 | 3.84375 | 4 | # 8-5 describe_city() function
def describe_city(city, country="China"):
print(str(city).title() + " is in " + country.title())
describe_city("Shanghai")
describe_city("Beijing")
describe_city(city="Chongqing")
describe_city("London", "England")
describe_city(city="California", country="America")
|
ab5cc8e8e5bc954b31b8a9334fb03af157fea522 | cookcodeblog/python_work | /ch10/guest.py | 457 | 4.09375 | 4 | # 10-3 Guest
# name = input("What is your name please ? ")
# # Don't forget add "w" to identify you want to write sth into the file
# with open("guest.txt", "w") as file_obj:
# file_obj.write(name)
with open("guest.txt", "a") as file_obj:
while True:
name = input("What is your name please? ")
file_obj.write(name + "\n")
repeat = input("Add other guest? (yes / no) ")
if repeat.lower() == "no":
break
|
0c26588a8506eb7d6bb5fa7d675451a607f5a3ab | cookcodeblog/python_work | /ch06/favorite_places.py | 366 | 3.796875 | 4 | # 6-9 Favorite Places
favorite_places = {
'William': ["Hainan", "Guangzhou", "Yunnan"],
'Sunna': ["Shanxi", "Greece", "London"],
'Wilson': ["Shanghai", "Beijing", "Hong Kong"]
}
for name, places in favorite_places.items():
print(name.title() + " likes following places:")
for place in places:
print("\t" + place.title())
print()
|
9d77a0ee4b5f9d90d48c67fcc19a686f6cb3b508 | cookcodeblog/python_work | /ch07/visit_poll.py | 543 | 4.125 | 4 | # 7-10 Visit Poll
visit_places = {}
poll_active = True
while poll_active:
name = input("What is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
visit_places[name] = place # It is like map.put(key, value)
repeat = input("Would you like to let another person respond? (yes / no)")
if repeat.lower() == "no":
poll_active = False
print("\n---Poll Result---\n")
for name, place in visit_places.items():
print(name.title() + " likes to visie " + place.title() + ".")
|
4f6f9d0dbcbf0baad2c94fa8a1aa5fd26e2a8f0f | cookcodeblog/python_work | /ch10/survey_programming.py | 283 | 3.84375 | 4 | # 10-5 Survey of Programming
with open("survey.txt", "a") as survey:
while True:
reason = input("Why do you want to learn Python? ")
survey.write(reason + "\n")
repeat = input("Continue? (yes / no) ")
if repeat.lower() == "no":
break
|
9bf8b21b2776a14fc8abc84c51549b3baff7385e | cookcodeblog/python_work | /ch09/restaurant.py | 1,155 | 4.03125 | 4 | # 9-1 Restaurant class
class Restaurant:
def __init__(self, restaurant_name, cuisine_type, number_served=0):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = number_served
def describe_restaurant(self):
print(self.restaurant_name + " is a " + self.cuisine_type + " restaurant.")
print(str(self.number_served) + " people visited this restaurant before.")
def open_restaurant(self):
print("Welcome to " + self.restaurant_name)
def set_number_served(self, number_served):
self.number_served = number_served
def increment_number_served(self, number):
self.number_served += number
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type, flavors, number_served=0):
# Must pass parameters to super class, and put default valued param at the end
super().__init__(restaurant_name, cuisine_type, number_served)
self.flavors = flavors
def describe_ice_cream(self):
print("Have following flavors:")
for flavor in self.flavors:
print(flavor)
|
2e1679facc189bf53edfc0c74160c0cecaa5b194 | cookcodeblog/python_work | /ch06/river.py | 316 | 4.25 | 4 | # 6-5 River
rivers = {
'Nile': 'Egypt',
'Changjiang': 'China',
'Ganges River': 'India'
}
for river, location in rivers.items():
print("The " + river + " runs through " + location + ".\n")
for river in rivers.keys():
print(river)
print()
for location in rivers.values():
print(location)
|
5d9d7e969d5200c7cab614e09c5dd5914a567609 | jhgdike/leetCode | /leetcode_python/201-300/213.py | 485 | 3.53125 | 4 | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def _rob_range(nums, i, j):
last = now = 0
for x in range(i, j):
last, now = now, max(now, last + nums[x])
return now
if not nums:
return 0
if len(nums) <= 3:
return max(nums)
return max(_rob_range(nums, 0, len(nums)-1), _rob_range(nums, 1, len(nums)))
|
0bb7fe5ad689ae77131bf184ddb4933995217a4c | jhgdike/leetCode | /leetcode_python/301-400/328.py | 856 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
odd = even = even_head = None
cur = head
while cur:
if odd:
odd.next = cur
odd = cur
if cur.next:
if not even:
even_head = even = cur.next
else:
even.next = cur.next
even = even.next
cur = cur.next.next
else:
break
odd.next = even_head
if even:
even.next = None
return head
|
c85b4dc755e367a5e8b1a554ebea5b74ee5f3b6f | jhgdike/leetCode | /leetcode_python/801-900/860.py | 706 | 3.578125 | 4 | class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
bil = [0, 0]
for b in bills:
if b == 5:
bil[0] += 1
elif b == 10:
if bil[0] < 1:
return False
bil[0] -= 1
bil[1] += 1
else:
if bil[0] < 1 or (bil[0] < 3 and bil[1] < 1):
return False
if bil[1]:
bil[1] -= 1
bil[0] -= 1
else:
bil[0] -= 3
return True
print(Solution().lemonadeChange([5,5,5,10,20]))
|
5f17c8f1ec2f340bdb38a58e045c18dff521c787 | jhgdike/leetCode | /leetcode_python/101-200/143.py | 1,018 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head:
return
fast, slow = head, head
while fast and fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
sec = slow.next
slow.next = None
sec_next = None
while sec:
cur = sec.next
sec.next = sec_next
sec_next = sec
sec = cur
tail = sec_next
cur = head
while cur and tail:
cur_next = cur.next
cur.next = tail
tail_next = tail.next
tail.next = cur_next
cur = cur_next
tail = tail_next
if tail:
cur.next = tail
|
ed83eebfc06efbb76af1baf6f9996f4389556824 | jhgdike/leetCode | /leetcode_python/1-100/43.py | 686 | 3.578125 | 4 | class Solution(object):
"""
Python can do it directly by str(int(num1)*int(num2))
"""
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = [0] * (len(num1) + len(num2))
lengh = len(res)
for i, n1 in enumerate(reversed(num1)):
for j, n2 in enumerate(reversed(num2)):
res[i + j] += int(n1) * int(n2)
res[i + j + 1] += res[i + j] / 10
res[i + j] %= 10
pt = lengh
while pt > 0 and res[pt - 1] == 0:
pt -= 1
res = res[:pt]
return ''.join(map(str, res[::-1] or [0]))
|
93f70311fcc86ee8a6fc47edc27da22cd085f77d | jhgdike/leetCode | /leetcode_python/301-400/374.py | 943 | 3.5625 | 4 | # The guess API is already defined for you.
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
def guess(num: int) -> int:
if num == 6:
return 0
elif num > 6:
return -1
return 1
class Solution:
def guessNumber(self, n: int) -> int:
l = 1
r = n
while True:
if l == r:
return l
mid = (l + r) // 2
ret = guess(mid)
if ret == 0:
return mid
if ret == 1:
l = mid + 1
else:
r = mid - 1
def _guessNumber(self, l, r):
if l == r:
return l
mid = (l + r) // 2
ret = guess(mid)
if ret == 0:
return mid
if ret == 1:
return self._guessNumber(mid + 1, r)
else:
return self._guessNumber(l, mid - 1)
print(Solution().guessNumber(11))
|
24cd99d037e3115ef980d5a035601d5ac745f634 | jhgdike/leetCode | /others/qsort.py | 249 | 3.578125 | 4 | # coding: utf-8
def ugly_qsort(seq):
if not seq:
return []
pivot = seq[0]
lesser = ugly_qsort([x for x in seq[1:] if x < pivot])
greater = ugly_qsort([x for x in seq[1:] if x >= pivot])
return lesser + [pivot] + greater
|
2a638fb07799491d5e2bdbcc5462e4507e089fff | jhgdike/leetCode | /leetcode_python/101-200/166.py | 1,312 | 3.734375 | 4 | class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
string_buffer = []
if numerator == 0:
return "0"
if (numerator < 0) ^ (denominator < 0):
string_buffer.append("-")
numerator = abs(numerator)
denominator = abs(denominator)
string_buffer.append(str(numerator//denominator))
remain = numerator % denominator
if remain == 0:
return ''.join(string_buffer)
string_buffer.append('.')
rd = dict()
while remain:
if remain in rd:
string_buffer.insert(rd[remain], '(')
string_buffer.append(')')
break
rd[remain] = len(string_buffer)
remain *= 10
string_buffer.append(str(remain // denominator))
remain %= denominator
return ''.join(string_buffer)
print(Solution().fractionToDecimal(1, 3))
print(Solution().fractionToDecimal(-1, 3))
print(Solution().fractionToDecimal(1, 2))
print(Solution().fractionToDecimal(6, 3))
print(Solution().fractionToDecimal(1, 4))
print(Solution().fractionToDecimal(2, 3))
print(Solution().fractionToDecimal(4, 333))
|
869a9d9c98a9ca7ecd1bc1d3eccf57e1195d0a52 | jhgdike/leetCode | /leetcode_python/__init__.py | 1,955 | 3.5 | 4 | import json
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return '[]'
res = []
tmp = [root]
has = True
while has:
cur = []
has = False
for t in tmp:
if t:
has = True
res.append(t.val)
cur.extend((t.left, t.right))
else:
res.append(None)
cur.extend((None, None))
tmp = cur
while res and res[-1] is None:
res = res[:-1]
return json.dumps(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
l = json.loads(data)
if len(l) == 0:
return None
root = TreeNode(l[0])
tmp = [root]
idx = 1
while idx < len(l):
cur = []
for i in range(len(tmp)):
if idx + i * 2 < len(l) and l[idx + i * 2] is not None:
tmp[i].left = TreeNode(l[idx + i * 2])
cur.append(tmp[i].left)
else:
cur.append(None)
if idx + i * 2 + 1 < len(l) and l[idx + i * 2 + 1] is not None:
tmp[i].right = TreeNode(l[idx + i * 2 + 1])
cur.append(tmp[i].right)
else:
cur.append(None)
idx += 2 * len(tmp)
tmp = cur
return root
c = Codec()
r = TreeNode(1)
r.left = TreeNode(2)
r.right = TreeNode(3)
r.right.left = TreeNode(4)
r.right.right = TreeNode(5)
raw = c.serialize(r)
print(raw)
c.deserialize(raw)
|
ba1970ff9331aca918aedc3fc019585970fc78a9 | jhgdike/leetCode | /leetcode_python/601-700/623.py | 880 | 3.96875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def addOneRow(self, root, val, depth):
"""
:type root: TreeNode
:type val: int
:type depth: int
:rtype: TreeNode
"""
if depth == 1:
return TreeNode(val, left=root)
queue = [root]
while depth > 2:
nexts = []
for node in queue:
if node.left: nexts.append(node.left)
if node.right: nexts.append(node.right)
queue = nexts
depth -= 1
for node in queue:
node.left = TreeNode(val, left=node.left)
node.right = TreeNode(val, right=node.right)
return root
|
6d8cea9f81c3d3d6714e8f6c613c95ce16b36ad2 | jhgdike/leetCode | /leetcode_python/1-100/56.py | 719 | 3.734375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
from operator import attrgetter
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort(key=attrgetter('start'))
res = []
if not intervals:
return res
res.append(intervals[0])
for i in range(1, len(intervals)):
if res[-1].end < intervals[i].start:
res.append(intervals[i])
elif res[-1].end < intervals[i].end:
res[-1].end = intervals[i].end
return res
|
0b44347123649993c9b6c56d3dd2a0594d19f83b | hunny123/Python-cpcode | /codeforces/CF677-D2-A.py | 322 | 3.71875 | 4 | def findwidth(n,h):
sum1=0
i=0
while i<len(n):
if(n[i]>h):
sum1 = sum1+2
else:
sum1 = sum1+1
i=i+1
return sum1
t = input()
t = list(map(int ,t.split(" ")))
li = input()
li = list(map(int,li.split(" ")))
print(findwidth(li,t[1]))
|
6d7d18fcd11e749140128f267f289f90bcd3023e | hunny123/Python-cpcode | /codeforces/CF102-D2-B.py | 154 | 3.5625 | 4 | def spell(n):
return sum(list(map(int,n)))
n = (input())
count=0
while len((n))!=1:
count =count+1
n=str(spell(n))
print(count)
|
b6f24db742408390a6125fd53ea58e20340246e1 | azdoherty/learners | /learners/TFtest.py | 517 | 3.53125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
from scipy.io import loadmat
import numpy as np
#mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#res = mnist.test.next_batch(batch_size=100)
#print(res[0].shape)
#print(res[1].shape)
trainfile = "datasets/housenumbers/train_32x32.mat"
trainset = loadmat(trainfile)
X = trainset['X']
y = trainset['y']
print(X.shape)
print(y.shape)
yvec = np.zeros((y.shape[0], len(np.unique(y))))
yvec[np.arange(y.shape[0]), (y-1).flatten()] = 1
print(yvec) |
045c4403c1babccb954fe09af19829d25aef3724 | zhenhao/phello | /src/utils/container/list.py | 506 | 3.609375 | 4 | __author__ = 'wangzhenhao'
class List:
def __init__(self):
self.l = []
def append(self, x):
self.l.append(x)
def insert(self, i, x):
self.l.insert(i, x)
def pop(self):
return self.l.pop()
def __str__(self):
return str(self.l)
def empty(self):
return len(self.l) == 0
def __len__(self):
return len(self.l)
def __bool__(self):
return not self.empty()
def __iter__(self):
return iter(self.l) |
859b5a09dc0a055963c28780a6fc9e93ae186747 | zhenhao/phello | /src/utils/helper.py | 239 | 3.953125 | 4 | __author__ = 'wangzhenhao'
def hanoi(a='A', b='B', c='C', n=1):
if n < 1:
pass
elif n == 1:
print(a + ' -> ' + c)
else:
hanoi(a, c, b, n - 1)
print(a + ' -> ' + c)
hanoi(b, a, c, n - 1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.