blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1a30a1aa633669910f34a7000d361be0ab9fdb28 | polyglotm/coding-dojo | /coding-challange/leetcode/hard/297-serialize-and-deserialize-binary-tree/297-serialize-and-deserialize-binary-tree.py | 2,007 | 3.765625 | 4 | """
297-serialize-and-deserialize-binary-tree
leetcode/hard/297. Serialize and Deserialize Binary Tree
Difficulty: hard
URL: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
"""
from typing import List
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import json
class Codec:
def createNode(self):
return {
'val': None,
'left': None,
'right': None,
}
def serializePreOrderTraversal(self, root, result):
if root:
result['val'] = root.val
else:
return
if root.left:
result['left'] = self.createNode()
self.serializePreOrderTraversal(root.left, result['left'])
if root.right:
result['right'] = self.createNode()
self.serializePreOrderTraversal(root.right, result['right'])
def deserializePreOrderTraversal(self, root, result):
if root:
result.val = root['val']
else:
return
if root['left']:
result.left = TreeNode()
self.deserializePreOrderTraversal(root['left'], result.left)
if root['right']:
result.right = TreeNode()
self.deserializePreOrderTraversal(root['right'], result.right)
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
_root = self.createNode()
self.serializePreOrderTraversal(root, _root)
return json.dumps(_root)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
parsedData = json.loads(data)
_root = TreeNode()
if not parsedData['val']:
return _root
self.deserializePreOrderTraversal(parsedData, _root)
return _root
|
a766f54edb606766578577139eb705ab3f90c246 | bc123456/data_science | /enron/outliers/outlier_cleaner.py | 791 | 3.59375 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
"""
import numpy as np
cleaned_data = []
error = abs(predictions - net_worths)
q = np.percentile(error, 90)
i = 0
for i in np.arange(len(predictions)):
if error[i] > q:
np.delete(predictions, i)
np.delete(ages, i)
np.delete(net_worths, i)
else:
tup = (ages[i], net_worths[i], error[i])
cleaned_data.append(tup)
return cleaned_data
|
850d9a8fe24a5ee7e318d25d2f7c5ea5d5378939 | Ashish0405/Test | /2.py | 1,137 | 4.21875 | 4 | def merge_intervals(intervals):
"""
A simple algorithm can be used:
1. Sort the intervals in increasing order
2. Push the first interval on the stack
3. Iterate through intervals and for each one compare current interval
with the top of the stack and:
A. If current interval does not overlap, push on to stack
B. If current interval does overlap, merge both intervals in to one
and push on to stack
4. At the end return stack
"""
si = sorted(intervals, key=lambda tup: tup[0])
merged = []
for tup in si:
if not merged:
merged.append(tup)
else:
b = merged.pop()
if b[1] >= tup[0]:
new_tup = tuple([b[0], tup[1]])
merged.append(new_tup)
else:
merged.append(b)
merged.append(tup)
return merged
if __name__ == '__main__':
l = [(5, 7), (11, 116), (3, 4), (10, 12), (6, 12)]
print("Original list of ranges: {}".format(l))
merged_list = merge_intervals(l)
print("List of ranges after merge_ranges: {}".format(merged_list)) |
06fd2f8c1576d80b0434cfebcba22ee857138852 | daniel-reich/turbo-robot | /iN48LCvtsQFftc7L9_23.py | 3,451 | 4.0625 | 4 | """
This challenge involves finding words in an 8x8 grid. Given a string of 64
`letters` and a list of `words` to find, convert the string to an 8x8 list,
and return `True` if _all_ words in the string can be found in the list.
Return `False` otherwise. Words can be read in any direction ( _horizontally_
, _vertically_ or _diagonally_ ).
### Example
letters = "PSUWHATSLPACKAGENYOLRDVLFINGEZBMIREHQNJOATBVGYESJDUWUESTPSTICKEY"
words = ["stick", "most", "key", "vein", "yes", "package", "tube", "target", "elm", "spy"]
This would give the list below:
[
["P", "S", "U", "W", "H", "A", "T", "S"],
["L", "P", "A", "C", "K", "A", "G", "E"],
["N", "Y", "O", "L", "R", "D", "V", "L"],
["F", "I", "N", "G", "E", "Z", "B", "M"],
["I", "R", "E", "H", "Q", "N", "J", "O"],
["A", "T", "B", "V", "G", "Y", "E", "S"],
["J", "D", "U", "W", "U", "E", "S", "T"],
["P", "S", "T", "I", "C", "K", "E", "Y"]
]
You would return `True` as all words can be found:
[
["_", "S", "_", "_", "_", "_", "T", "_"],
["_", "P", "A", "C", "K", "A", "G", "E"],
["N", "Y", "_", "_", "R", "_", "_", "L"],
["_", "I", "_", "G", "_", "_", "_", "M"],
["_", "_", "E", "_", "_", "_", "_", "O"],
["_", "T", "B", "V", "_", "Y", "E", "S"],
["_", "_", "U", "_", "_", "E", "_", "T"],
["_", "S", "T", "I", "C", "K", "_", "_"]
]
### Notes
Words must be contained inside the grid, without wrapping over columns/rows.
"""
def word_search(letters, words):
safe = []
grid = [list(letters[x:x+8]) for x in range(0, 64, 8)]
for x in words:
x = x.upper()
if x in letters or x[::-1] in letters:
safe.append(True)
continue
for row in range(8):
for col in range(8):
if grid[row][col] == x[0]:
d = row + len(x) - 1 < 8
u = row - len(x) >= -1
if d:
c = ''.join([grid[row+d][col] for d in range(len(x))])
if c == x or c[::-1] == x:
safe.append(True)
if u:
c = ''.join([grid[row-d][col] for d in range(len(x))])
if c == x or c[::-1] == x:
safe.append(True)
if row + len(x) < 8 and col - len(x) >= -1:
c = ''.join(grid[row+d][col-d] for d in range(len(x)))
if c == x or c[::-1] == x:
safe.append(True)
if row + len(x) < 8 and col + len(x) <= 8:
c = ''.join(grid[row+d][col+d] for d in range(len(x)))
if c == x or c[::-1] == x:
safe.append(True)
if u and col + len(x) <= 8:
c = ''.join(grid[row-d][col+d] for d in range(len(x)))
if c == x or c[::-1] == x or c in words or c[::-1] in words:
safe.append(True)
if u and col - len(x) >= -1:
c = ''.join(grid[row-d][col-d] for d in range(len(x)))
if c == x or c[::-1] == x or c[::-1] in words:
safe.append(True)
return len(safe) == len(words)
|
ea4313c0bef7de4eca6e91d96781dc475db7d3cb | nehakotwal1998/Python-projects | /books.py | 625 | 3.953125 | 4 | import sqlite3
con=sqlite3.connect("books_db.sqlite3")
cur=con.cursor() #to execute sql in python this is the package
try:
cur.execute("CREATE TABLE books (id INTEGER PRIMARY KEY , name TEXT, rating INTEGER)")
except sqlite3.OperationalError:
print("table already exists..")
cur.execute("INSERT into books VALUES (1,' If you could see me now',5)")
cur.execute("INSERT into books VALUES (2,'The book of tomorrow',3)")
cur.execute("INSERT into books VALUES (3,'a place called here',4)")#till here if we execute its wront ony tables formed data isnt there so to put data we use see down
con.commit()#it saves it on the disks |
920b36ef8b3736abfab445e8673d0768ea409a68 | brandoneng000/LeetCode | /easy/762.py | 569 | 3.59375 | 4 | class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
def is_prime(num: int) -> bool:
for factor in range(2, int(num ** 0.5) + 1):
if num % factor == 0:
return False
return num != 1
return sum(is_prime(bin(num).count('1')) for num in range(left, right + 1))
def main():
sol = Solution()
print(sol.countPrimeSetBits(6, 10))
print(sol.countPrimeSetBits(10, 15))
print(sol.countPrimeSetBits(1, 10000))
if __name__ == '__main__':
main() |
70573e3c8acd50b795391813530aa0a0122f5794 | varinder-singh/PythonProgramming | /PythonProgramming/HelloWorld/ListProgramming.py | 907 | 4.375 | 4 | # This program understands to make a list and how to iterate the list via for loop
# Use of append operation over list.
# USe of sort operation over the list. Sort on the list in python never creates a new object it does the operation on
# the same object.
#
groceryList = ['bread', 'butter', 'rice', 'lentils', 'jam', 'cup cakes', 'dosa batter']
# groceryList.append("sambar masala")
# groceryList.sort()
#
# # However, if we try to print the above statement it returns NONE.
# print(groceryList.sort())
# # If at all a new list object is needed then use the method 'sorted()'
# print(sorted(groceryList))
# Two lists can be concatenated using '+' operator in python
print()
x = 1
print("******************Start of Grocery List**********************")
for item in groceryList:
print("Item # {0} is {1}".format(x,item))
x+=1
print("******************End of Grocery List************************") |
da5a159654afb8a63415886235876648295062f5 | Souravdg/Python.Session_5.Assignment-5.2 | /subject_verb_object program.py | 470 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
"""
Problem Statement 1:
Implement a Python program to generate all sentences where subject is in
["Americans", "Indians"] and verb is in ["Play", "watch"] and the object is in
["Baseball","cricket"]
"""
subject=["Americans", "Indians"]
verb=["Play", "watch"]
obj=["Baseball","cricket"]
result = [sub+' '+ver+' '+ob for sub in subject for ver in verb for ob in obj]
for x in range(len(result)):
print(result[x])
|
7313564c7f7a7d0457f1b93167679d7c2cc999e2 | rakshitraj/lol | /hashmap.py | 1,522 | 3.53125 | 4 | class HashMap:
def __init__(self):
self.MAX = 100
self.arr = [[] for _ in range(self.MAX)]
def get_hash(self, key):
hash = 0
for char in key:
hash += ord(char)
return hash % self.MAX
def __setitem__(self, key, value):
h = self.get_hash(key)
found = False
for index, element in enumerate(self.arr[h]):
if len(element) == 2 and element[0] == key:
self.arr[h][index] = (key, value)
found = True
break
if not found:
self.arr[h].append((key, value))
def __getitem__(self, key):
h = self.get_hash(key)
for element in self.arr[h]:
if element[0] == key:
return element[1]
def __delitem__(self, key):
h = self.get_hash(key)
for index, element in enumerate(self.arr[h]):
if element[0] == key:
del self.arr[h][index]
def print(self):
for h in range(self.MAX):
print(f'{self.arr[h]}')
if __name__ == '__main__':
handler = open('lipsum.txt', 'r')
table = HashMap()
for line in handler:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word[-1] in ['.', ','] : word = word[:-1]
val = 0 if table[word] is None else table[word]
val += 1
table[word] = val
handler.close()
table.print() |
848810181bd0d2fcd10c5aec64c4f545b74cea86 | pravin-asp/Python-Learnings | /Overriding.py | 742 | 4.46875 | 4 | # Overriding
# same method name in parent and child class is called overriding
# 1. Method Overriding
class Parent:
def study(self):
print('Engineering or Medical')
class Child(Parent):
def play(self):
print('Playing Kabadi')
def study(self):
#super().study()
print('Animation / Director')
c = Child()
c.study()
print()
# 2. Constructor Overriding
class Parent:
def __init__(self):
print('Parent Class Constructor')
def study(self):
print('Engineering or Medical')
class Child(Parent):
def __init__(self):
#super().__init__()
print('Child Class Constructor')
def play(self):
print('Playing Kabadi')
def study(self):
#super().study()
print('Animation / Director')
c = Child()
c.study() |
19489294697ee29e3fd42d16096216a741906641 | dgoldsb/advent-of-code-2018 | /day-16/problem_16.py | 10,554 | 3.546875 | 4 | """
You scan a two-dimensional vertical slice of the ground nearby and discover that it is mostly sand with veins of clay. The scan only provides data with a granularity of square meters, but it should be good enough to determine how much water is trapped there. In the scan, x represents the distance to the right, and y represents the distance down. There is also a spring of water near the surface at x=500, y=0. The scan identifies which square meters are clay (your puzzle input).
For example, suppose your scan shows the following veins of clay:
x=495, y=2..7
y=7, x=495..501
x=501, y=3..7
x=498, y=2..4
x=506, y=1..2
x=498, y=10..13
x=504, y=10..13
y=13, x=498..504
Rendering clay as #, sand as ., and the water spring as +, and with x increasing to the right and y increasing downward, this becomes:
44444455555555
99999900000000
45678901234567
0 ......+.......
1 ............#.
2 .#..#.......#.
3 .#..#..#......
4 .#..#..#......
5 .#.....#......
6 .#.....#......
7 .#######......
8 ..............
9 ..............
10 ....#.....#...
11 ....#.....#...
12 ....#.....#...
13 ....#######...
The spring of water will produce water forever. Water can move through sand, but is blocked by clay. Water always moves down when possible, and spreads to the left and right otherwise, filling space that has clay on both sides and falling out otherwise.
For example, if five squares of water are created, they will flow downward until they reach the clay and settle there. Water that has come to rest is shown here as ~, while sand through which water has passed (but which is now dry again) is shown as |:
......+.......
......|.....#.
.#..#.|.....#.
.#..#.|#......
.#..#.|#......
.#....|#......
.#~~~~~#......
.#######......
..............
..............
....#.....#...
....#.....#...
....#.....#...
....#######...
Two squares of water can't occupy the same location. If another five squares of water are created, they will settle on the first five, filling the clay reservoir a little more:
......+.......
......|.....#.
.#..#.|.....#.
.#..#.|#......
.#..#.|#......
.#~~~~~#......
.#~~~~~#......
.#######......
..............
..............
....#.....#...
....#.....#...
....#.....#...
....#######...
Water pressure does not apply in this scenario. If another four squares of water are created, they will stay on the right side of the barrier, and no water will reach the left side:
......+.......
......|.....#.
.#..#.|.....#.
.#..#~~#......
.#..#~~#......
.#~~~~~#......
.#~~~~~#......
.#######......
..............
..............
....#.....#...
....#.....#...
....#.....#...
....#######...
At this point, the top reservoir overflows. While water can reach the tiles above the surface of the water, it cannot settle there, and so the next five squares of water settle like this:
......+.......
......|.....#.
.#..#||||...#.
.#..#~~#|.....
.#..#~~#|.....
.#~~~~~#|.....
.#~~~~~#|.....
.#######|.....
........|.....
........|.....
....#...|.#...
....#...|.#...
....#~~~~~#...
....#######...
Note especially the leftmost |: the new squares of water can reach this tile, but cannot stop there. Instead, eventually, they all fall to the right and settle in the reservoir below.
After 10 more squares of water, the bottom reservoir is also full:
......+.......
......|.....#.
.#..#||||...#.
.#..#~~#|.....
.#..#~~#|.....
.#~~~~~#|.....
.#~~~~~#|.....
.#######|.....
........|.....
........|.....
....#~~~~~#...
....#~~~~~#...
....#~~~~~#...
....#######...
Finally, while there is nowhere left for the water to settle, it can reach a few more tiles before overflowing beyond the bottom of the scanned data:
......+....... (line not counted: above minimum y value)
......|.....#.
.#..#||||...#.
.#..#~~#|.....
.#..#~~#|.....
.#~~~~~#|.....
.#~~~~~#|.....
.#######|.....
........|.....
...|||||||||..
...|#~~~~~#|..
...|#~~~~~#|..
...|#~~~~~#|..
...|#######|..
...|.......|.. (line not counted: below maximum y value)
...|.......|.. (line not counted: below maximum y value)
...|.......|.. (line not counted: below maximum y value)
How many tiles can be reached by the water? To prevent counting forever, ignore tiles with a y coordinate smaller than the smallest y coordinate in your scan data or larger than the largest one. Any x coordinate is valid. In this example, the lowest y coordinate given is 1, and the highest is 13, causing the water spring (in row 0) and the water falling off the bottom of the render (in rows 14 through infinity) to be ignored.
So, in the example above, counting both water at rest (~) and other sand tiles the water can hypothetically reach (|), the total number of tiles the water can reach is 57.
How many tiles can the water reach within the range of y values in your scan?
--- Part Two ---
After a very long time, the water spring will run dry. How much water will be retained?
In the example above, water that won't eventually drain out is shown as ~, a total of 29 tiles.
How many water tiles are left after the water spring stops producing water and all remaining water not at rest has drained?
"""
import re
import numpy as np
MIN_X = None
GRID = np.ndarray(shape=(0,0))
SPRING = [500, 0]
DEBUG = False
class Drop:
def __init__(self, location=SPRING):
self.x = location[0]
self.y = location[1]
if DEBUG:
print(f'Spawn at {self.x},{self.y}.')
def can_fall(self):
return GRID[self.x][self.y + 1] in [0, 2]
def can_spread(self):
return (GRID[self.x - 1][self.y] in [0, 2]) or (GRID[self.x + 1][self.y] in [0, 2])
def fall(self):
while True:
if self.y + 1 == len(GRID[x]):
# Return that this hit the end
return True
elif GRID[x][self.y + 1] == 100:
return True
elif not self.can_fall():
break
else:
self.y += 1
GRID[self.x][self.y] = 2
return self.spread()
def spread(self):
children = []
# Spread right.
right_ended = False
start_x = self.x
start_y = self.y
while True:
if self.can_fall():
new_drop = Drop([self.x, self.y])
reached_end = new_drop.fall()
if reached_end:
GRID[self.x][self.y] = 100 # create a sink
children.append(0)
else:
children.append(1)
break
elif GRID[self.x + 1][self.y] == 100:
children.append(0)
right_ended = True
break
elif GRID[self.x + 1][self.y] == -1:
break
else:
self.x += 1
GRID[self.x][self.y] = 2
# Spread left.
left_ended = False
self.x = start_x
self.y = start_y
while True:
if self.can_fall():
new_drop = Drop([self.x, self.y])
reached_end = new_drop.fall()
if reached_end:
GRID[self.x][self.y] = 100 # create a sink
children.append(0)
else:
children.append(1)
break
elif GRID[self.x - 1][self.y] == 100:
children.append(0)
left_ended = True
break
elif GRID[self.x - 1][self.y] == -1:
break
else:
self.x -= 1
GRID[self.x][self.y] = 2
if right_ended and left_ended:
return True
# If no children, spread still.
if len(children) == 0:
return self.still()
else:
if sum(children) > 0:
return False
else:
return True
def still(self):
GRID[self.x][self.y] = 3
while True:
if GRID[self.x + 1][self.y] == -1:
break
else:
self.x += 1
GRID[self.x][self.y] = 3
while True:
if GRID[self.x - 1][self.y] == -1:
break
else:
self.x -= 1
GRID[self.x][self.y] = 3
# Return that this did not reach a sink.
return False
def print_grid():
def map_to_char(a):
if a == 1:
return '+'
elif a == -1:
return '#'
elif a == 0:
return '.'
elif a == 100:
return 's'
elif a == 2:
return '|'
elif a == 3:
return '~'
for grid_line in list(np.transpose(GRID)):
print(''.join([map_to_char(a) for a in grid_line[MIN_X:]]))
def answer():
unique, counts = np.unique(GRID, return_counts=True)
dict_counts = dict(zip(unique, counts))
total = dict_counts[2] + dict_counts[3] + dict_counts[100]
print(f'Answer 1 is {total}.')
print(f'Answer 1 is {dict_counts[3]}.')
if __name__ == '__main__':
tiles = []
with open('input', 'r') as file:
for line in file:
match = re.match('([xy])=([0-9]+), ([xy])=([0-9]+)..([0-9]+)', line)
if match:
if match.group(1) == 'x':
for y in range(int(match.group(4)), int(match.group(5)) + 1):
tiles.append((int(match.group(2)), y))
elif match.group(1) == 'y':
for x in range(int(match.group(4)), int(match.group(5)) + 1):
tiles.append((x, int(match.group(2))))
# Create the grid.
MIN_X = min([c[0] for c in tiles]) - 2
min_y = min([c[1] for c in tiles])
max_x = max([c[0] for c in tiles]) + 2
max_y = max([c[1] for c in tiles]) + 1
GRID = np.ndarray(shape=(max_x, max_y))
for c in tiles: # 1 is well, 2 is flowing, 3 is still, -1 is clay
GRID[c[0], c[1]] = -1
GRID[SPRING[0], SPRING[1]] = 1 # place the well
# Loop until the drop and its children are dead.
i = 0
while True:
grid_copy = np.copy(GRID)
drop = Drop()
# Evaluate the drop.
if drop.can_fall():
drop.fall()
elif drop.can_spread():
drop.spread()
if DEBUG:
print(f'Doing drop from well #{i}.')
i += 1
if np.array_equal(GRID, grid_copy):
break
# Print the endgame grid.
smaller = [line[min_y:] for line in list(GRID)]
GRID = np.array(smaller)
print_grid()
answer()
|
dc1b036fc47eb3a114a1b4dc3a3b4f57989e7942 | JamesRoth/Unit4 | /functionDemo.py | 640 | 4.0625 | 4 | #James Roth
#3/9/18
#functionDemo.py - writing functions
"""
def hw():
print("Hello world")
hw() #test of our function
"""
"""
def double(thingToDouble):
print(thingToDouble*2)
double(12)
double("wowwow")
double(True)
"""
"""
def bigger(a,b):
if a>b:
print(a)
else:
print(b)
bigger(12, 5)
def slope(x1,y1,x2,y2):
print((y1-y2)/(x1-x2))
#slope(10,5,3,4)
i=1 #surprisingly enough, if you input 1 for true, the loop will run as true, since python outputs the True boolean as 1
while 1: #not a good habit
print("James")
i+=1
if i==10:
break
"""
print("The max of 3 and 4 is:", max(3,4))
|
6a5e169d426a7ae82f1ada99a7972f16ff0df1cf | renjithrp/smart-winds | /db.py | 2,029 | 3.625 | 4 |
import sqlite3
from sqlite3 import Error
from config import DATABASE_NAME
CREATE_TABLE_QUERY = """ CREATE TABLE IF NOT EXISTS data (
id integer primary key autoincrement ,
spool_width NUMERIC,
spool_diaz NUMERIC,
wire_guage NUMERIC,
no_of_turns NUMERIC,
rpm NUMERIC,
int_position NUMERIC,
turns_count NUMERIC,
pos_reach NUMERIC,
mode INTEGER
); """
def create_connection():
db_file = DATABASE_NAME + ".db"
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def get_connection():
conn = create_connection()
if conn is not None:
create_table(conn, CREATE_TABLE_QUERY)
return conn
else:
print("Database connection error!!")
conn = get_connection()
def update(values):
columns = ', '.join(values.keys())
placeholders = ', '.join('?' * len(values))
sql = 'INSERT INTO data ({}) VALUES ({})'.format(columns, placeholders)
values = [int(x) if isinstance(x, bool) else x for x in values.values()]
c = conn.cursor()
c.execute(sql, values)
conn.commit()
return True
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def fetch():
sql = "select * from data ORDER BY id DESC;"
conn.row_factory = dict_factory
c = conn.cursor()
c.execute(sql)
return c.fetchone()
|
b59e61d5da2bb1033218de5ba00ed948775dedce | wonyoung2257/coding_test_python | /binarySerch/PartSearch.py | 863 | 3.828125 | 4 | import sys
def binary_search(array, target, start, end):
while start <= end:
mid = (start + end) //2
# 찾았을 때
if array[mid] == target:
return mid;
# 타겟이 중간값 왼쪽에 있을 때
elif array[mid] > target:
end = mid -1;
# 타겟이 중간값 오른쪽에 있을 때
else:
start = mid +1;
return None;
N = int(sys.stdin.readline().rstrip())
N_array = list(map(int, input().split()))
M = int(sys.stdin.readline().rstrip())
M_array = list(map(int, input().split()))
N_array.sort()
M_array.sort()
for i in M_array:
if binary_search(N_array, i, 0, N-1) == None:
print("no", end=" ")
else:
print("yes", end=" ")
for i in M_array:
if i in N_array:
print("yes", end = " ")
else:
print("no", end= " ") |
9addbbe2355e44d13b2a55cef5c4c87a31f1d05c | ericma1999/COMP0005-TA | /week3/exercise1.py | 2,047 | 3.921875 | 4 | words = ["eat", "tea", "part", "ate", "trap", "pass"]
def sort(word):
for i in range(0,len(word)):
for j in range(i, 0, -1):
if (word[j] < word[j-1]):
word = swap(word, j-1, j)
return word
def swap(value, i, j):
return ''.join((value[:i], value[j], value[i+1:j], value[i], value[j+1:]))
def sortArray(vals):
newList = []
for word in vals:
newList.append(sort(word))
return newList
def dualMergeSort(arr,arr2):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
L2 = arr2[:mid]
# into 2 halves
R = arr[mid:]
R2 = arr2[mid:]
# Sorting the first half
dualMergeSort(L,L2)
# Sorting the second half
dualMergeSort(R,R2)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
arr2[k] =L2[i]
i += 1
else:
arr[k] = R[j]
arr2[k] = R2[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
arr2[k] = L2[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
arr2[k] = R2[j]
j += 1
k += 1
def groupAnagrams(words, words2):
groups = [[]]
count = 0
value = words.pop(0)
groups[count].append(words2.pop(0))
while(len(words) > 0):
while(value == words[0]):
words.pop(0)
groups[count].append(words2.pop(0))
count += 1
value = words.pop(0)
groups.append([])
groups[count].append(words2.pop(0))
return groups
def anagrams(words):
sortedWords = sortArray(words)
dualMergeSort(sortedWords, words)
return(groupAnagrams(sortedWords, words))
print(anagrams(words))
|
81c5ad98a0a320cb9f9b6311f4aeaf2738c96a0f | FriendedCarrot4z/Final-Project-CSE-212 | /QueueMusicSolution.py | 4,495 | 4 | 4 | """
"""
import pygame
from pygame import mixer
pygame.mixer.init()
class Priority_Queue:
"""
This queue follows the same FIFO process except that higher priority
nodes will be dequeued before lower priority nodes. Nodes of the same
priority will follow the same FIFO process.
"""
class Node:
"""
Each node is the queue will have both a song and a priority.
"""
def __init__(self, song, priority):
"""
Initialize a new node
"""
self.song = song
self.priority = priority
def __str__(self):
"""
Display a single node
"""
return "{} {}".format(self.song, self.priority)
def __init__(self):
"""
Initialize an empty priority queue
"""
self.queue = []
def enqueue(self, song, priority):
"""
Add a new song to the queue with an associated priority. The
node is always added to the back of the queue irregardless of
the priority.
"""
new_node = Priority_Queue.Node(song, priority)
self.queue.append(new_node)
def dequeue(self):
"""
Remove the next song from the queue based on the priority. The
highest priority item will be removed. In the case of multiple
songs with the same high priority, the one closest to the front
(in traditional FIFO order) will be removed. Priority songs are
interpreted as higher numbers have higher priority. For example,
10 is a higher priority than 5.
"""
if len(self.queue) == 0: # Verify the queue is not empty
print("end of play list")
return False
# Find the index of the item with the highest priority to remove
high_pri_index = 0
for index in range(0, len(self.queue)):
if self.queue[index].priority < self.queue[high_pri_index].priority:
high_pri_index = index
# Remove and return the item with the highest priority
song = self.queue[high_pri_index].song
del self.queue[high_pri_index]
return song
def __len__(self):
"""
Support the len() function
"""
return len(self.queue)
def __str__(self):
"""
Suppport the str() function to provide a string representation of the
priority queue. This is useful for debugging. If you have a
Priority_Queue object called pq, then you run print(pq) to see the
contents.
"""
result = "["
for node in self.queue:
result += str(node) # This uses the __str__ from the Node class
result += ", "
result += "]"
return result
def Play(self):
true = True
song = self.dequeue()
pygame.mixer.music.load(song)
pygame.mixer.music.play(0)
print(song)
print("If the song ends, press any key to jump to the next song")
while true:
Input = input("p to pause music, u to resume music, r to restart music, e to exit out ")
#use keyboard commands instead of inputs
while pygame.mixer.music.get_busy() == False:
if len(self.queue) == 0:
true = False
song = self.dequeue()
pygame.mixer.music.load(song)
pygame.mixer.music.play(0)
print(song)
if Input == "p":
pygame.mixer.music.pause()
if Input == "u":
pygame.mixer.music.unpause()
if Input == "r":
pygame.mixer.music.rewind()
pygame.mixer.music.play(0)
print("rewind")
if Input == "e":
true = False
priority = Priority_Queue()
priority.enqueue("Silent Night.wav", 1)
priority.enqueue("What Child Is This.wav", 2)
priority.enqueue("Did you Think to Pray.wav", 3)
priority.enqueue("His Hands.wav", 4)
priority.enqueue("Im Trying to Be like Jesus.wav", 5)
priority.enqueue("Israel Israel God Is Calling.wav", 6)
priority.enqueue("Lord I Would Follow Thee.wav", 7)
priority.enqueue("Nearer My God to Thee.wav", 8)
priority.enqueue("O Come All Ye Faithful.wav", 9)
priority.enqueue("O Come Emmanuel - Christmas Version - ThePianoGuys.wav", 10)
priority.Play()
|
ab745fbe76357fb8e4b6e56b4c8e9ef1a1407dbf | helenamulcahy/Helena_Python | /week 3/2-decimal-parts.py | 500 | 3.96875 | 4 | def read_float(prompt):
while True:
try:
number = float(input(prompt))
break
except ValueError:
print("Must be numeric...")
return number
def find_parts(x):
integer = int(x)
decimal = x - integer
return integer, decimal
def main():
number = read_float("Decimal number >>> ")
whole, decimal_part = find_parts(number)
print("The whole part is", whole)
print(f"The decimal part is {decimal_part:.6f}")
main()
|
3fefecb302629a8610438b155f5d3ee5640891a6 | maketubuwa/python | /test/fangwenxianzhi.py | 830 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-02 18:55:00
# @Author : mx (mengxiang@xiangcloud.com.cn)
# @Link : http://www.xiangcloud.com.cn/
# @Version : $Id$
class Student(object):
"""dname,scoretring for Student"""
def __init__(self, name,score):
self.__name=name
self.__score=score
def get_name(self):
return self.__name
def set_name(self,name):
if name is not null:
self.__name=name
else:
raise ValueError('bad name')
def set_score(self,score):
if 0<=score<=100:
self.__score=score
else:
raise ValueError('bad score')
def get_score(self):
return self.__score
def print_score(self):
print('%s %s' %(self.__name,self.__score))
bart=Student('caowei',23)
print(bart.get_name())
print(bart.get_score())
bart.set_score(65)
print('修改后的年龄为:' + str(bart.get_score())) |
1871a7056cad24021c140ae7e75e80f90f0124bf | JSYoo5B/TIL | /PS/BOJ/9084/9084.py | 550 | 3.75 | 4 | #!/usr/bin/env python3
def get_ways_to_price(coins, price):
ways = [ 0 for _ in range(price + 1) ]
for c in coins:
if c > price:
break
ways[c] += 1
for cur in range(c+1, price+1):
ways[cur] += ways[cur-c]
return ways[price]
if __name__ == '__main__':
tests_cnt = int(input())
for _ in range(tests_cnt):
coins_cnt = int(input())
coins = list(map(int, input().split()))
price = int(input())
ways = get_ways_to_price(coins, price)
print(ways)
|
6dc7e2b4cf1f977839856648b7cafd8f1b74ed2f | poohcid/class | /PSIT/84.1.py | 511 | 3.90625 | 4 | """Largest Number"""
def main(num1, num2, num3):
"""statement"""
number = high(0, int(num1+num2+num3))
number = high(number, int(num1+num3+num2))
number = high(number, int(num2+num1+num3))
number = high(number, int(num2+num3+num1))
number = high(number, int(num3+num1+num2))
number = high(number, int(num3+num2+num1))
print(int(number))
def high(num1, num2):
"""high"""
if num1 > num2:
return num1
else:
return num2
main(input(), input(), input())
|
bd1d226ed196200c34feab3a6b635219f1d06c4f | mihail-nikolov/hackBG | /week0/simple_problems/24_int_prime_fact.py | 1,376 | 3.984375 | 4 | def is_prime(x):
if x > 1:
if x == 2 or x == 3:
return True
else:
for i in range(2, x - 1):
if x % i == 0:
return False
return True
else:
return False
def is_it_works(n):
if is_prime(n) is True:
return True
else:
for i in range(2, n+1):
for j in range(1, n+1):
if (i ** j == n) and (is_prime(i) is True) and (is_prime(j) is True):
return True
return False
def ret_arr(n):
if is_prime(n) is True:
arr = [n, 1]
return arr
else:
for c in range(2, n+1):
for d in range(1, n+1):
if c ** d == n and (is_prime(c) is True) and (is_prime(d) is True):
arr = [c, d]
return arr
def prime_fact(n):
result = []
if is_prime(n) is True:
result = [n, 1]
return result
else:
for a in range(2, n+1):
if n % a == 0:
for b in range(a, n+1):
if (a * b == n) and (is_it_works(a) is True) and (is_it_works(b) is True):
arr1 = ret_arr(a)
arr2 = ret_arr(b)
result = [arr1, arr2]
return result
return False
print(prime_fact(1000))
|
7b8d61daaaaee32169be55f65478a7d86e024c34 | evinpinar/competitive_python | /leetcode/23.py | 2,883 | 4.0625 | 4 |
import heapq
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def mergeKLists(lists):
'''
At each step, find the next minimum element from the lists, append to result.
'''
h = ListNode(0)
next_node = h
if len(lists) == 0:
return None
for i in range(len(lists) - 1, -1, -1):
if lists[i] == None:
lists.pop(i)
while lists:
min_num = float('inf')
min_i = -1
for n, l in enumerate(lists):
if l.val < min_num:
min_num = l.val
min_i = n
if lists[min_i].next != None:
lists[min_i] = lists[min_i].next
else:
lists.pop(min_i)
next_node.next = ListNode(min_num)
next_node = next_node.next
return h.next
def mergeKLists2(lists):
'''
Optimized version of previous solution. Use a priority queue to keep the initial elements. At each step, when the node is removed, add node.next to the priority queue.
'''
h = ListNode(0)
next_node = h
if len(lists) == 0:
return None
heap = []
for n, l in enumerate(lists):
if l != None:
heapq.heappush(heap, (l.val, n))
while heap:
min_num, min_i = heapq.heappop(heap)
next_node.next = ListNode(min_num)
next_node = next_node.next
lists[min_i] = lists[min_i].next
if lists[min_i] != None:
heapq.heappush(heap, (lists[min_i].val, min_i))
return h.next
def mergeKLists3(lists):
'''
Totally different approach than others. Merge the lists two by two until we
end up with only one list.
'''
h = ListNode(0)
next_node = h
def mergeLists(l1, l2):
h = nextnode = ListNode(0)
while l1 or l2:
if l1 and l2:
if l1.val < l2.val:
nextnode.next = ListNode(l1.val)
l1 = l1.next
else:
nextnode.next = ListNode(l2.val)
l2 = l2.next
elif l1:
nextnode.next = ListNode(l1.val)
l1 = l1.next
else:
nextnode.next = ListNode(l2.val)
l2 = l2.next
nextnode = nextnode.next
return h.next
while len(lists)!=1:
for i in range(len(lists)-1, 0, -2):
lists[i] = mergeLists(lists[i], lists[i-1])
lists.pop(i-1)
print(i, " : ", len(lists))
return lists[0]
if __name__ == '__main__':
l1 = ListNode(1)
l1.next = ListNode(4)
l1.next.next = ListNode(5)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
l3 = ListNode(2)
l3.next = ListNode(6)
ans = mergeKLists3([l1, l2, l3])
while ans:
print(ans.val)
ans = ans.next |
b32a0f94ad008136889baff4cb056810e2a67ffd | LevonAr/Teaching-Myself-the-Basics | /Python/cash/cash.py | 624 | 3.71875 | 4 | while True:
try:
change = float(input("change owed:"))
if change>0:
break
else:
pass
except ValueError:
pass
slice_change = int(change)
difference = change-slice_change
dollar_change = slice_change/.25
pre_whole_num_change = difference*100
whole_num_change = round(pre_whole_num_change)
quarters = whole_num_change//25
quarter_rem = whole_num_change%25
dimes = quarter_rem//10
dime_rem = quarter_rem%10
nickels = dime_rem//5
nickel_rem = dime_rem%5
pennies = nickel_rem//1
total = int(dollar_change+quarters+dimes+nickels+pennies)
print (total)
|
5432137ee014aaa455348b31c2086e9d48957d4b | keerthidl/Python-Assignment-re-work- | /char_read.py | 208 | 4.25 | 4 | #Implement a program to read alternative characters in the file.
def main():
file = open("char_read.txt")
text = file.read()
print(text[::3])
#important
file.close()
if __name__=="__main__":
main() |
ce3f466874042b4237e191e19858b5565c0563f6 | siddushan/sudoku_solver | /main.py | 2,217 | 3.578125 | 4 | __author__ = 'Sidd'
sudoku_grid = [
[4, 0, 0, 0, 0, 0, 8, 0, 5],
[0, 3, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 7, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 6, 0],
[0, 0, 0, 0, 8, 0, 4, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 6, 0, 3, 0, 7, 0],
[5, 0, 0, 2, 0, 0, 0, 0, 0],
[1, 0, 4, 0, 0, 0, 0, 0, 0]]
"""
sudoku_grid = [
[0, 1, 2, 0, 0, 0, 8, 0, 5],
[4, 3, 8, 0, 0, 0, 0, 0, 0],
[9, 5, 7, 7, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 6, 0],
[0, 0, 0, 0, 8, 0, 4, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 6, 0, 3, 0, 7, 0],
[5, 0, 0, 2, 0, 0, 0, 0, 0],
[1, 0, 4, 0, 0, 0, 0, 0, 0]]
"""
possible_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}
def check_box(x_val, y_val):
remove_set = set()
col = (x_val / 3) * 3
row = (y_val / 3) * 3
for i in range(3):
for j in range(3):
if sudoku_grid[row + i][col + j] != 0:
remove_set.add(sudoku_grid[row + i][col + j])
return possible_set - remove_set
def check_row(x_val):
remove_set = set()
for elements in sudoku_grid[x_val]:
if elements != 0:
remove_set.add(elements)
return possible_set - remove_set
def check_col(y_val):
remove_set = set()
for i in range(9):
if sudoku_grid[i][y_val] != 0:
remove_set.add(sudoku_grid[i][y_val])
return possible_set - remove_set
def is_solved():
for i in range(9):
for j in range(9):
if sudoku_grid[i][j] == 0:
return False
return True
def solve():
i = 0
j = 0
solved = False
possible = list()
while not solved:
if sudoku_grid[i][j] == 0:
print 'i', i
print 'j', j
box = check_box(i, j)
row = check_row(i)
col = check_col(j)
if len(list(box & row & col)) == 1:
sudoku_grid[i][j] = list(box & row & col)[0]
else:
sudoku_grid[i][j] = list(box & row & col)
if i == 8 and j == 8:
i = 0
j = 0
elif j < 8:
j += 1
else:
i += 1
j = 0
solved = is_solved()
solve()
print sudoku_grid
|
8702806a564f9689006a92d95b9b6dbb1ff8e875 | 24emmory/Python-Crash-Course | /simplestatsfunc.py | 668 | 4.375 | 4 | squares = [value**2 for value in range(1,11)]
print(squares)
squares = [value**2 for value in range(1,11)]
#start list with defined name and brackets to store
#expression to feed values from range generated values
#define the expression for the values you want to store in
#the new list
#a for loop to generate the numbers you want to feed* into
#the expression
#for loop ending in range to generate numbers
list = [value1**3 for value1 in range(1,5)]
print(list)
#for loop feeding values 1-4 into expression!
#note no colon is used
trendy = [trendy1*trendy1 for trendy1 in range(1,3)]
print(trendy)
numbers = [number**4 for number in range(1,11)]
print(numbers)
|
4fb0988ed05c8e8a56cd7ad5fb035149dc6d61e2 | juiceblend/spotify-country | /Comparison.py | 1,891 | 3.53125 | 4 | import Playlists
from math import sqrt
def get_comparisons(playlists):
temp_data = []
for playlist in playlists:
temp_data.append((playlist['name'], Playlists.playlist_audio_features_average(playlist)))
comparison_list = []
for index1 in range(len(temp_data)):
for index2 in range(index1):
distance = 0
for key in Playlists.ATTRIBUTES:
score1 = temp_data[index1][1][key]
score2 = temp_data[index2][1][key]
distance += (score1 - score2) ** 2
distance = round(sqrt(distance), 4)
comparison_list.append((temp_data[index1][0], temp_data[index2][0], distance))
return comparison_list
def comparison_sort_helper(data):
return data[2]
def sort_comparison_list(list):
list.sort(key=comparison_sort_helper)
def print_comparisons(playlists):
comparisons = get_comparisons(playlists)
sort_comparison_list(comparisons)
comparisons = [str(i) for i in comparisons]
f = open("Country_Comparisons.txt", "w")
for data in comparisons:
f.write(data + '\n')
f.close()
def get_country_comparisons(country):
comparisons = []
with open("Country_Comparisons.txt", "r") as reader:
lines = reader.readlines()
# print(lines) debug
for line in lines:
if country in line:
other_country = ''
for key in Playlists.TOP_PLAYLIST_DICT:
if key != country:
if key in line:
other_country = key
parts = line.split(',')
parts[2] = parts[2].replace(' ', '')
parts[2] = parts[2].replace(')', '')
parts[2] = parts[2].replace('\n', '')
comparisons.append((other_country, parts[2]))
return comparisons
|
2ae204bf7d1739caaa16e6e2aa8760897fa65826 | reinaldoboas/Curso_em_Video_Python | /Mundo_2/desafio047.py | 371 | 3.796875 | 4 | ### Curso em Vídeo - Exercicio: desafio047.py
### Link: https://www.youtube.com/watch?v=Qws8-E-YrlY
### Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.
# Fazendo um laço de repetição de 0 até 51, pulando de 2 em 2 para selecionar apenas os pares.
for num in range (0, 51, 2):
print(num, end=' - ')
print("FIM")
|
2d03cf006d86fb6934ae9da52505d1ce1bd7b926 | unleashed-coding/advent-of-code | /2018/01_1/python/sqdorte.py | 150 | 3.578125 | 4 | with open('input', 'r') as raw:
i = raw.read().strip().split('\n')
frequency = 0
for change in i:
frequency += int(change)
print(frequency) |
921a8ceb342a0e0eaba9aa2768b660baaaec6e11 | 3470f666a766a2691cb258a8711920/Python_HSE | /2week/problems/2-7/2-7.py | 147 | 3.640625 | 4 | h1 = int(input())
w1 = int(input())
h2 = int(input())
w2 = int(input())
if (h1 + w1) % 2 == (h2 + w2) % 2:
print("YES")
else:
print("NO")
|
249e60accc2dca90e05627651233ad199fd3659f | AttitudeL/AdventOfCode2017 | /days/day11.py | 2,042 | 3.625 | 4 | import os
INPUT_DIRECTORY = '../inputs/'
INPUT_FILE_EXTENSION = '_input.txt'
def load_input(input_file):
relative_path = os.path.join(os.path.dirname(__file__), INPUT_DIRECTORY + input_file)
with open(relative_path, 'r') as opened_file:
directions = opened_file.read()
return directions.split(',')
def part_one(directions):
coordinates = []
x = 0
y = 0
for direction in directions:
if 'n' == direction:
y += 2
elif 'ne' == direction:
x += 1
y += 1
elif 'se' == direction:
x += 1
y -= 1
elif 's' == direction:
y -= 2
elif 'sw' == direction:
x -= 1
y -= 1
elif 'nw' == direction:
x -= 1
y += 1
coordinates.append((x, y))
steps = 0
while abs(x) != abs(y):
if y > 0:
y -= 2
elif y < 0:
y += 2
steps += 1
return steps + abs(x)
def part_two(directions):
coordinates = []
x = 0
y = 0
max_x = 0
max_y = 0
for direction in directions:
if 'n' == direction:
y += 2
elif 'ne' == direction:
x += 1
y += 1
elif 'se' == direction:
x += 1
y -= 1
elif 's' == direction:
y -= 2
elif 'sw' == direction:
x -= 1
y -= 1
elif 'nw' == direction:
x -= 1
y += 1
if abs(x) + abs(y) > abs(max_x) + abs(max_y):
max_x = x
max_y = y
coordinates.append((x, y))
steps = 0
while abs(max_x) != abs(max_y):
if y > 0:
max_y -= 2
elif y < 0:
max_y += 2
steps += 1
return steps + abs(max_x)
if __name__ == '__main__':
current_file = os.path.splitext(os.path.basename(__file__))[0]
directions = load_input(current_file + INPUT_FILE_EXTENSION)
print part_one(directions)
print part_two(directions)
|
36a714f41f775000b95fa33da5e3d908f16bc5d2 | misataubis/pyladies | /03/retezce.py | 300 | 3.796875 | 4 | retezec = 'Ahoj'
print(retezec.upper())
print(retezec.lower())
print(retezec)
jmeno = input('Jaké je tvé jméno?')
prijmeni = input('Jaké je tvé přijmení?')
prvni_iniciala = jmeno[0].upper()
druha_iniciala = prijmeni[0].upper()
print('Tvoje inicály jsou: '+ prvni_iniciala + druha_iniciala)
|
6b92dd99dd731d35773ea15f68a95f33ce6d5d27 | wattaihei/ProgrammingContest | /Codeforces/CR580/probD.py | 2,548 | 3.78125 | 4 | class UnionFind():
# 作りたい要素数nで初期化
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def Find_Root(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.Find_Root(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def Unite(self, x, y):
x = self.Find_Root(x)
y = self.Find_Root(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
def isSameGroup(self, x, y):
return self.Find_Root(x) == self.Find_Root(y)
# ノードxが属する木のサイズ
def Count(self, x):
return -self.root[self.Find_Root(x)]
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
L = max(A).bit_length()
graph = [[] for _ in range(L)]
for i, a in enumerate(A):
for k in range(L):
if (1 << k) & a:
graph[k].append(i)
UF = UnionFind(N)
for k in range(L):
if not graph[k]: continue
for p in graph[k]:
UF.Unite(graph[k][0], p)
roots = set()
for i in range(N):
roots.add(UF.Find_Root(i))
dis = [-1]*N
checked = [False]*N
def bfs(s):
dis[s] = 0
c = 0
q = [s]
ans = -1
while q:
c += 1
qq = []
for p in q:
checked[p] = True
print(p, checked, dis)
for k in range(L):
if (1 << k) & A[p]:
for np in graph[k]:
print(np)
if checked[np]: continue
if dis[np] == -1:
print(dis)
qq.append(np)
dis[np] = c
else:
ans = dis[np] + c
return ans
q = qq
return -1
def dfs(p, d):
dis[p] = d
for k in range(L):
if (1 << k) & A[p]:
for np in graph[k]:
if dis[np] == -1:
dfs(np, d+1)
ans = N+1
for r in roots:
a = bfs(r)
if a != -1:
ans = min(ans, a)
if ans == N+1:
print(-1)
else:
print(ans) |
7a2f33fffde6a6d3a62594edf92cf9aa1584347c | sambasivaraokambala/Intro-to-Programming-with-Python | /if statement-codecrash.py | 270 | 3.984375 | 4 | #################################################
# if-statement user input example
# Shiva K
#################################################
deposit = input("Enter deposit amount:")
if deposit > 100:
print("You will get a free toast!")
print("Thanks")
|
19c0fb7f248e1182f59c349ccc04642b9515d17e | EugeneSchweiger/Hillel-HW | /edu/hillel/homework/task8.py | 371 | 3.578125 | 4 | import math
print("___________________________________")
print("Task8")
print("___________________________________")
txt1=input("Input first text block")
txt2=input("Input second text block")
print("You have entered %s and %s"
%(txt1,txt2))
mid1 = len(txt1)//2
mid2 = len(txt2)//2
txt3=(txt2[:mid2]+txt1+txt2[mid2:])
txt4=(txt1[:mid1]+txt3+txt1[mid1:])
print(txt4)
|
a5cd616aa6ccaa839492d32b36fd6b88343c9dcf | GaganGowda89/Practise_Python | /Employee.py | 1,108 | 4.125 | 4 | #!/usr/bin/python
class Employee:
'Common base class for employees'
empcount=0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empcount +=1
def displayCount(self):
print("Total Employee: %d" %Employee.empcount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
'First object of emloyee class'
emp1 = Employee("Somanna",20000)
'Second object of employee class'
emp2 = Employee("Maramma",30000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total employee %d" %Employee.empcount)
'Function to manipulate or access attributes'
emp1.age= 29
hasattr(emp1, 'age')
getattr(emp1, 'age')
setattr(emp1, 'age',32)
print("************ Employee Details ****************\n")
print("Name: ",emp1.name, ", Salary: ", emp1.salary, ", Age: ", emp1.age)
print("**** Class details *** \n")
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)
|
449aa3c3515013d90e14a469a4f65b0c499aabd4 | bovem/algorithms-1 | /SumProblems/three_sum_binary.py | 1,634 | 3.765625 | 4 | """ Implementing 3 sum problem with binary search
Takes n^2 log n time to converge"""
import sys
import timeit
from math import log2
def binary_search(arr, low, high, j):
arr_len = len(arr)
mid = int(low + (high-low)/2)
if(low >= high):
# Search left if less than mid
if(j < arr[mid]):
search(arr, low, mid-1, j)
# Seach right if greater than mid
elif(j > arr[mid]):
search(arr, mid+1, high, j)
# Element found at mid
elif(j == arr[mid]):
return 1
else :
return -1
class three_sum_binary:
def __init__(self, file):
self.time = 0
self.exptime = 0
with open(file, "r") as array:
self.arr = list(map(lambda x: int(x), array))
self.length = len(self.arr)
def binary(self):
start = timeit.default_timer()
found = 0
count = 0
for i in range(self.length):
for j in range(i+1, self.length):
found = binary_search(self.arr, 0, len(self.arr),
(-(int(self.arr[i]+self.arr[j]))))
if(found == -1):
break
else:
count += 1
stop = timeit.default_timer()
self.time = stop - start
def timed(self):
print("Runtime of Brute force algorithm : {}".format(self.time))
print("Expected runtime of Brute force algorithm : {}".format((self.length**2)*log2(self.length)))
threesum = three_sum_binary(sys.argv[1])
threesum.binary()
threesum.timed()
|
dd7d02366259563c4270ce0d678197e03680aca8 | dikshamenghmalani/Chaos-Game-Sierpinski-s-Triangle | /Seirpinskis_triangle.py | 1,013 | 3.96875 | 4 | import turtle
pen = turtle.Turtle()
def triangle_draw(length,side):
if(side == -1):
pen.color("black","#E5E4E2")
elif(side == 0):
pen.color("black","#837E7C")
elif(side == 1):
pen.color("black","#000000")
pen.begin_fill()
pen.setheading(180)
for i in range(3):
pen.right(120)
pen.forward(length)
pen.end_fill()
def sierpinski_triangle(n,length,side):
if(n == 1):
triangle_draw(length,side)
else:
sierpinski_triangle(n-1,length,-1)
pen.right(120)
pen.forward(length*2**(n-2))
sierpinski_triangle(n-1,length,0)
pen.left(120)
pen.forward(length*2**(n-2))
sierpinski_triangle(n-1,length,1)
pen.forward(length*2**(n-2))
length = 7
n = 7
sierpinski_triangle(n,length,-1)
turtle.done()
try:
turtle.bye()
except turtle.Terminator:
pass |
ba8cad36178d9d4b358a16d5d8bd9494574e4199 | JDTrujillo18/Python-Structures | /Stack.py | 1,092 | 3.53125 | 4 | import DLinkedList
class Stack(DLinkedList.DLinkedList):
def __init__(self, data=None):
super(Stack, self).__init__(data)
def __str__(self, arrows=False, stack=False, format=False):
if arrows:
copy = self.copy()
copy.reverse()
return copy.__str__(True)
elif stack:
self.reverse()
mystr = '\nStack:\nLength: ' + str(len(self)) + '\nTop: ' + str(self.head.data) + '\n'
for item in self:
mystr += ' ' + str(item) + '\n'
mystr += 'Bottom: ' + str(self.tail.data) + '\n'
self.reverse()
return mystr
elif format:
mystr = '\n'
self.reverse()
for item in self:
mystr += ' '+ str(item) + '\n'
self.reverse()
return mystr
else:
copy = self.copy()
copy.reverse()
return copy.__str__()
def push(self, value):
self.append(value)
def peek(self):
return self.tail.data
def is_empty(self):
if len(self) == 0:
return True
else:
return False
def arrows(self):
print(self.__str__(arrows=True))
def printstack(self):
print(self.__str__(stack=True))
def format(self):
print(self.__str__(format=True))
|
5297d270d2c7e0d3bc310f922724bfac04f42e79 | faiz687/CodingProblems | /CapitalizeMe.py | 312 | 3.9375 | 4 | def CapitalizeMe(a):
check = True
newstring = ""
for i in a:
if check == True:
newstring += i.upper()
check = False
else:
newstring += i
if i == " ":
check = True
print(newstring)
CapitalizeMe("evertything is in lower case") |
66adbee5ec4180022347723a7098dbf47e37d145 | citroen8897/Python_advanced | /Lecon_deux_/bibliotheque/livres.py | 2,392 | 3.625 | 4 | import re
class Livre:
def __init__(
self, id_livre: str, nom: str, author: str, year: str, triger: int
) -> None:
"""
Создаем объект класса Книга.
Необходимо передать пять атрибутов. Первые четыре - str. Пятый - int.
:param id_livre: id
:param nom: название
:param author: автор
:param year: год издания
:param triger: триггер (0 - книгу у читателя или 1 - книга в библи-ке)
"""
self.id_livre = id_livre
self.nom = nom
self.author = author
self.year = year
self.triger = triger
def __setattr__(self, key, value):
if key == 'id_livre':
while not value.isdigit():
print('Некорректный id!')
value = input('Введите корректный id: ')
self.__dict__[key] = int(value)
elif key == 'nom':
while not re.findall(r'\w', value):
print('Некорректное название книги!')
value = input('Введите корректно название книги: ')
self.__dict__[key] = value.title()
elif key == 'author':
while re.findall(r'[^a-zA-Zа-яА-Я, \s]', value):
print('Некорректный автор!')
value = input('Введите корректно автора книги: ')
self.__dict__[key] = value.title()
elif key == 'year':
while not value.isdigit() or len(value) != 4:
print('Некорректный год!')
value = input('Введите корректно год издания книги: ')
self.__dict__[key] = value
else:
self.__dict__[key] = value
def __str__(self):
return f'\nНазвание: {self.nom}\nАвтор: {self.author}\n' \
f'Год: {self.year}\nid: {self.id_livre}\n'
@classmethod
def faire_object_livre(cls, dict_data: dict):
return cls(
str(dict_data['id_livre']),
dict_data["nom"],
dict_data['author'],
dict_data['year'],
dict_data['triger']
)
|
797f2b050151c2a896db08652d09ce9b996a33a5 | pinstripezebra/Sp2018-Online | /students/darrell/wk1 - assignments/generator_solution.py | 953 | 3.71875 | 4 | import math
def intsum():
seq =[0]
while True:
if len(seq) == 1:
yield 0
else:
yield sum(seq)
seq.append(seq[-1] + 1)
def doubler():
n = 1
while True:
if n == 1:
yield 1
else:
yield n
n *= 2
def fib():
seq = [1]
while True:
yield seq[-1]
if len(seq) == 1:
seq.append(1)
else:
# add the last 2 numbers in seq and append
seq.append(sum(seq[-2:]))
def prime():
prime_numbers = []
x = 2
while True:
if is_prime(x):
prime_numbers.append(x)
yield prime_numbers[-1]
x += 1
def is_prime(n):
prime_num = False
if n in [2, 3, 5, 7]:
return True
for i in range(2, n):
if n % i == 0:
prime_num = False
break
else:
prime_num = True
return prime_num |
c7bc4fcdcbb3de8cea495c788e14a6ac495a0eeb | apolloparty/projet7 | /Class/Parser.py | 1,904 | 3.734375 | 4 | import json
import sys
class Parser:
"""
"""
def __init__(self, split_words):
self.split_words = split_words
def parser(self):
"""
Put a JSON stopwords list into an exploitable python list
"""
path = "ressources/fr-split/fr.json"
with open(path, encoding='utf-8') as french:
words = json.load(french) # JSON to list
return words
def compare(self, words):
"""
Compare every stop words with list of words and attribute
them a value, mix of both create a dictionnary
"""
i = 0
ponct = ["!", ".", "?"]
li = []
values = []
dictionary = {}
x = (len(self.split_words))
y = 0
if x == 2 or x == 1:
values.append(self.split_words[i])
if self.split_words[0][0].isupper:
li.append(0)
while i != len(self.split_words):
temp = words.count(f"{(self.split_words[i])}") # count stop words
temp2 = ponct.count(f"{(self.split_words[i])}") # count ponctuation char
if i != 0 and self.split_words[i][0].isupper(): # City/Place
values.append(self.split_words[i])
li.append(3)
elif temp >= 1: # Stop words
li.append(1)
elif temp2 == 1: # Ponctuation
li.append(2)
elif temp == 0 and i != 0: # Ignored
li.append(0)
i = i + 1
dictionary = dict(zip(self.split_words, li))
z = len(values) - 1 # number of last word
for i in values[z]:
if i == "." or i == "!" or i == "?":
values[z] = values[z][:-1] # remove last character
city = ' '.join([str(elem) for elem in values])
print(city)
return city
|
806a5de8a4516bbf04ec17d34b5dcf5d43f74458 | amihaylo/N-queens | /src/main.py | 1,594 | 4.09375 | 4 | from board import Board
import random
def solve_N_queens(n):
"""
Given n solve the N-queens problem
How to place N queens on an NxN grid
without any of them sharing the same
vertical, horizontal, and diagonal space
@return: the solution
@return: the # of attempts it took to achieve that solution
"""
#Init
rng = random.Random()
attempts = 1 #The number of attempts it took to find a solution
potential_sol = list(range(n))
# while True:
while True:
rng.shuffle(potential_sol)
curr_board = Board(potential_sol)
if curr_board.is_valid():
return {
"board":curr_board,
"attempts":attempts
}
attempts+=1
def run_single_solution(n):
# Solve the N qeen problem and display the board and # attempts
print("Running the {} Queen problem...".format(n))
solution = solve_N_queens(n)
board = solution["board"]
attempts = solution["attempts"]
print(board)
print("Number of attempts made before solving = {}".format(attempts))
def run_multiple_solutions(highest_n):
#Solve the N queen problem for everyting up to and including highest_n
for curr_n in range(4,highest_n+1):
solution = solve_N_queens(curr_n)
board = solution["board"]
attempts = solution["attempts"]
print("{:2}-Queen solved in {:8} attempts".format(curr_n, attempts))
def test():
pass
if __name__ == "__main__":
run_single_solution(8)
print("------------------")
run_multiple_solutions(10)
|
dfc2e427cfe5cd97012f9876072665acd72c1fa9 | thegamingcoder/leetcode | /345.reverse-vowels-of-a-string.py | 641 | 3.78125 | 4 | #
# [345] Reverse Vowels of a String
#
# https://leetcode.com/problems/reverse-vowels-of-a-string/description/
#
# algorithms
# Easy (39.56%)
# Total Accepted: 114.8K
# Total Submissions: 290.1K
# Testcase Example: '"hello"'
#
# Write a function that takes a string as input and reverse only the vowels of
# a string.
#
#
# Example 1:
# Given s = "hello", return "holle".
#
#
#
# Example 2:
# Given s = "leetcode", return "leotcede".
#
#
#
# Note:
# The vowels does not include the letter "y".
#
#
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
|
a277df92c186b8b4f7c71bc04402fca9c7e42670 | rebeccamello/Projetos-em-Python | /Sistema_coordenadas.gyp | 2,502 | 4.1875 | 4 | print('Digite o valor da origem do seu plano cartesiano:')
x = int(input('Abscissa (eixo x): '))
y = int(input('Ordenada (eixo y): '))
n = int(input('Indique a quantidade de pontos: '))
import math
def distancia():
global ponto_maior_x
global ponto_maior_y
global dist_maior
global ponto_menor_x
global ponto_menor_y
global dist_menor
global primeiro
global segundo
global quarto
global terceiro
dist_maior = 0
dist_menor = 1000
ponto_maior_x = 0
ponto_maior_y = 0
ponto_menor_x = 0
ponto_menor_y = 0
primeiro = 0
segundo = 0
terceiro = 0
quarto = 0
for i in range(1, n+1):
print('\nInforme o valor da abscissa', i, ':')
global absc
absc = int(input())
print('Informe o valor da ordenada', i, ':')
global orde
orde = int(input())
# Qual quadrante
if (absc > x) and (orde > y):
print('Ponto (',absc,',',orde,') está no 1o quadrante.')
primeiro = primeiro + 1
elif (absc < x) and (orde > y):
print('Ponto (',absc,',',orde,') está no 2o quadrante.')
segundo = segundo + 1
elif (absc < x) and (orde < y):
print('Ponto (',absc,',',orde,') está no 3o quadrante.')
terceiro = terceiro + 1
elif (absc > x) and (orde < y):
print('Ponto (',absc,',',orde,') está no 4o quadrante.')
quarto = quarto + 1
else:
print('Ponto (',absc,',',orde,') esta na origem.')
# Distancia ate a origem
dist = math.sqrt(((orde - y) ** 2) + ((absc - x) ** 2))
if dist > dist_maior:
dist_maior = dist
ponto_maior_x = absc
ponto_maior_y = orde
if dist < dist_menor:
dist_menor = dist
ponto_menor_x = absc
ponto_menor_y = orde
distancia()
print('\n\nPonto (',ponto_menor_x, ',',ponto_menor_y,') eh o mais proximo, distancia =', format(dist_menor, '.2f'))
print('Ponto (',ponto_maior_x, ',',ponto_maior_y,') eh o mais distante, distancia =', format(dist_maior, '.2f'))
# Ver pq o mais proximo da errado algumas vezes
def percentual():
global conta1
conta1 = (primeiro * 100) / n
global conta2
conta2 = (segundo * 100) / n
global conta3
conta3 = (terceiro * 100) / n
global conta4
conta4 = (quarto * 100) / n
percentual()
print('\n\nPorcentagem de pontos o 1o quadrante', conta1, '%.')
print('\nPorcentagem de pontos o 2o quadrante', conta2, '%.')
print('\nPorcentagem de pontos o 3o quadrante', conta3, '%.')
print('\nPorcentagem de pontos o 4o quadrante', conta4, '%.')
|
0eb4f1df836ed541ca2219538e7b55beeee37040 | NikhilDinesan11/Data-Structure-in-Python | /SelectionSort.py | 366 | 3.984375 | 4 | def selection_sort(nums):
for i in range(len(nums)-1):
index = i
for j in range(i+1,len(nums)):
if nums[j]<nums[index]:
index=j
if index!= i:
swap(nums,i,index)
return nums
def swap(nums,i,j):
temp=nums[i]
nums[i]=nums[j]
nums[j]=temp
nums=[3,2,6,9,4,8]
print(selection_sort(nums)) |
a4ff6eed9dfcd8f0e7a6ef07b0ac89440e81251c | koskot77/leetcode | /1457paths.py | 1,639 | 3.953125 | 4 | # https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/submissions/
# good: 1) broke it down to subproblems
# 2) figured bottom-up pattern
# errors: 1) python syntax
# 2) attention to details
# 3) over-complicated return argument
# 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 check(self, path):
counts = {}
for i in path:
if i in counts:
counts[i] += 1
else:
counts[i] = 1 # error #1: 1 not 0
odd = 0
for i,j in counts.iteritems():
if (j%2)==1: odd += 1
if (len(path)%2)==1 and odd == 1: return True
if (len(path)%2)==0 and odd == 0: return True
return False
def helper(self, node, path):
path += [node.val] # error #2: do it before not after anything
if node.left==None and node.right==None:
if self.check(path): return 1
path_new = copy.deepcopy(path)
count = 0 # error #3: no need to make it an argument
if node.left != None:
count = self.helper(node.left, path_new)
path_new = path
if node.right != None:
count += self.helper(node.right, path_new)
return count
def pseudoPalindromicPaths (self, root):
"""
:type root: TreeNode
:rtype: int
"""
path = []
return self.helper(root,path)
|
06704b5dc45801fce2cb78544d71475b13d49df0 | jgartsu12/my_python_learning | /python_data_structures/tuples/add_elements_lev_reassignment.py | 1,584 | 4.3125 | 4 | # How to Add Elements to a Tuple by Leveraging Re-Assignment
# leverage reassignment to create a new tuple
# tuples are immutable !!
# title #subheading # content
post = ('Python Basics', 'Intro guide to python', 'Some cool python content') # hard coded tuple
# this will come from databases and api with tons of data u cant see al or know all
print(id(post))
# different id from below because it is another object
# post = post + ('published') # this wouldnt be treated like a tuple but a math expression pemdas such as (2*2) + 5 => order of ops == > TypeError can only concat a tuple with another tuple -- it views it as a str + tuple
# post = post + ('published',) # so to not treat liek order ops need a ',' so python treats it like a tuple
# overrides to make a new one
post += ('published',) # mass assignmnet operator -- eqaul to post = post + ('published',)
print(id(post)) # id function in python - gives references and unique id for an object -- in memory there is a very specific spot in memory where every obj is stored
# prints specific id for this post stored in memory (long identifier with numebrs)
# this id is not the same as the original tuple since they are different tuples due to reassignment --- IMMUTABLE ---
title, sub_heading, content, status = post # tuple unpacking # added status by making a new tuple called status via reassignment and override it
print(title)
print(sub_heading)
print(content)
print(status) |
b43d23a473a6eede050917991d2fa53548a2957d | DrunkWizard/Python-Tasks | /Polynom/Solution.py | 2,849 | 3.65625 | 4 | def get_numbers(number1, number2):
out1 = ''
out2 = ''
if number1 != 0 and number2 != 0:
if number1 != 1 and number1 != -1:
out1 = str(number1)
if number1 == -1:
out1 += '-'
out1 += 'x'
if number2 != 1:
out2 = '^' + str(number2)
out2 += '+'
return out1 + out2
def match_polynoms(self, other):
if not isinstance(other, Polynom):
other = Polynom(other)
if len(self.coefficients) >= len(other.coefficients):
while len(other.coefficients) != len(self.coefficients):
other.coefficients.insert(0, 0)
else:
while len(self.coefficients) != len(other.coefficients):
self.coefficients.insert(0, 0)
return self, other
class Polynom:
def __init__(self, *coefficients):
self.coefficients = list(coefficients)
def __str__(self):
degree = len(self.coefficients) - 1
out = ''
while degree > 0:
out += get_numbers(self.coefficients[len(self.coefficients) - 1 - degree], degree)
degree -= 1
if self.coefficients[len(self.coefficients) - 1] != 0:
return (out + str(self.coefficients[len(self.coefficients) - 1])).replace('+-', '-')
else:
return out[:len(out) - 1].replace('+-', '-')
def __call__(self, x):
answer = 0
for i in range(len(self.coefficients)):
answer += float(self.coefficients[len(self.coefficients) - (i + 1)]) * float(x) ** float(i)
return answer
def __add__(self, other):
self, other = match_polynoms(self, other)
result_coeff = []
for i in range(len(self.coefficients)):
result_coeff.append(self.coefficients[i] + other.coefficients[i])
return Polynom(*result_coeff)
def __sub__(self, other):
self, other = match_polynoms(self, other)
result_coeff = []
for i in range(len(self.coefficients)):
result_coeff.append(self.coefficients[i] - other.coefficients[i])
return Polynom(*result_coeff)
def __mul__(self, other):
self, other = match_polynoms(self, other)
result_coeff = [0 for i in range((len(self.coefficients) - 1) * 2 + 1)]
for i in range(len(self.coefficients)):
for j in range(len(self.coefficients)):
result_coeff[len(self.coefficients) - (i + 1) + len(self.coefficients) - (j + 1)] += self.coefficients[i] * other.coefficients[j]
result_coeff.reverse()
return Polynom(*result_coeff)
def __eq__(self, other):
if isinstance(other, Polynom):
return self.coefficients == other.coefficients
else:
return len(self.coefficients) == 1 and self.coefficients[0] == other
a = Polynom(-1,2,4,-5,111,1,1,0,1,1,-4,0,11,12,0)
print(a) |
0ca2f5086c464dec47f21f529d99d52eb7764cbd | jingz/try-lang | /python/class.py | 1,236 | 3.8125 | 4 | class Person(object):
__firstname = "First Name" # private static variable
__lastname = "Last Name"
_firstname = __firstname # public static variable
def __wrap():
# dynamic private class method
@classmethod
def __xxx(cls):
return 'xxx inside wrap'
return __xxx
xxx = __wrap()
_l = lambda x: x*2
b = _l(10)
print "inside class", b
ll = staticmethod(_l)
__ll = staticmethod(_l) # private
def __init__(self, firstname, lastname):
self.__firstname = firstname
self.__lastname = lastname
pass
def __str__(self):
return "First Name: %s , Last Name: %s" % (self.__firstname, self.__lastname)
@property
def fullname(self):
return "%s %s" % (self.__firstname, self.__lastname)
@fullname.setter
def fullname(self, value):
return "%s %s" % value.split(' ')
def class_name():
return "Person"
@classmethod
def some_class_method(self):
return 'SOME CLASS METHOD'
p = Person("Sarunyoo", "XX");
print p
print p.fullname
print Person.ll(6)
print "call outside class", Person.b
print Person._firstname
print Person.xxx()
print Person.some_class_method()
|
11aedd30a84fbbdae2bf89fffedbed6edd0d8c2e | lemon89757/homework | /exe_5.py | 556 | 3.75 | 4 | import math
def quadratic_equation(a,b,c):
characteristic_equation = b*b-4*a*c
if characteristic_equation<0:
x1=x2='no solution'
return x1,x2
elif characteristic_equation==0:
x1=x2=-(b/(2*a))
return x1,x2
else:
sqrt_characteristic_equation = math.sqrt(characteristic_equation)
x1 = (-b + sqrt_characteristic_equation)/(2*a)
x2 = (-b - sqrt_characteristic_equation)/(2*a)
return x1, x2
print(quadratic_equation(a= int(input("a=")),b= int(input("b=")),c= int(input("c="))))
|
b58f89bc14cd8885ec78b639971bceb5a08aa469 | LukeDeWaal/WingGeo | /src/frontend/DraggablePlot.py | 3,786 | 3.78125 | 4 | import math
import matplotlib.pyplot as plt
from matplotlib.backend_bases import MouseEvent
class DraggablePlot(object):
u""" An example of plot with draggable markers """
def __init__(self, figure = None, xlim: tuple = None, ylim: tuple = None):
self._figure, self._axes, self._line = figure, None, None
self._dragging_point = None
self._points = {}
self.xlim = xlim if xlim is not None else (0, 10)
self.ylim = ylim if ylim is not None else (0, 200)
self._init_plot()
def _init_plot(self):
self._figure = plt.figure("Example plot")
axes = plt.subplot(1, 1, 1)
axes.set_xlim(*self.xlim)
axes.set_ylim(*self.ylim)
axes.grid(which="both")
self._axes = axes
self._figure.canvas.mpl_connect('button_press_event', self._on_click)
self._figure.canvas.mpl_connect('button_release_event', self._on_release)
self._figure.canvas.mpl_connect('motion_notify_event', self._on_motion)
plt.show()
def _update_plot(self):
if not self._points:
self._line.set_data([], [])
else:
x, y = zip(*sorted(self._points.items()))
# Add new plot
if not self._line:
self._line, = self._axes.plot(x, y, "b", marker="o", markersize=10)
# Update current plot
else:
self._line.set_data(x, y)
self._figure.canvas.draw()
def _add_point(self, x, y=None):
if isinstance(x, MouseEvent):
x, y = float(x.xdata), float(x.ydata)
self._points[x] = y
return x, y
def _remove_point(self, x, _):
if x in self._points:
self._points.pop(x)
def _find_neighbor_point(self, event):
u""" Find point around mouse position
:rtype: ((int, int)|None)
:return: (x, y) if there are any point around mouse else None
"""
distance_threshold = 3.0
nearest_point = None
min_distance = math.sqrt(2 * (100 ** 2))
for x, y in self._points.items():
distance = math.hypot(event.xdata - x, event.ydata - y)
if distance < min_distance:
min_distance = distance
nearest_point = (x, y)
if min_distance < distance_threshold:
return nearest_point
return None
def _on_click(self, event):
u""" callback method for mouse click event
:type event: MouseEvent
"""
# left click
if event.button == 1 and event.inaxes in [self._axes]:
point = self._find_neighbor_point(event)
if point:
self._dragging_point = point
else:
self._add_point(event)
self._update_plot()
# right click
elif event.button == 3 and event.inaxes in [self._axes]:
point = self._find_neighbor_point(event)
if point:
self._remove_point(*point)
self._update_plot()
def _on_release(self, event):
u""" callback method for mouse release event
:type event: MouseEvent
"""
if event.button == 1 and event.inaxes in [self._axes] and self._dragging_point:
self._dragging_point = None
self._update_plot()
def _on_motion(self, event):
u""" callback method for mouse motion event
:type event: MouseEvent
"""
if not self._dragging_point:
return
if event.xdata is None or event.ydata is None:
return
self._remove_point(*self._dragging_point)
self._dragging_point = self._add_point(event)
self._update_plot()
if __name__ == "__main__":
plot = DraggablePlot() |
95af36bbb8f4c1c940038054d0d5194bd6ef8271 | koryun23/python-DS-and-Algorithms | /heap_sort.py | 742 | 3.71875 | 4 | def max_heapify(arr, heap_size, i):#[43,53,12,324,34,234,2]
left = 2 * i + 1
right = 2 * i + 2
largest = i
if left < heap_size and arr[left] > arr[largest]:
largest = left
if right < heap_size and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
max_heapify(arr, heap_size, largest)
def build_heap(arr):
heap_size = len(arr)
for i in range (heap_size//2,-1,-1):
max_heapify(arr,heap_size, i)
return arr
def heapsort(arr):
heap_size = len(arr)
build_heap(arr)
for i in range(heap_size-1,0,-1):
arr[0], arr[i] = arr[i], arr[0]
heap_size -= 1
max_heapify(arr, heap_size, 0)
|
f3a626637ffe01d5879c1161edf80fae5e947473 | danofa/coursework | /mitx6.00/Week3.py | 1,384 | 4.15625 | 4 | #week 3 definitions
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
result = 1
while exp > 0:
result *= base
exp -= 1
return result
def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
if exp > 0:
return base * recurPower(base, exp-1)
else:
return 1
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
midCharIndex = len(aStr) / 2
if aStr == '':
return False
if len(aStr) == 1:
return aStr == char
if char == aStr[midCharIndex]:
return True
elif char > aStr[midCharIndex]:
return isIn(char, aStr[midCharIndex+1:])
else:
return isIn(char, aStr[0:midCharIndex])
def semordnilap(str1, str2):
'''
str1: a string
str2: a string
returns: True if str1 and str2 are semordnilap;
False otherwise.
'''
if len(str1) != len(str2):
return False
elif len(str1) == 1:
return str1 == str2
if str1[0] == str2[-1]:
return semordnilap(str1[1:], str2[:-1])
else:
return False
|
9b0f26fc4cc3f08fd80eea8fc7c4424ce2c9bbfc | jramirez901/Python-Design-Project- | /Python design tapestry.py | 616 | 3.546875 | 4 |
from RamirezFunctions import *
import turtle
bob = turtle.Turtle()
bob.speed(0)
turtle.bgcolor("black")
for times in range(256):
bob.circle(120)
bob.color("purple")
bob.forward(160)
bob.backward(160)
bob.left(79)
bob.circle(130)
bob.color("blue")
bob.forward(200)
bob.backward(200)
bob.left(79)
bob.circle(150)
bob.color("white")
bob.forward(260)
bob.backward(260)
bob.left(72)
bob.circle(160)
bob.color("blue")
bob.forward(260)
bob.backward(260)
bob.left(72)
|
e1dcf3339395cb53e346052a57ecf1bde73e630a | Jesuvi27/Best-Enlist-2021 | /day6.py | 1,221 | 4.53125 | 5 | 1)Write a Python script to merge two Python dictionaries
Ans:
a={"apple":"orange","red":"orange"}
b={"grapes":"banana","voilet":"yellow"}
c=a|b
print(c)
OUTPUT:
{'apple': 'orange', 'red': 'orange', 'grapes': 'banana', 'voilet': 'yellow'}
2)Write a Python program to remove a key from a dictionary
Ans:
name = {"kalai":"21","kayal":"17","maran":"22"}
removed_value = name.pop('kayal')
print ("The dictionary after remove is : " + str(name))
print ("The removed key's value is : " + str(removed_value))
OUTPUT:
The dictionary after remove is : {'kalai': '21', 'maran': '22'}
The removed key's value is : 17
3)Write a Python program to map two lists into a dictionary
Ans:
Name = ['Kalai','Kayal','Maran']
Num = ['24','17','22']
Data = dict(zip(Name,Num))
print(Data)
OUTPUT:
{'Kalai': '24', 'Kayal': '17', 'Maran': '22'}
4)Write a Python program to find the length of a set
Ans:
fruits={"apple","orange","grapes","kiwi"}
print(len(fruits))
OUTPUT:
4
5)Write a Python program to remove the intersection of a 2nd set from the 1st set
Ans:
a={5,3,2,4,1}
b={4,3,1,2,6}
a.difference_update(b)
print(a)
print(b)
OUTPUT:
{5}
{1, 2, 3, 4, 6}
|
dd8abf39cb444cb0682229f8998db22a05acb1ba | AgrimNautiyal/Problem-solving | /linked_list/reverse_linkedlist/reverse_linkedlist_iterative.py | 324 | 4.03125 | 4 | #question url : https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1
def reverseList(head):
# Code here
current = head
prev= None
next = None
while(current):
next = current.next
current.next=prev
prev= current
current = next
return prev
|
fdb529b462f198477f2a5be6ef0aab9f691099e0 | blahu/pynet-mat | /LearnPythonCourse/class8/ex1.py | 3,402 | 3.921875 | 4 | #!/usr/bin/env python
"""
Class 8, was 6
Exercise 1, was 3
Author Mat
"""
__author__ = 'mateusz'
"""
Class6
"""
"""
Class8
I. Re-using the IP address validation function created in Class #6, exercise3;
create a Python module that contains only this one ip validation function.
A. Modify this Python module such that you add a set of tests into the
module. Use the __name__ == '__main__' technique to separate the test code
from the function definition. In your test code, check the validity of each of
the following IP addresses (False means it should fail; True means it should
pass the IP address validation).
test_ip_addresses = {
'192.168.1' : False,
'10.1.1.' : False,
'10.1.1.x' : False,
'0.77.22.19' : False,
'-1.88.99.17' : False,
'241.17.17.9' : False,
'127.0.0.1' : False,
'169.254.1.9' : False,
'192.256.7.7' : False,
'192.168.-1.7' : False,
'10.1.1.256' : False,
'1.1.1.1' : True,
'223.255.255.255': True,
'223.0.0.0' : True,
'10.200.255.1' : True,
'192.168.17.1' : True,
}
B. Execute this module--make sure all of the tests pass.
C. Import this module into the Python interpreter shell. Make sure the
test code does not execute. Also test that you can still correctly call the ip
validation function.
"""
def validate_ip_address (ip_address) :
"""
3a.Convert the IP address validation code (Class4, exercise1) into a function,
take one variable 'ip_address' and return either True or False (depending on
whether 'ip_address' is a valid IP). Only include IP address checking in the
function--no prompting for input, no printing to standard output.
"""
octets = ip_address.split(".")
if len(octets) != 4:
return False
else:
a,b,c,d = octets
try:
int_a = int(a)
int_b = int(b)
int_c = int(c)
int_d = int(d)
except ValueError as e:
# int() conversion failed:
return False
# check 1st octet
if int_a < 1 or int_a > 223 or int_a == 127:
return False
# check 2nd 3rd and 4th octet
elif ( (int_b not in range (0, 256)) or
(int_c not in range (0, 256)) or
(int_d not in range (0, 256))) :
return False
# check 169.254.x.x
elif int_a == 169 and int_b == 254:
return False
# validated as an IP address!
return True
#ENDOF def validate_ip_address
if __name__ == '__main__':
test_ip_addresses = {
'192.168.1' : False,
'10.1.1.' : False,
'10.1.1.x' : False,
'0.77.22.19' : False,
'-1.88.99.17' : False,
'241.17.17.9' : False,
'127.0.0.1' : False,
'169.254.1.9' : False,
'192.256.7.7' : False,
'192.168.-1.7' : False,
'10.1.1.256' : False,
'1.1.1.1' : True,
'223.255.255.255': True,
'223.0.0.0' : True,
'10.200.255.1' : True,
'192.168.17.1' : True,
}
for test_ip, test_result in test_ip_addresses.items():
result = validate_ip_address ( test_ip )
if result == test_result:
result_text = 'ok'
else:
result_text = 'failed, was {} should be {}'.format (result, test_result)
print "{:.<30}{}".format (test_ip + ' ', result_text)
|
6714b8674190d7de9359422bf256a7b55aa1c38c | sogoagain/problem-solving-and-algorithms | /codeit/01_ Recursion/sum_of_digits.py | 333 | 3.546875 | 4 | # n의 각 자릿수의 합을 리턴
def sum_digits(n):
# base case
if n < 10:
return n
# recursive case
n, remainder = divmod(n, 10)
return remainder + sum_digits(n)
# 테스트
print(sum_digits(22541))
print(sum_digits(92130))
print(sum_digits(12634))
print(sum_digits(704))
print(sum_digits(3755))
|
278df1fe826cdb3133510067df217d80e7468169 | rafaelperazzo/programacao-web | /moodledata/vpl_data/303/usersdata/296/72129/submittedfiles/testes.py | 247 | 4.125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
a = 3
b = 5
c = 10
if a < b:
print("Comando 1")
else:
if a < c:
print("Comando 2")
else:
if b < c:
print("Comando 3")
print("Pronto")
|
a01798f4c8759c74afc3b70d03ffefa9c38bc0b1 | Samukat/WordsOnline | /ABencoder.py | 644 | 3.515625 | 4 | def encode(ToCode):
rm = ToCode%26
tt = ToCode//26
def toCode(num, base):
if num//26 > 0:
return toCode(num//26, 65) + toCode(num%26, 65)
else:
return chr(base + num)
return toCode(tt,65) + toCode(rm,97)
def decode(ToDecode):
code = [ord(item) for item in ToDecode][::-1]
num = 0
for i in range(len(code)):
if code[i] >= 97:
num += code[i] - 97
elif code[i] >= 65:
num += (code[i] - 65) * (26**i)
return num
if __name__ == "__main__":
b = 421231345
print(encode(b))
print(decode(encode(b)))
|
3428ee3ef4c3c5d11691bae26172599c11f75c3b | edu-athensoft/stem1401python_student | /py200912f_python2m7/day04_201003/file_4_read.py | 128 | 3.53125 | 4 | """
open a file in read mode
"""
f = open("file5_mode_r.txt",'r')
# read the whole data in the file
print(f.read())
f.close() |
21cd6bc193d48fb27145d74273472ca201f6a6c1 | macnaer/Python-Lessons- | /02. loops/start.py | 614 | 3.796875 | 4 | import random
# exit = True
# while exit:
# a = int(input("0. Exit "))
# if a == 0:
# exit = False
# a = int(input("Enter digit: "))
# i = 1
# factorial = 1
# while i < a:
# factorial *= i
# i += 1
# print("Факторіал числа", a, " = ", factorial)
# count = 10
# for i in range(1, count):
# for j in range(1, 10):
# print(i * j, end="\t")
# print("\n")
days = 0
counter = 0
while days <= 7:
#a = int(input("Temp = "))
a = random.randrange(-50, 50)
print("random number => ", a)
if a > 10:
counter += 1
days += 1
print(counter)
|
7157cb8a1d1c4c02f4696e31232af122afef39f8 | SalvadorGuido/BayesNetworkLab | /BayesNetworkLab.py | 630 | 3.671875 | 4 |
class Node(object):
def __init__(self):
self.name = None
self.parents = None
self.prob = None
def createNodes(nodes,network):
for item in nodes:
node = Node()
node.name = item
node.parents = []
node.prob = {}
network.append(node)
# def assignProb(network):
# for item in network:
bnetwork = []
p = []
q = []
n = list(input().split(','))
for i in range(0, int(input()),1):
p.append(input())
for i in range(0, int(input()), 1):
q.append(input())
print(n)
print(p)
print(q)
createNodes(n,bnetwork)
for item in bnetwork:
print(item.name) |
f7a0d6fc666616853adc7c06bd2daf2e2e2285cc | PhoenixBureau/TheGeneralProgram | /by.py | 1,838 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''
_ -> 0 "Nothing"
○ -> 100 "I exist but I'm empty and have no friends."
(A)B -> 1AB
◎ -> 1 100 0
○○ -> 1 0 100
◎○ -> 1 100 100
○◎ -> 1 0 11000
◎◎ -> 1 100 11000
'''
#: Depth-first encoding of forms.
encode = lambda f: '1' + encode(f[0]) + encode(f[1:]) if f else '0'
#: Decode paths from encoder.
decode = lambda path: _decode(iter(path))[0]
def _decode(path):
if next(path) == '0':
return (), path
A, path = _decode(path)
B, path = _decode(path)
return (A,) + B, path
#: Depth-first encoding of forms.
encode_breadth = lambda f: '1' + encode_breadth(f[1:]) + encode_breadth(f[0]) if f else '0'
#: Decode paths from encoder.
decode_breadth = lambda path: _decode_breadth(iter(path))[0]
def _decode_breadth(path):
if next(path) == '0':
return (), path
B, path = _decode_breadth(path)
A, path = _decode_breadth(path)
return (A,) + B, path
def _s(shell, do_special=False):
s = ''.join(map(str, shell)).replace(',', '').replace(' ', '')
if do_special:
s = s.replace('(())', '◎').replace('()', '○')
return s
def concat(*paths):
if not paths:
return '0'
return ''.join([path[:-1] for path in paths[:-1]] + [paths[-1]])
if __name__ == '__main__':
a = ()
b = ((),)
c = (((),),)
d = (((),),(), )
e = ((), ((),))
FO = (a, b, c, d, e)
for shell in FO:
print _s(shell, True), '->', encode(shell), '->', _s(decode_breadth(encode(shell)), True)
for shell in FO:
shell = (shell,) * 2
print _s(shell, True), '->', encode(shell), '->', _s(decode_breadth(encode(shell)), True)
for shell in FO:
shell = (shell,) * 3
print _s(shell, True), '->', encode(shell), '->', _s(decode_breadth(encode(shell)), True)
def foo():
new_forms = sorted(set(map(decode, forms) + map(decode_breadth, forms)))
|
b1aceadbe41227e3671a78824a526a1fda4099ff | thanhpham312/ACIT2515Final | /models/transaction.py | 1,654 | 3.671875 | 4 | class Transaction():
'''
Model for a transaction log
Attributes:
__account: the account the fees belong to
__time: time of the transaction
__type: type of the transaction
__balance_before: the account balance before the transaction
__balance_after: the account balance after the transaction
__balance_before: status of the transaction
__description: description of the transaction
Methods:
_to_dict: a dictionary version of the transaction class
'''
def __init__(self, account, time, type, balance_before, balance_after, status, description):
self.__account = account
self.__time = time
self.__type = type
self.__balance_before = balance_before
self.__balance_after = balance_after
self.__status = status
self.__description = description
@property
def time(self):
return self.__time
@property
def type(self):
return self.__type
@property
def balance_before(self):
return self.__balance_before
@property
def balance_after(self):
return self.__balance_after
@property
def status(self):
return self.__status
@property
def description(self):
return self.__description
def _to_dict(self):
return {
"time": str(self.__time),
"type": self.__type,
"balance_before": self.__balance_before,
"balance_after": self.__balance_after,
"status": self.__status,
"description": self.__description
}
|
6ed9b32635a4bcbebd5a9465d65bf42dc14c120b | Zandela/Python_Work | /04/list_control.py | 2,146 | 4.3125 | 4 | # 日期:2020-03-04
# 作者:YangZai
# 功能:操作列表
# 4-1 比萨
pizzas = ['egg yolk shrimp pizza', 'hawaiian pizza', 'mashed potato pizza']
for pizza in pizzas:
print('I like ' + pizza)
print('I really love pizza!\n')
# 4-2 动物
animals = ['cat', 'dog', 'bird']
for animal in animals:
print('A ' + animal + ' would make a great pet')
print('Any of these animals would make a great pet!\n')
# 4-3 数到20
for value in range(1, 21):
print(value)
print()
# 4-4 一百万
'''
values = []
for value in range(1, 1000001):
values.append(value)
print(value)
'''
# 4-5 计算1~1000000的总和
values = [value for value in range(1, 1000001)]
print(min(values))
print(max(values))
print(sum(values))
print()
# 用时0.5s
# 4-6 1~20的奇数
odds = [odd for odd in range(1, 21, 2)]
for value in odds:
print(value)
print()
# 4-7 3~30被3整除的数字
numbers = [number for number in range(3, 31, 3)]
for value in numbers:
print(value)
print()
# 4-7 3~30被3整除的数字
cubes = [cube ** 3 for cube in range(1, 11)]
for value in cubes:
print(value)
print()
# 4-8 切片
my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print('The first three items in the list are:')
print(my_foods[:3])
print('Three items form the middle of the list are:')
print(my_foods[1:4])
print('The last three items in the list are:')
print(my_foods[2:])
print()
# 4-9 你的比萨和我的比萨
friend_pizzas = pizzas[:]
pizzas.append('assorted sausage pizza')
friend_pizzas.append('chicken mushroom pizza')
print('My favorite pizzas are:')
for pizza in pizzas:
print(pizza)
print('\nMy friend\'s favorite pizzas are:')
for pizza in friend_pizzas:
print(pizza)
# 注意:friend_pizzas = pizzas 行不通,结果会输出相同的列表
print()
# 4-13 元组
foods = ('扬州炒饭', '番茄鸡蛋面', '卤肉飯', '清蒸鲈鱼', '紫菜汤')
for food in foods:
print(food)
# 尝试修改其中一个元素会发生错误
#foods[0] = '白饭'
foods = ('扬州炒饭', '番茄鸡蛋面', '紫菜泡饭', '清蒸鲈鱼', '鲫鱼汤')
print('\n修改后的菜单:')
for food in foods:
print('\t' + food) |
21e5bf4123ab27b4e35ba0446c9e1a21d690c875 | JoshuaP199/Games_Project | /Hangman.py | 5,234 | 3.53125 | 4 | ###############################
# Created by Gillian Covillo #
# @gcovillo #
###############################
def bodyLeft(bodyParts, guessWord):
if bodyParts == 0:
print(" ______")
print("| |")
print("| (- -)")
print("| __|__")
print("| | ")
print("|_ / \\")
elif bodyParts == 1:
print(" ______")
print("| |")
print("| (- -)")
print("| __|")
print("| | ")
print("|_ / \\")
elif bodyParts == 2:
print(" ______")
print("| |")
print("| (- -)")
print("| |")
print("| | ")
print("|_ / \\")
elif bodyParts == 3:
print(" ______")
print("| |")
print("| (- -)")
print("| |")
print("| | ")
print("|_ \\")
elif bodyParts == 4:
print(" ______")
print("| |")
print("| (- -)")
print("| |")
print("| | ")
print("|_")
elif bodyParts ==5:
print(" ______")
print("| |")
print("| (- -)")
print("|")
print("|_")
else:
print("YOU ARE DEAD!!!")
print("The word was ", guessWord)
def displayWord(guessWord, lettersGuessed):
r = len(guessWord)
if len(lettersGuessed) == 0:
print(r*" _ ")
else:
holder = ["_"]*r
for letter in lettersGuessed:
letterLocations = []
i = 0
for l in guessWord:
if letter == l:
letterLocations.append(i)
i+=1
for ll in letterLocations:
holder[ll] = letter
stringy = ""
for thingy in holder:
stringy+= " "
stringy += thingy
stringy+= " "
return stringy
def chooseWord():
import random
words = ['apple', 'nutmeg', 'pineapple', 'cat', 'pengolin', 'india', 'turkey', 'bicycle', 'python', 'programming', 'netflix', 'wonderland', 'cows', 'vegetarian', 'helpful', 'college',
'linux', 'horse', 'necklace', 'safe', 'motorboat', 'father', 'relationship', 'murder', 'arsenic', 'vampire', 'twilight', 'wizard', 'socks', 'farmer', 'glass', 'grandparents',
'flowers', 'rose', 'wine', 'park', 'hummus', 'christmas', 'kangaroo', 'books', 'island',
'woolgthering', 'psithurism', 'fumadiddle', 'novaturient', 'sempiternal', 'gigil', 'imbroglio', 'torpid', 'neologize', 'sarang', 'voorpret', 'hiraeth', 'degust', 'sciolist',
'gegenschien', 'antapology', 'petrichor', 'quixotic', 'anagnorisis', 'alexithymia', 'obviate',
'flummox', 'dowdy', 'nincompoop', 'muesli', 'myopic', 'bamboozle', 'phyllo', 'thwart', 'brouhaha', 'zeal', 'pneumatic', 'noxious', 'flimflam', 'abomasum', 'wanderlust']
return random.choice(words)
'''
#########################
# Geeks for Geeks #
#########################
def removeChar(s, c) : #
counts = s.count(c) #
s = list(s) #
while counts : #
s.remove(c) #
counts -= 1 #
s = '' . join(s) #
return s #
#########################
# Geeks for Geeks #
#########################
'''
def hangman(o):
if o == 'c':
guessWord = chooseWord()
else:
print("Player 1: Please Enter your word away from Player 2")
guessWord = input("Enter Word Here: ").lower()
bodyParts = 0
guessedLetters = []
correctLetters = []
bodyLeft(bodyParts, guessWord)
displayWord(guessWord, correctLetters)
while True:
print("Guessed Letters: ", [letter for letter in guessedLetters])
alphabet = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'y', 'x', 'z']
gl = input("Guess a letter: ")
if gl not in alphabet:
print("Please enter only one letter!")
continue
if gl in guessedLetters:
print("You have already guessed this letter, please guess again!")
continue
guessedLetters.append(gl)
if gl not in guessWord:
bodyParts +=1
bodyLeft(bodyParts, guessWord)
word = str(displayWord(guessWord, correctLetters))
print(word)
else:
correctLetters.append(gl)
word = str(displayWord(guessWord, correctLetters))
bodyLeft(bodyParts, guessWord)
if len(correctLetters) == len(guessWord):
guessed = True
print(word)
word = removeChar(word, " ")
word = removeChar(word, "_")
if len(word) == len(guessWord):
print("You Won!")
if (input("Do you want to play again?") == 'y'):
hangman('c')
else:
menu()
elif (bodyParts == 6):
print("YOU ARE DOOMED TO ETERNAL DAMNATION!")
if (input("Do you want to play again?") == 'y'):
hangman('c')
else:
menu()
|
5582f759c5c94370d79afbbd4069959f8935cd48 | sd2001/Technocolab-S.D | /Weather Data/get_temperature.py | 477 | 3.625 | 4 | import pyowm
owm=pyowm.OWM('0833f103dc7c2924da06db624f74565c')
mgr=owm.weather_manager()
place=(input("Enter the city name : "))
obs=mgr.weather_at_place(place)
weather=obs.weather
temp_f=weather.temperature(unit='fahrenheit')['temp']
temp_c=weather.temperature(unit='celsius')['temp']
print(f'The Temperature of {place} is {temp_f} Fahrenheit and {temp_c} Celsius')
#input-Enter the city name : Kolkata
#output-The Temperature of Kolkata is 91.4 Fahrenheit and 33.0 Celsius |
e4c1c70c3b7c54048203a1be3c97ac048eeb8bd4 | agatachamula/genetic-algorthm | /graphs.py | 422 | 3.78125 | 4 | import matplotlib.pyplot as plt
def main():
filename = input('Enter a file name: ')
X = [0,1,2,3,4,5]
Y=[0.78,0.92,0.91,0.88,0.88,0.89]
#plt.ylabel('Generation with best result')
plt.ylabel('Accuracy of result')
plt.plot(X,Y)
plt.xlabel('Degree of polynomial')
plt.show()
x = [[9, 5, 9], [7, 8, 9]]
print(x)
if __name__ == '__main__':
main() |
a6f4a09f0e979e77ccd4fe3145940c5e07994db1 | Nikita-Voloshko/Lesson7 | /Clovers.py | 1,800 | 4.21875 | 4 | from abc import abstractmethod
class Clovers():
size = 0
@abstractmethod
def __init__(self, size):
pass
@abstractmethod
def my_clover(self):
pass
class Clover1(Clovers):
def __init__(self, size):
if (size == "XS"):
Clovers.size = 20
elif (size == "S"):
Clovers.size = 25
elif (size == "M"):
Clovers.size = 30
elif (size == "L"):
Clovers.size = 35
elif (size == "XL"):
Clovers.size = 40
else:
print("Ошибка! Неправельный размер.")
Clovers.__init__(self, size="M")
@property
def my_clover(self):
if (Clovers.size > 0):
return f'{(Clovers.size / 6.5 + 0.5)} квадратных метров ткани на костюм {a.size}-го размера.'
else:
return 0
class Clover2(Clovers):
def __init__(self, size):
if (size == 20):
Clovers.size = 20
elif (size == 25):
Clovers.size = 25
elif (size == 30):
Clovers.size = 30
elif (size == 35):
Clovers.size = 35
elif (size == 40):
Clovers.size = 40
else:
print("Ошибка! Неправельный размер.")
@property
def my_clover(self):
if (Clovers.size > 0):
return f'{(2 * Clovers.size + 0.3)} квадратных метров ткани на пальто {a.size}-го размера.'
else:
return 0
a = Clover2(20)
a.__init__(20)
print(a.my_clover, f'квадратных метров ткани на пальто {a.size}-го размера.')
|
0e3c36592419c24fc25e61c6c535b294801d470d | tino2002/VuNgocMinh-C4T8 | /session6/bt5.py | 299 | 4.15625 | 4 | while True:
name = input("Password ?")
if name.isalpha():
print("password must have number")
else:
if name.count('') < 8:
print(name)
break
else:
print("password must have at least 8 characters")
|
ee71da812913bad2dcc6b41c386fd7955a834575 | CivilizedWork/Whisper-Jhin | /day2/Exercise4.2.py | 647 | 3.6875 | 4 | import math
import turtle
def arc(t,r,angle):
bob = turtle.Turtle()
t= turtle.Turtle()
n=50
for i in range(n):
t.fd(2*math.pi*r/n)
t.lt(angle/n)
turtle.mainloop()
def petal (t,r,angle):
for i in range(2):
arc(t, r, angle)
t.lt(180 - angle)
def flower(t,n,r,angle):
for i in range(n):
petal(t, r, angle)
t.lt(360.0 / n)
def move(t,length):
t.pu()
t.fd(length)
t.pd()
bob = turtle.Turtle()
move(bob, -100)
flower(bob, 7, 60.0, 60.0)
move(bob, 100)
flower(bob, 10, 40.0, 80.0)
move(bob, 100)
flower(bob, 20, 140.0, 20.0)
bob.hideturtle()
turtle.mainloop() |
e942cdc30e56f127aa2d90d69ab7e5e03fd4ff99 | flavian-anselmo/BlogSite | /blogy/myblogs/models.py | 3,244 | 4.09375 | 4 | from django.db import models
class Category(models.Model):
categoryName=models.CharField(max_length=100)
def __str__(self):
#helps in displaying the categories
return self.categoryName
#category name of a specific blog
class Post(models.Model):
#this model represents the posts
title=models.CharField(max_length=100)
blog=models.TextField()
createdOn=models.DateTimeField(auto_now_add=True)
lastModified=models.DateTimeField(auto_now=True)
categories=models.ManyToManyField('Category',related_name='post')
class Comment(models.Model):
#this represents users comments
author=models.CharField(max_length=100)
comment=models.TextField()
createdOn=models.DateTimeField(auto_now_add=True)
post=models.ForeignKey('Post',on_delete=models.CASCADE)
"""
category model has only the name of the category
we need a single charfield that we store the name of the category
options in lastmodified and created on fields
auto_now_add=True
this assigns current date and time to this field whenever an instance of this class
is created
auto_now=true
assigns the current date and time to this field whenever an instance of this field
whenever you edit an instance of this class ,,the date odified is updated
manyto many field takes two arguments the first is the model which the
relationship is in this case its category The second allows us to access the relationship
form a category object even though we havent added a field there by adding a related
in the comment model we have foreigh key that creates a many to one
since one post equals many comments but no the other way round
we cant have many posts with one comment
on_delete=models.CASCADE is used to delete the the comment instance if
the posts is deleted form the database
HOW TO UNDERSTAND MANY TO ONE RELATIONSHIP
{
USE django.db.models.ForeignKey
it requires a positional argument :the class or
table to which the table is related
for example you have two tables and hence one depends on another to display data
eg a table car_tbl and manufacturer
you can have many cars but each have only one manufacturer
hence a many to one relationship
hence the cartable depends on the manufacturer table to display a manufacturer
hence the car table will have a field to input a manufacturer
eg{
manufacturer=models.ForeignKey('manufacturer_tbl', on_delete=models.CASCADE)
}
}
HOW TO UNDERSTAND MANY TO MANY RELATIONSHIP
{
TO define many to many relaionship
use manyTomany field
for example you have a tbl teacher and tble stream in
a school set db
the teachers tbl requires to be assigned a stream hence
the teacher table will have a field stream
one teacher can teach many streams and one stream can be taught by one teacher
pizza can have many toppings and a topping can be in many pizzaz
eg{
stream=models.ManyToManyField('streamTable')
generally manyTomany instances should go in the object that is goin to be edited
eg {
streams will be editted in the teachers form
}
}
}
""" |
7f995f0157916d45828c2e8bd06fec8a58bc5d97 | abchilders/algorithms | /programming assignments/pa2/class notes 02 - dijkstras shortest path/lecture code/cpp/lecture/lecture/graph.py | 1,398 | 3.75 | 4 | #style: use underscore casing for function names
#booleans are capitalized
#PQ functions in Python
from heapq import *
class Graph:
#constructor in Python
def __init__(self):
self._graph = {} #HT in Python, should work with any kvp
def add_vertex(self, node):
self._graph[node] = {} #multidimensional hashtables
def connect_vertex(self, source, sink, weight, is_bidirectional = False):
self._graph[source][sink] = weight
if is_bidirectional == True:
self.connect_vertex(sink, source, weight, False)
def compute_shortest_path(self, start):
#tracks known distances
distances = {}
#make sure start is in graph
if start in self._graph:
# define PQ
to_visit = []
#push on starting location
#by default, python will sort PQ by first value in Tuple
#PQs are min-queues by default in Python, so we put weight first to act as sorting criteria
heappush(to_visit, (0, start)) #push onto to_visit, we will push on a tuple(pair)
#while PQ is not empty
while len(to_visit) > 0:
#pop returns item in Python
top = heappop(to_visit)
#2nd item is our key
key = top[1]
if not key in distances:
#record distance
distances[key] = top[0]
#push on children
for edge, weight in self._graph[key].items():
if not edge in distances:
heappush(to_visit, (weight + top[0], edge))
return distances |
f85362dcdc4391ff14e9232c7020a97fe1cd3ede | Adriana-ku06/programming2 | /pythom/np/np_operation.py | 347 | 3.6875 | 4 | import numpy as np
#operaciones con los valores de los arreglos
arr_1 = np.arange(1,6)
arr_2 = np.array([-3,7,3,13,0])
# Suma
suma=np.add(arr_1, arr_2)
print(suma)
# Resta
resta=np.subtract(arr_2, arr_1)
print(resta)
# Raiz cuadrada
raiz=np.sqrt(arr_1)
print(raiz)
# Potencia
potencia=np.power(arr_1, 2)
print(potencia)
# Signo
|
6679023217712a8de292d74331f5214c911679de | ftorresi/PythonLearning | /Unit3/ej3.27.py | 763 | 3.875 | 4 | from math import pi, cos
def maxmin(f, a, b, n=1000):
h=float(b-a)/(n-1) #evaluate f on steps of length h
x=a
fmax=f(x)
fmin=f(x)
while x<=b: #evaluate f in many points, to find max and min
x+=h
fval=f(x)
fmax=(fval if fval > fmax else fmax) #to keep only the highest value
fmin=(fval if fval < fmin else fmin) #to keep only the lowest value
return fmax, fmin
def test_maxmin():
"""Test maxmin function for cosine"""
maxexp=1.0
minexp=-1.0
maxv,minv=maxmin(cos,-0.5*pi, 2*pi, 1e6)
succmax=abs(maxexp-maxv)<1e-10
succmin=abs(minexp-minv)<1e-10
msgmax= "Test fails for max. in cosine"
msgmin= "Test fails for min. in cosine"
assert succmax, msgmax
assert succmin, msgmin
test_maxmin()
|
f8499f770a015482380e40dd35621a9b08d2b8a4 | Superbeet/LeetCode | /Recover_Binary_Search_Tree.py | 1,571 | 4.03125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class stack(object):
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
return True
def peek(self):
return self.stack[-1]
def pop(self):
return self.stack.pop(-1)
def size(self):
return len(self.stack)
def empty(self):
return len(self.stack)==0
"""
O(n) space
"""
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if root is None:
return None
def inorder_check(node, elem):
"""
elem = [s1, s2, pre]
"""
if node is None:
return
inorder_check(node.left, elem)
if node is not None and elem[2] is not None and node.val<elem[2].val:
if elem[0] is None:
elem[0] = elem[2] # s1=pre
elem[1] = node # s2=node
else:
elem[1] = node
elem[2] = node
inorder_check(node.right, elem)
element = [None, None, None]
inorder_check(root, element)
element[0].val,element[1].val = element[1].val,element[0].val
root = TreeNode(0)
root.left = TreeNode(1)
sol = Solution()
sol.recoverTree(root) |
c88b6fda0dd589155424d252c986454c166f2223 | newmayor/pythonlearning | /6.00.1_edX/ex_bisectionsearch_recursive.py | 630 | 3.96875 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
l = len(aStr)
if l%2 !=0 :
mid = int(l/2)
elif len(aStr) == 0:
return False
else:
mid = int(l/2)
if char == aStr[mid]:
return True
elif char < aStr[mid]:
aStr = aStr[:mid]
return isIn(char, aStr)
elif char > aStr[mid]:
aStr = aStr[mid:]
return isIn(char, aStr)
elif len(aStr) == 1 and char != aStr:
return False
else:
return False |
4006f0fe0c03d3061050d7149b44561ae81b8e2d | mtochs/Udacity | /Data Analytics Nanodegree/P5 Enron Finance and Email Analysis with Machine Learning/tools/scatplot.py | 520 | 3.71875 | 4 | #!/usr/bin/python
"""
Simple function that displays a scatter plot with two feature inputs
from data_dict
"""
import numpy as np
import matplotlib.pyplot as plt
from feature_format import featureFormat, targetFeatureSplit
def scatplot(data, x, y):
d = featureFormat(data, [x, y, 'poi'])
for point in d:
xp = point[0]
yp = point[1]
poi = point[2]
color = 'red' if poi else 'blue'
plt.scatter(xp, yp, color=color)
plt.xlabel(x)
plt.ylabel(y)
plt.show()
|
7a3e2da0ad8315ea436644b5ce71b5a07b34a2d8 | Abdurrahmans/Uri-problem-solving | /URI_1132.py | 178 | 3.65625 | 4 | a = int(input())
b = int(input())
temp = 0
sum = 0
if a > b:
temp = b
b = a
a = temp
for x in range(a,b):
if x % 13 != 0:
sum += x
print(sum)
|
dbbf3f5dc12b97f37b0019bd796064a1381f6360 | manastole03/Programming-practice-2 | /python1/DAY3_PROGRAMS/pascal_triangle.py | 272 | 3.84375 | 4 | rows = int(input("Enter the number of rows : "))
for i in range(0, rows):
res = 1
for j in range(1, rows-i):
print(" ", end="")
for k in range(0, i+1):
print(" ", res, end="")
res = int(res * (i - k) / (k + 1))
print()
|
03ebb6ad0341eb75e0e142556bc6c26b49de5ffb | ankurgokhale05/LeetCode | /Amazon/Binary Search/33-Search_in_Rotated_Sorted_Array.py | 1,773 | 3.78125 | 4 | #Time Complexity : O(logn)
class Solution:
def search(self, nums: List[int], target: int) -> int:
if nums == None or len(nums) == 0:
return -1
left = 0
right = len(nums) - 1
#The goal of this search is to find the smallest element of array.
while left < right:
mid = left + (right - left)//2
# Is middle element greater than element to right. Because in a sorted array all element to left are less than element at right. If nums[mid] > target then it is peculiar. We can narrow down search space to left = midpoint +1 and search in right part of array. we do that because we know for sure middle element is not smallest as nums[mid] > nums[right]
# Else it is normal and we search for left part of array.
# Loop will break when left is at smallest element index
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
start = left
left = 0
right = len(nums) - 1
# Now since we know the starting index or smallest element.
if target >= nums[start] and target <= nums[right]: # Perfect boundaries it since this is sorted version.
# In this case [4,5,6,7,0,1,2] if target is 1 we got nums[start] = 0 nums[left] = 4 and nums[right] = 2. We know that we have to search on right side of nums[start] else on left side of nums[start]
left = start
else:
right = start
while left <= right:
mid = left + (right - left)//2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
|
ca466e4f3c421eb18bb73070a8ca05d2ec94e314 | lrvick/usb-ser-mon | /find_port.py | 4,436 | 3.8125 | 4 | #!/usr/bin/python -u
"""Program which detects USB serial ports.
This program will search for a USB serial port using a search criteria.
In its simplest form, you can use the -l (--list) option to list all of
the detected serial ports.
You can also add the following filters:
--vid 2341 Will only match devices with a Vendor ID of 2341.
--pid 0001 Will only match devices with a Product ID of 0001
--vendor Micro Will only match devices whose vendor name starts with Micro
--seral 00123 Will only match devices whose serial number stats with 00123
If you use -l or --list then detailed information about all of the matches
will be printed. If you don't use -l (or --list) then only the name of
the device will be printed (i.e. /dev/ttyACM0). This is useful in scripts
where you want to pass the name of the serial port into a utiity to open.
"""
from __future__ import print_function
import select
import pyudev
import serial
import sys
import tty
import termios
import traceback
import syslog
import argparse
import time
EXIT_CHAR = chr(ord('X') - ord('@')) # Control-X
def is_usb_serial(device, args):
"""Checks device to see if its a USB Serial device.
The caller already filters on the subsystem being 'tty'.
If serial_num or vendor is provided, then it will further check to
see if the serial number and vendor of the device also matches.
"""
if 'ID_VENDOR' not in device:
return False
if not args.vid is None:
if device['ID_VENDOR_ID'] != args.vid:
return False
if not args.pid is None:
if device['ID_MODEL_ID'] != args.pid:
return False
if not args.vendor is None:
if not 'ID_VENDOR' in device:
return False
if not device['ID_VENDOR'].startswith(args.vendor):
return False
if not args.serial is None:
if not 'ID_SERIAL_SHORT' in device:
return False
if not device['ID_SERIAL_SHORT'].startswith(args.serial):
return False
return True
def extra_info(device):
extra_items = []
if 'ID_VENDOR' in device:
extra_items.append("vendor '%s'" % device['ID_VENDOR'])
if 'ID_SERIAL_SHORT' in device:
extra_items.append("serial '%s'" % device['ID_SERIAL_SHORT'])
if extra_items:
return ' with ' + ' '.join(extra_items)
return ''
def main():
"""The main program."""
default_baud = 115200
parser = argparse.ArgumentParser(
prog="find-port.py",
usage="%(prog)s [options] [command]",
description="Find the /dev/tty port for a USB Serial devices",
)
parser.add_argument(
"-l", "--list",
dest="list",
action="store_true",
help="List USB Serial devices currently connected"
)
parser.add_argument(
"-s", "--serial",
dest="serial",
help="Only show devices with the indicated serial number",
default=None,
)
parser.add_argument(
"-n", "--vendor",
dest="vendor",
help="Only show devices with the indicated vendor name",
default=None
)
parser.add_argument(
"--pid",
dest="pid",
action="store",
help="Only show device with indicated PID",
default=None
)
parser.add_argument(
"-v", "--verbose",
dest="verbose",
action="store_true",
help="Turn on verbose messages",
default=False
)
parser.add_argument(
"--vid",
dest="vid",
action="store",
help="Only show device with indicated VID",
default=None
)
args = parser.parse_args(sys.argv[1:])
if args.verbose:
print('pyudev version = %s' % pyudev.__version__)
context = pyudev.Context()
if args.list:
detected = False
for device in context.list_devices(subsystem='tty'):
if is_usb_serial(device, args):
print('USB Serial Device %s:%s%s found @%s\r' % (
device['ID_VENDOR_ID'], device['ID_MODEL_ID'],
extra_info(device), device.device_node))
detected = True
if not detected:
print('No USB Serial devices detected.\r')
return
for device in context.list_devices(subsystem='tty'):
if is_usb_serial(device, args):
print(device.device_node)
return
sys.exit(1)
main()
|
b729bba0d224c58ccf8902f353c895b981d15384 | 633-1-ALGO/introduction-python-raemarcelo | /8.1- Exercice - Séquence 1/sequence1.py | 361 | 3.671875 | 4 | # Problème : Etant donné une variable a et b, on demande de mettre la valeur de a dans b et celle de b dans a
# Contraintes : Ne pas utiliser de valeurs numériques.
# Données : les variables a et b
a = 11
b = 42
print('Valeur de a : ', a)
print('Valeur de b :', b)
c = a
d = b
a = d
b = c
print ('Valeur de a-new : ', a)
print ('Valeur de b-new : ', b)
|
c0428b25a0c637fed013bfc5e1ead60199a55466 | itoyuhao/stanCode_Projects | /SC-Projects/Breakout_game/breakout.py | 4,643 | 3.625 | 4 | """
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao.
Creator Name: Kevin Chen
"""
from breakoutgraphics import BreakoutGraphics
from campy.gui.events.timer import pause
FRAME_RATE = 1000 / 120 # 120 frames per second
NUM_LIVES = 3 # Number of attempts
def main():
graphics = BreakoutGraphics()
lives = NUM_LIVES
# Add animation loop here!
if lives > 0 and graphics.mouse_switch:
while True:
# When there's no brick, end the game and show the final score
if graphics.there_is_no_brick():
graphics.window.remove(graphics.ball)
graphics.window.remove(graphics.score_board)
pause(1000)
graphics.congrats()
graphics.show_score(graphics.get_score())
break
# When the ball's out of the window
if graphics.ball.y >= graphics.window.height:
lives -= 1
# If there's lives remained, reset the ball and turn the mouse switch on
if lives > 0:
graphics.reset_ball()
graphics.mouse_switch = True
# If there's no lives left, end the game and show the final score
else:
graphics.remove_all()
graphics.window.remove(graphics.score_board)
pause(1000)
graphics.game_over()
graphics.show_score(graphics.get_score())
break
# Update animation
ball_vx = graphics.get_vx()
ball_vy = graphics.get_vy()
graphics.ball.move(ball_vx, ball_vy)
# Check
if graphics.ball.x <= 0 or graphics.ball.x + graphics.ball.width >= graphics.window.width:
graphics.set_vx(-ball_vx)
if graphics.ball.y <= 0:
graphics.set_vy(-ball_vy)
# When the ball hit something (except for the wall)
if graphics.is_ball_collision() is not None:
an_object = graphics.is_ball_collision()
# If the ball hits the paddle
if an_object is graphics.paddle:
# To avoid from stuck in the paddle (set the ball on the paddle)
if graphics.ball.y + graphics.ball.height >= an_object.y:
graphics.ball.y = graphics.paddle.y - graphics.ball.height
# Bouncing up
graphics.set_vy(-ball_vy)
# vx changes with the position ball hit the paddle
if graphics.ball.x + graphics.ball.width/2 < graphics.paddle.x + graphics.paddle.width/4:
graphics.set_vx(ball_vx-2)
if graphics.paddle.x + graphics.paddle.width/4 <= graphics.ball.x + graphics.ball.width/2 \
< graphics.paddle.x + graphics.paddle.width/2:
graphics.set_vx(ball_vx-1)
if graphics.paddle.x + graphics.paddle.width/2 <= graphics.ball.x + graphics.ball.width/2 \
< graphics.paddle.x + graphics.paddle.width*3/4:
graphics.set_vx(ball_vx+1)
if graphics.paddle.x + graphics.paddle.width*3/4 <= graphics.ball.x + graphics.ball.width/2:
graphics.set_vx(ball_vx+2)
else:
# When the ball hits the bricks
if an_object is not graphics.score_board:
# Changing color of the ball
graphics.ball.color = an_object.fill_color
graphics.ball.fill_color = an_object.fill_color
# Bounce
graphics.set_vy(-ball_vy)
# Remove the bricks
graphics.window.remove(an_object)
# Get 100 scores (updating the score board)
graphics.set_score(100)
graphics.score_board_update(graphics.get_score())
# When the ball hits the 'score board' (try it, haha)
else:
# Bounce
graphics.set_vy(-ball_vy*1.5)
# Double scores and speed up (updating the score board)
graphics.set_score(graphics.get_score())
graphics.score_board_update(graphics.get_score())
# Pause
pause(FRAME_RATE)
if __name__ == '__main__':
main()
|
13b1cd9866a44a44175264e49936e53934864d23 | taketakeyyy/atcoder | /abc/066/b.py | 405 | 3.65625 | 4 | # -*- coding:utf-8 -*-
def solve():
S = input()
for i in range(1, len(S)):
s = S[:-i]
if len(s)%2 != 0: continue # 長さが偶数じゃなければ偶文字列になりえない
pivot = len(s)//2
upper = s[0:pivot]
lower = s[pivot:]
if upper == lower:
print(len(s))
return
if __name__ == "__main__":
solve()
|
0f9e3354980a45c51a104c9ae8d341fc22f79768 | Marshall00/CheckiO-tasks-solutions | /ELEMENTARY/SecondIndex.py | 413 | 4 | 4 | def second_index(text: str, symbol: str) -> [int, None]:
"""
returns the second index of a symbol in a given text
"""
counter=0
index=0
if symbol not in text:
return None
else:
counter+=1
index=text.index(symbol)
for i in range(index+1,len(text)):
if text[i]==symbol:
return i
else:
continue
|
5339bf9b63bd9bc4623701339ff32f5c4a1a9d46 | kirigaikabuto/Python13Lessons | /lesson21/objects/student_list.py | 904 | 3.796875 | 4 | class StudentList:
def __init__(self, students):
self.students = students
def print_info(self):
for i in self.students:
i.print_info()
def filter_by_age(self, age):
for i in self.students:
if i.age >= age:
i.print_info()
def filter_by_grade_name(self, name):
pass
def get_students_name_by_grade_name(self, name):
students = []
for i in self.students:
if i.grade.name == name:
students.append(i.username)
return students
def filter_by_grade(self):
grades_names = ["11a", "11b", "11c"]
d = {}
for i in grades_names:
# code
d[i] = self.get_students_name_by_grade_name(i)
print(d)
def filter_by_ages(self):
ages = [15, 16, 17, 17, 19, 20]
d = {}
# code
print(d)
|
990c538fec1b81f2970cedbab5ee9fa9c2a97fcf | langrenchuan/ConsoleSnake | /snake.py | 4,045 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,random,sys,time,copy,threading
from getChar import _Getch
RED='\33[1;31m' ; GREEN='\33[1;32m' ; YELLOW='\33[1;33m' ; BLUE='\33[1;34m' ; MAGENTA='\33[1;35m' ; CYAN='\33[1;36m'; NOR='\33[m'; BOLD='\33[1m'
Head=[CYAN,"D"];Body=[MAGENTA,"0"];Food=[BLUE,"I"];Road=[YELLOW,"-"];
RIGHT=0;LEFT=1;UP=2;DOWN=3;
Height=10;Width=30;Board=[];Snake=[];Direct=RIGHT
IsAlive = True;
if os.name=="nt":
CLEAR="cls"
else:
CLEAR="clear"
def getchar():
inkey = _Getch()
for i in xrange(sys.maxint):
k=inkey()
if k<>'':break
return k;
def init():
"""init Board """
global Snake
Board.append(Body);Board.append(Body);Board.append(Head)
Snake = [[0,2],[0,1],[0,0]]
for i in range(Height*Width-3):
Board.append(Road)
randomFood()
def printBoard():
strborad = ""
for i in range(Height):
str = ""
for j in range(Width):
temp = Board[i*Width+j]
str += temp[0] + temp[1]
strborad += str + "\n"
print strborad,NOR
def printHelp():
print "use key a s w d to move left down up right,q to exit "
def randomFood():
temp=[]
global Board
global IsAlive
for i in range(Width*Height):
if Board[i] == Road :
temp.append(i)
if len(temp)==0:
clear()
printBoard()
print "you win ! press q to exit!"
IsAlive = False
else:
Board[temp[random.randint(0,len(temp)-1)]]=Food
def updateSnake():
global Board
global IsAlive
for i in range(Height*Width):
if Board[i] != Food:
Board[i]=Road
for i in range(1,len(Snake)):
Board[Snake[i][0]*Width + Snake[i][1]]=Body
Board[Snake[0][0]*Width + Snake[0][1]]=Head
if Snake[0] in Snake[1:]:
clear()
printBoard()
print "you lose bite yourself! press q to exit!"
IsAlive = False
def moveon():
global Snake
global IsAlive
while True:
SnakeHead = copy.deepcopy(Snake[0])
SnakeTail = copy.deepcopy(Snake[-1])
if Direct==LEFT:
if SnakeHead[1] == 0:
SnakeHead[1]=Width-1
else:
SnakeHead[1]=SnakeHead[1]-1
elif Direct==RIGHT:
if SnakeHead[1] == Width-1:
SnakeHead[1]=0
else:
SnakeHead[1]=SnakeHead[1]+1
elif Direct==UP:
if SnakeHead[0] == 0:
SnakeHead[0]=Height-1
else:
SnakeHead[0]=SnakeHead[0]-1
elif Direct==DOWN:
if SnakeHead[0] == Height-1:
SnakeHead[0]=0
else:
SnakeHead[0]=SnakeHead[0]+1
Snake = [SnakeHead]+Snake[:-1]
if Board[SnakeHead[0]*Width+SnakeHead[1]]==Food:
Snake.append(SnakeTail)
updateSnake()
randomFood()
else:
updateSnake()
if not IsAlive:
break
clear()
printHelp()
printBoard()
time.sleep(0.3)
def clear():
"""clear game board"""
sys.stdout.write('\033[1;1H\033[2J')
#os.system(CLEAR)
def moveUp():
global Direct
if Direct==LEFT or Direct==RIGHT:
Direct = UP
def moveDown():
global Direct
if Direct==LEFT or Direct==RIGHT:
Direct = DOWN
def moveLeft():
global Direct
if Direct==UP or Direct==DOWN:
Direct = LEFT
def moveRight():
global Direct
if Direct==UP or Direct==DOWN:
Direct = RIGHT
def control():
while True:
c=getchar()
if c=="w" or c=="W":
moveUp()
elif c=="s" or c=="S":
moveDown()
elif c=="a" or c=="A":
moveLeft()
elif c=="d" or c=="D":
moveRight()
elif c=="q" or c=="Q":
exit()
def gameStart():
init()
t1 = threading.Thread(target=moveon)
t1.setDaemon(True)
t1.start()
control()
if __name__ == '__main__': # a little test
gameStart()
|
4bc360ed049a2d3f74a72464c80c38fb1273eccf | aofwittawat/django50hr | /readdb.py | 505 | 3.546875 | 4 | # readdb.py
import sqlite3
import csv
conn = sqlite3.connect('db.sqlite3')
c = conn.cursor()
with conn:
c.execute("""SELECT * FROM myapp_orderpending WHERE user_id=3""")
data = c.fetchall()
# data = c.fetchone()
# data = c.fetchmany(2)
# print(data)
for d in data:
print(d)
print('---------------')
############### EXPORT TO CSV ################################################
with open('allorder_user3.csv','w',newline='',encoding='utf-8') as f:
fw = csv.writer(f)
fw.writerows(data) |
56fd1c5966d0be227b00a71cd8b2a942e5060ed6 | YuanGao0702/Hadoop-American-Airplane | /Airline-reduce2.py | 712 | 3.546875 | 4 | #!/usr/bin/env python
#How many minutes total did passengers spend waiting for all late departures in 2014?
#Student: Changle Xu, Yuan Gao, Bei Xia
from operator import itemgetter
import sys
total = 0
delay = 0
# input comes from STDIN
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
#Input: the key is FL_NUM; the value is the delay whose value is larger than 0 minutes.
# parse the input we got from mapper.py
count = line.split('\t')
delay = int(count[1])
total += delay
#There is no key of output of reducer.The value is the total minutes passengers spent waiting for all late departures in 2014.
print "Total Waiting time: "+'%s\t' % (total)
|
e7dbedf5fe60f897ce3db80cbd39c46d6bf3038a | Jethrodeen/ImageWord2Vec | /Simple.py | 5,273 | 4 | 4 | """
https://becominghuman.ai/building-an-image-classifier-using-deep-learning-in-python-totally-from-a-beginners-perspective-be8dbaf22dd8
"""
# to initialise our nn as a sequence of layers (could alternatively initialise as a graph)
from keras.models import Sequential
#for the convolution operation. Conv3D will be for videos
from keras.layers import Conv2D
# for the pooling operation
from keras.layers import MaxPooling2D
#for converting all resultant 2D arrays into single long continous linear vector
from keras.layers import Flatten
#perform the full connection of the neural network
from keras.layers import Dense
#build model
model = Sequential()
#add conv layer
"""
Four arguments:
1. the number of filters. i.e. 32
2. shape of each filter i.e. 3x3
3. input shape and type of image(RGB/Grayscale) ie. 64x64 and 3
4. the activation function
"""
model.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
#Pooling layer.
model.add(MaxPooling2D(pool_size = (2, 2)))
#Flatten the pooled image pixels to one dimension
model.add(Flatten())
#create the fully connected (hidden) layer
"""
arguments:
1. units = where we define the number of nodes that should be present in this hidden layer.
2. activation function
"""
model.add(Dense(units = 128, activation= 'relu'))
#create output layer. units dependant on your class. Binary i.e. 1 in our case
model.add(Dense(units = 1, activation= 'sigmoid'))
#compile model
"""
arguments:
1. optimizer to choose the stochastic gradient descent function
2. Loss to choose the loss function
3. metrics to choose performance metric
"""
model.compile(optimizer='adam', loss= 'binary_crossentropy', metrics =['accuracy'])
#checkpoint to store weights
"""
taken from
https://towardsdatascience.com/visualizing-intermediate-activation-in-convolutional-neural-networks-with-keras-260b36d60d0
"""
from keras.callbacks import ModelCheckpoint
checkpointer = ModelCheckpoint(filepath="best_weights.hdf5",
monitor = 'val_acc',
verbose=1,
save_best_only=True)
#===============================================================================================
#image processing =https://keras.io/preprocessing/image/
#for custom dataset in folder "data"
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('data/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary')
test_set = test_datagen.flow_from_directory('data/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary')
training_set.image_shape
# =============================================================================================
#train model
"""
arguments:
1.steps per epoch: number of training images
2.validation_steps = number of validation images
"""
history = model.fit_generator(training_set, steps_per_epoch=1589,epochs = 50, validation_data= test_set, validation_steps= 378
, callbacks = [checkpointer]) #this line only if we want to save best weights
#model save and accuracy plots
"""
from G Pierobon
https://towardsdatascience.com/visualizing-intermediate-activation-in-convolutional-neural-networks-with-keras-260b36d60d0
"""
#load best weights
model.load_weights('best_weights.hdf5')
#save model
model.save('cnn.h5')
#plot
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
#=======================================================================================================================
#Test on an image
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dog2.jfif', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
#check labels
training_set.class_indices
if result[0][0] == 1:
prediction = 'dog'
else:
prediction = 'cat'
print(prediction)
#=======================================================================================================================
#check layers
from keras import models
# Extracts the outputs of all layers
layer_outputs = [layer.output for layer in model.layers]
# Creates a model that will return these outputs, given the model input
activation_model = models.Model(inputs=model.input, outputs=layer_outputs)
# Returns a list of Numpy arrays: one array per layer activation
activations = activation_model.predict(test_image)
first_layer_activation = activations[2]
print(first_layer_activation.shape) |
0f924a8e5fbc915824990897bbb222afc4939f8e | kushagra189/bomberman | /bricks.py | 573 | 3.53125 | 4 | from __future__ import print_function
import random
class Bricks:
def makeBricks(self, array, Matrix):
counter = 0
temp = 0
while(counter < 36):
x = random.randint(2, 36)
y = random.randint(4, 76)
if array[x][y] == 0 and Matrix[x][y] == ' ':
if (x % 4 == 0 and y % 8 == 4) or (x % 4 == 2 and y % 4 == 0):
for i in range(x, x + 2):
for j in range(y, y + 4):
Matrix[i][j] = '/'
counter = counter + 1
|
6937b4b1fdb4d6c69ecd4bd707407c00adb0785d | baothais/Practice_Python | /handle_file.py | 6,733 | 4.15625 | 4 | # """
# "r" - Read - Default value. Opens a file for reading, error if the file does not exist
#
# "a" - Append - Opens a file for appending, creates the file if it does not exist
#
# "w" - Write - Opens a file for writing, creates the file if it does not exist
#
# "x" - Create - Creates the specified file, returns an error if the file exists
# """
#
# # # open file demo1.txt and read file
# # f = open("demo1.txt", "r")
# #
# # # reading the content of the file
# # print(f.read())
# #
# # # print 5 first characters
# # print(f.read(5))
# #
# # # To read a text file one line at a time
# # print(f.readline())
# #
# # # To read a list of lines in a text file
# # print(f.readlines())
# #
# # # close file
# # f.close()
#
# # file = open("demo2.txt", "w+")
# #
# # file.write("Hello Thai Bao\n")
# # file.write("What is your age?\n")
# # file.write("I love you!\n")
# # file.write("Hello")
# #
# # file.close()
# #
# # file = open("demo2.txt", "r")
# #
# # # print(file.read())
# #
# # # print(file.readline())
# #
# # # print(file.readlines())
# #
# # # for i in file:
# # # print(i)
# #
# # s = ""
# # for i in file.readlines():
# # s += i
# # print(s.split("\n"))
# #
# # file.close()
#
# # lines = ["Hello Thai Bao\n", "You very handsome\n", "I love you"]
# # f = open("demo3.txt", "w")
# # for line in lines:
# # f.write(line)
# #
# # f.close()
#
# # with open("demo3.txt", "r") as f1:
# # with open("demo2.txt", "r") as f2:
# # for i in f1.readlines():
# # if i in f2.readlines():
# # print(i)
#
#
#
# # # print(f.read())
# #
# # # print(f.readline())
# #
# # # print(f.readlines())
# # s = ""
# # for i in f.readlines():
# # s += i
# #
# # print(s.split("\n"))
# #
# # l = s.split("\n")
# # # for i in range(len(l)):
# # # print(l[i])
# #
# # print(l[1])
# # line = f.readline()
# # count = 0
# # while line:
# # print(line)
# # line = f.readline()
# # print(count)
# # print(len(f.readlines()))
#
# # for i in f.readlines():
# # print(i)
# #
# # for i in f1.readlines():
# # print(i)
# # import random
# #
# # list_number1 = random.sample(range(1, 10), 5)
# # list_number2 = random.sample(range(1, 1000), 7)
# # with open("one.txt", "r") as f:
# # print(f.readlines())
# # with open("two.txt", "r") as f:
# # for number in list_number2:
# # f.write(str(number))
# # f.close()
#
# # f = open("demo2.txt", "r")
# # string = f.read()
# # print(string)
# # print(string.split("\n"))
# # f = open("demo4.txt", "w")
# # f.write("Hello")
# # f.write("What is your name?")
# # f.close()
# #
# f = open("demo4.txt", "r")
# l = f.read()
# print(type(l))
# # f.close()
# import random
#
# # with open("sowpods.txt") as f:
# # l = f.read().split()
# # print(l)
# # # # l = list(f)
# # # # print(l)
# # # # print(f.readlines())
# # f.close()
# #
# # print(random.choice(l).strip())
#
# # s = "asdasd\n\n\n\n\n\n\nasdasdasd\nasdasd\nasda"
# # print(s.split())
# import random
#
# def choose_random_word():
# words=[]
# with open('sowpods.txt', 'r') as file:
# line = file.readline()
# while line:
# words.append(line.replace("\n","".strip()))
# line = file.readline()
# choice=words[random.randint(0,len(words)-1)]
# return choice
#
#
#
#
#
# print("Welcome to Hangman!")
# secret_word=choose_random_word()
# dashes=list(secret_word)
# display_list=[]
# for i in dashes:
# display_list.append("_")
# count=len(secret_word)
# guesses=0
# letter = 0
# used_list=[]
# while count != 0 and letter != "exit":
# print(" ".join(display_list))
# letter=input("Guess your letter: ")
#
# if letter.upper() in used_list:
# print("Oops! Already guessed that letter.")
# else:
# for i in range(0,len(secret_word)):
# if letter.upper() == secret_word[i]:
# display_list[i]=letter.upper()
# count -= 1
# guesses +=1
# used_list.append(letter.upper())
#
# if letter == "exit":
# print("Thanks!")
# else:
# print(" ".join(display_list))
# print("Good job! You figured that the word is "+secret_word+" after guessing %s letters!" % guesses)
#
#
# import json
#
# # a Python object (dict):
# x = {
# "name": "John",
# "age": 30,
# "city": "New York"
# }
#
# # convert into JSON:
# y = json.dumps(x)
#
# # the result is a JSON string:
# print(y)
# print(x)
# print(json.dumps({"name": "John", "age": 30}))
# print(json.dumps(["apple", "bananas"]))
# print(json.dumps(("apple", "bananas")))
# print(json.dumps("hello"))
# print(json.dumps(42))
# print(json.dumps(31.76))
# print(json.dumps(True))
# print(json.dumps(False))
# print(json.dumps(None))
import json
# with open("states.json", "r") as f:
# data = json.load(f)
#
# for state in data["states"]:
# for x in state:
# print(state[x])
# my_info = {
# "Albert Einstein": "03/14/1879",
# "Benjamin Franklin": "01/17/1706",
# "Ada Lovelace": "12/10/1815",
# 'Donald Trump': '06/14/1946',
# 'Rowan Atkinson': '01/6/1955'
# }
#
# with open("info.json", "w") as f:
# json.dump(my_info, f, indent=2, sort_keys=True)
#
# with open("info.json", "r") as f:
# data = json.load(f)
#
# for key in data.keys():
# print(key, data[key])
import json
# from urllib.request import urlopen
#
# with urlopen("https://jsonplaceholder.typicode.com/posts") as f:
# source = f.read()
# # print(source)
#
# data = json.loads(source)
# print(type(data))
# print(json.dumps(data, indent=2))
# with open("posts.json", "w") as f:
# json.dump(data, f, indent=2)
#
# my_string = "hello a Bao dep zai"
# with open("demo5.json", "w") as f:
# json.dump(my_string, f)
#
with open("file_json/demo5.json", "r") as f:
# print(type(f))
data = json.load(f)
print(type(data))
print(json.dumps(data))
#
# with open("demo5.txt", "w") as f:
# f.write(my_string)
#
# with open("demo5.txt", "r") as f:
# print(f)
# data = f.read()
# print(type(data))
# my_string = """[{
# "name": "Thai Bao",
# "age": 25,
# "sex": "Male"
# },
# {"name": "Thai Tits",
# "age": 1,
# "sex": "Male"
# }]"""
#
# data = json.loads(my_string)
# print(json.dumps(data, indent=2))
#
# with open("demo6.json", "w") as f:
# json.dump(data, f, indent=2)
#
with open("file_json/demo6.json", "r") as f:
new_data = json.load(f)
print(type(new_data))
print(json.dumps(new_data, indent=2))
# my_str = "hello a Bao dep zai"
#
# with open("demo7.json", "w") as f:
# json.dump(my_str, f)
#
# with open("demo7.json", "r") as f:
# new_str = json.load(f)
#
# print(new_str)
with open("file_txt/demo2.txt", "r") as f:
data = f.read()
print(type(data))
with open("file_json/demo2.json", "w") as f:
json.dump(data, f, indent=2)
# print(json.dumps(data, indent=2))
|
8e9f2edeac226993b1486d9e78aeb17be26891d6 | InfiniteShadowz/ESPM | /semestre1/matDiscreta/mantissaDec2Bin.py | 2,812 | 3.84375 | 4 | #Python3
decimal = float(input("digite o decimal float para transformar para binario (lembre-se de usar . e não ,): "))
#max 1024 e min 2^-18
res = 1024.0
binario = []
headers = []
binarioFinal = []
start = False
count = 0
numSignedExp = 0
#Faz a verificação do input do usuario, entre + ou -
if decimal < 0:
signedDecimal = 1
#evita trabalhar com num negativo no cod principal
decimal *= -1
else:
signedDecimal = 0
#firstADD - adiciona o sinal do numero no binario Final
binarioFinal.append(signedDecimal)
###############################################
#percorre do expoente 10 até o -18
for exp in range(10, -19, -1):
#se o inputado - resultado do expoente > 0:
if decimal - res >= 0:
decimal -= res
start = True
#a variavel start determina se o numero ja se iniciou (inicia no primeiro '1' dropado)
if start:
headers.append(exp)
binario.append(1)
#conta quantos digitos há depois do start ativado, a variavel foi criada pensando em como pegar o primeiro expoente ativado
count +=1
if start and count == 1:
numSignedExp = exp
else:
if start:
headers.append(exp)
binario.append(0)
count +=1
#corta o resultadoExpoente por 2, para ir para o expoente anterior
res /= 2
###############################################
#determina, por padrao somente, que o sinal do expoente é +
signedExp = 0
#Se o primeiro expoente for menor que 0:
if numSignedExp < 0:
#o sinal do expoente se torna ativo (1)
signedExp = 1
#torna-se positivo para trabalhar com numero positivo
numSignedExp *= -1
#coloca o sinal do expoente no binario Final
binarioFinal.append(signedExp)
#Coloca o trecho de 4 binarios dentro do binario Final:
for i in range(3, -1, -1):
aux = numSignedExp
numSignedExp = numSignedExp - 2**i
if numSignedExp < 0:
binarioFinal.append(0)
numSignedExp = aux
else:
binarioFinal.append(1)
#Resultados do 1berto:
# 1.6666666666 = 0000.0010.1010.1010
# -0.0735 = 1101.0000.1011.0100
# -240.25 = 1001.1111.1000.0010
# 45.1875 = 0001.0101.1010.0110
#Alguns numeros dão diferente no programa, acredito que por distinções de precisão de cada calculadora/programa utilizado
#Escreve na tela desde o primeiro elemento até o ultimo contado da lista de binario
for i in range(0, count):
numBin = binario[i]
expoente = headers[i]
print("Expoente --> {} || {}".format(expoente, numBin))
#esconde o primeiro digito 1 (natural da mantissa, pois trata-se de uma redundância)
del binario[0]
#Como o programa é em 16Bits, é necessário somente 10 digitos de mantissa, logo:
for i in range(0, 10):
binarioFinal.append(binario[i])
print("\nResultado Final:\n")
print(binarioFinal)
#descomente a linha abaixo para usar o programa no cmd:
#input()
|
a4205f3c3bd082e6046035f249edc793b8731b79 | bubble501/turtle-kids-teaching | /level_2_grammer/lesson_3/3-1.py | 167 | 3.640625 | 4 | #Python 数据类型的转换
a = 6.66 #浮点数a
print(a)
b = int(a) #将浮点数a转化为整型
print(b)
c = float(b) #将整数b转化为浮点数
print(c) |
a7edf597c954625767dd1ed46f8e2ae7f9cf2319 | pstorozenko/YP2018-PythonPodstawy | /Zajecia3/Grupa1/wstep_zaj3.py | 926 | 3.6875 | 4 | # zad 1
print(2 * 7 * 722287)
# zad 2
a = int(input("Podaj 1. bok trójkąta: "))
b = int(input("Podaj 2. bok trójkąta: "))
c = int(input("Podaj 3. bok trójkąta: "))
if a+b>c and a+c>b and b+c>a:
print("Nierówność trójkąta spełniona")
else:
print("Nierówność trójkąta nie spełniona")
# zad 3
zespol = input("Podaj swój ulubiony zespół")
print("WIWAT", zespol.upper())
# zad 4
imie = input("Jak masz na imię?")
if imie.endswith("a") and imie.lower() != "kuba":
print("Dzień dobry Pani")
else:
print("Dzień dobry Panu")
# zad 5
odp = input("Ile wynosi 2+2*2?: ")
if int(odp) == 6:
print("Poprawna odpowiedź :)")
else:
print("Zła odpowiedź :(")
# zad 6
skala = input("Jaką skale chcesz zamienić C czy F?")
temp = int(input("Podaj jaką chcesz temperaturę zamienić"))
if skala == "C":
print(2/9 * temp + 32, "stopni F")
else:
print(5/9 * (temp - 32), "stopni C")
|
e017672e3e0d7ee028e8de1622a76479d3361e3c | MannyP31/CompetitiveProgrammingQuestionBank | /Searching Algorithms/binary_search.py | 1,184 | 4.375 | 4 | # BINARY SEARCH
# It is a searching algorithm which is more efficient than linear search. It can find an element if present in O(log(n)) time complexity.
# For this algorithm to work, the array should be in sorted order
# it returns the position of the element in the array
def binary_search (arr, item):
"""The binary_Search function takes input the sorted list of elements and the item to be searched
and returns the position of the item, if found in the list, else it returns -1 """
beg, end = 0, len(arr)-1
mid = (beg+end)//2
while beg<=end:
mid = (beg+end)//2
if arr[mid] == item :
return mid
elif arr[mid] > item:
end = mid-1
elif arr[mid] < item:
beg = mid+1
return -1 # return -1 if the element is not present in the array
## DRIVER CODE
test_arr = [1,2,3,4,5] # this should be a sorted array
test_item = 2 # this is the item to be searched
ans = binary_search(test_arr, test_item)
if ans != -1 :
print(f"Element found at index position {ans}")
else:
print("Element is not present in array") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.