blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
49713799dca629c6241c231cee6c665ba878eb31 | miclindb/BioSim_G09_Michael_Daniel | /src/biosim/island.py | 8,925 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Island Module
"""
__author__ = "Michael Lindberg, Daniel Milliam Müller"
__email__ = "michael.lindberg@nmbu.no, daniel.milliam.muller@nmbu.no"
from .cell import Ocean, Mountain, Jungle, Savannah, Desert
from .animals import Herbivore, Carnivore
class Island:
"""
Island class. Superclass for all landscape types.
"""
def __init__(self, island_map):
"""
Class constructor for island.
Parameters
----------
island_map: str
String containing information about the island such as shape and
landscape type.
"""
self.island_map = island_map
self.landscape_dict = {'M': Mountain,
'O': Ocean,
'J': Jungle,
'S': Savannah,
'D': Desert}
def construct_vertical_coordinates(self, h_axis):
"""
Constructs the vertical coordinates for the island map.
"""
for x in range(len(self.island_map[h_axis])):
if self.island_map[h_axis][x] not in self.landscape_dict.keys():
raise ValueError('Landscape type does not exist')
else:
self.island_map[h_axis][x] = self.landscape_dict[
self.island_map[h_axis][x]
]()
self.island_map[h_axis][x].coordinate = (h_axis, x)
def construct_map_coordinates(self):
"""
Construct the coordinates of the island map.
"""
for y in range(len(self.island_map)):
iteration = iter(self.island_map)
length = len(next(iteration))
if not all(len(list) == length for list in iteration):
raise ValueError('Inconsistent line length')
if self.island_map[y][0] != 'O' and self.island_map[y][1] == 'O':
print(self.island_map[y][0], self.island_map[y][1])
raise ValueError('Bad boundary')
self.construct_vertical_coordinates(h_axis=y)
def map_constructor(self):
"""
Constructs the entire map of the island.
"""
self.island_map = self.island_map.split('\n')
for n in range(len(self.island_map)):
self.island_map[n] = \
[character for character in self.island_map[n]]
self.construct_map_coordinates()
def generate_cell_above(self, x, y, list_of_nearby_cells):
"""
Generates cell above current cell.
"""
cell_1 = self.island_map[y - 1][x]
list_of_nearby_cells.append(cell_1)
def generate_cell_left(self, x, y, list_of_nearby_cells):
"""
Generates cell to the left of current cell.
"""
cell_2 = self.island_map[y][x - 1]
list_of_nearby_cells.append(cell_2)
def generate_cell_below(self, x, y, list_of_nearby_cells):
"""
Generates cell below current cell.
"""
cell_3 = self.island_map[y + 1][x]
list_of_nearby_cells.append(cell_3)
def generate_cell_right(self, x, y, list_of_nearby_cells):
"""
Generates cell to the right of current cell.
"""
cell_4 = self.island_map[y][x + 1]
list_of_nearby_cells.append(cell_4)
def generate_nearby_cells(self):
"""
Generates a list of cells near current cell. These cells are used for
animal migration.
"""
for y in range(len(self.island_map)):
for x in range(len(self.island_map[y])):
list_of_nearby_cells = []
if y != 0:
self.generate_cell_above(x, y, list_of_nearby_cells)
if x != 0:
self.generate_cell_left(x, y, list_of_nearby_cells)
if y != len(self.island_map)-1:
self.generate_cell_below(x, y, list_of_nearby_cells)
if x != len(self.island_map[y])-1:
self.generate_cell_right(x, y, list_of_nearby_cells)
self.island_map[y][x].nearby_cells = list_of_nearby_cells
def add_herbivores(self, animal, animal_list):
"""
Adds herbivores to the island population. Used for 'adding_population'
method.
Parameters
----------
animal: Herbivore
Herbivore object to be added to the population.
animal_list: list
List of animals to be added to the population.
"""
self.island_map[animal_list['loc'][0]][
animal_list['loc'][1]].population.append(
Herbivore(age=animal['age'], weight=animal['weight']))
def add_carnivores(self, animal, animal_list):
"""
Adds carnivores to the island population. Used for 'adding_population'
method.
Parameters
----------
animal: Carnivore
Carnivore object to be added to the population.
animal_list: list
List of animals to be added to the population.
"""
self.island_map[animal_list['loc'][0]][
animal_list['loc'][1]].population.append(
Carnivore(age=animal['age'], weight=animal['weight']))
def adding_population(self, population):
"""
Adds population to the island.
Parameters
----------
population: List
List containing dictionaries describing the population's location
and population type.
Required format:
ini_animals = [{
"loc": (coordinate_x, coordinate_y),
"pop": [
{"species": str(animal_species), "age": age, "weight": weight}
for _ in range(number_of_animals)
],
}]
"""
try:
for animals in population:
for animal in animals['pop']:
if animal['species'] == 'Herbivore':
self.add_herbivores(animal, animals)
if animal['species'] == 'Carnivore':
self.add_carnivores(animal, animals)
except (ValueError, KeyError):
raise ValueError(
'Invalid input for population, see documentation.'
)
def total_population(self):
"""
Constructs a list containing all the animals on the island.
Returns
-------
total_population_list: list
List containing the total population on the island.
"""
total_population_list = []
for y in self.island_map:
for cell in y:
total_population_list += cell.population
return total_population_list
def island_fodder_growth(self):
"""
Yearly cycle for fodder growth. Fodder grows for all cells on the
island.
"""
for y in self.island_map:
for cell in y:
cell.fodder_growth()
def island_feeding(self):
"""
Yearly cycle for feeding. All animals on the island attempts to feed.
"""
for y in self.island_map:
for cell in y:
cell.feeding()
def island_procreate(self):
"""
Yearly cycle for procreation. All animals on the island attempts to
procreate.
"""
for y in self.island_map:
for cell in y:
cell.procreate()
def island_migration(self):
"""
Yearly cycle for migration. All animals on the island cell attempts to
migrate. Resets the 'has_moved' status of the animals afterwards.
"""
for y in self.island_map:
for cell in y:
cell.migration()
for y in self.island_map:
for cell in y:
for animal in cell.population:
animal.has_moved = False
def island_aging(self):
"""
Yearly cycle for aging. All animals on the island turn one year older.
"""
for y in self.island_map:
for cell in y:
cell.aging()
def island_loss_of_weight(self):
"""
Yearly cycle for loss of weight. All animals on the island loses
weight.
"""
for y in self.island_map:
for cell in y:
cell.loss_of_weight()
def island_deaths(self):
"""
Yearly cycle for death. Checks for all animals on the island if the
die.
"""
for y in self.island_map:
for cell in y:
cell.deaths()
def island_cycle(self):
"""
Performs operations related to the annual cycle for one cell.
"""
self.island_fodder_growth()
self.island_feeding()
self.island_procreate()
self.island_migration()
self.island_aging()
self.island_loss_of_weight()
self.island_deaths()
|
0651263e6c6455bfacbe5fd2f7f54ac39cad0d60 | Aries5522/daily | /2021届秋招/leetcode/面试真题/美团/美团.py | 2,425 | 3.59375 | 4 | import sys
class UnionFindSet(object):
"""并查集"""
def __init__(self, data_list):
"""初始化两个字典,一个保存节点的父节点,另外一个保存父节点的大小
初始化的时候,将节点的父节点设为自身,size设为1"""
self.father_dict = {}
self.size_dict = {}
for node in data_list:
self.father_dict[node] = node
self.size_dict[node] = 1
def find(self, node):
"""使用递归的方式来查找父节点
在查找父节点的时候,顺便把当前节点移动到父节点上面
这个操作算是一个优化
"""
father = self.father_dict[node]
if (node != father):
if father != self.father_dict[father]: # 在降低树高优化时,确保父节点大小字典正确
self.size_dict[father] -= 1
father = self.find(father)
self.father_dict[node] = father
return father
def is_same_set(self, node_a, node_b):
"""查看两个节点是不是在一个集合里面"""
return self.find(node_a) == self.find(node_b)
def union(self, node_a, node_b):
"""将两个集合合并在一起"""
if node_a is None or node_b is None:
return
a_head = self.find(node_a)
b_head = self.find(node_b)
if (a_head != b_head):
a_set_size = self.size_dict[a_head]
b_set_size = self.size_dict[b_head]
if (a_set_size >= b_set_size):
self.father_dict[b_head] = a_head
self.size_dict[a_head] = a_set_size + b_set_size
else:
self.father_dict[a_head] = b_head
self.size_dict[b_head] = a_set_size + b_set_size
n, m = map(int, sys.stdin.readline().split())
nums = []
maxNum = 0
for _ in range(m):
tempTwoNum = list(map(int, input().split()))
maxNum = max(maxNum, max(tempTwoNum))
nums.append(tempTwoNum)
union_find_set = UnionFindSet(list(range(maxNum + 1)))
for i in range(m):
union_find_set.union(nums[i][0], nums[i][1])
res_dict = {}
for i in union_find_set.father_dict:
rootNode = union_find_set.find(i)
if rootNode in res_dict:
res_dict[rootNode].append(i)
else:
res_dict[rootNode] = [i]
print(res_dict)
print('朋友圈个数:', len(res_dict.keys()))
"""
5 5
1 1
2 2
3 3
4 2
5 5
"""
|
5d47636a8a87897ea60e875853b2edfc91614d96 | whigg/maidenhead | /maidenhead/__init__.py | 2,291 | 3.84375 | 4 | from typing import Tuple
"""## mlocs - Maidenhead
toMaiden([lat, lon], level) returns a char (len = lvl*2)
toLoc(mloc) takes any string and returns topleft [lat,lon] within mloc
Beyond 8 characters is not defined for Maidenhead.
"""
def toLoc(maiden: str) -> Tuple[float, float]:
"""
input: maidenhead locator of length 2 to 8
output: [lat,lon]
"""
if not isinstance(maiden, str):
raise TypeError('Maidenhead locator must be a string')
maiden = maiden.strip().upper()
N = len(maiden)
if not 8 >= N >= 2 and N % 2 == 0:
raise ValueError('Maidenhead locator requires 2-8 characters, even number of characters')
Oa = ord('A')
lon = -180.
lat = -90.
# %% first pair
lon += (ord(maiden[0])-Oa)*20
lat += (ord(maiden[1])-Oa)*10
# %% second pair
if N >= 4:
lon += int(maiden[2])*2
lat += int(maiden[3])*1
# %%
if N >= 6:
lon += (ord(maiden[4])-Oa) * 5./60
lat += (ord(maiden[5])-Oa) * 2.5/60
# %%
if N >= 8:
lon += int(maiden[6]) * 5./600
lat += int(maiden[7]) * 2.5/600
return lat, lon
def toMaiden(lat: float, lon: float,
precision: int = 3) -> str:
"""Returns a maidenhead string for specified lat-lon tuple at specified level.
"""
A = ord('A')
a = divmod(lon+180, 20)
b = divmod(lat+90, 10)
astring = chr(A+int(a[0])) + chr(A+int(b[0]))
lon = a[1] / 2.
lat = b[1]
i = 1
while i < precision:
i += 1
a = divmod(lon, 1)
b = divmod(lat, 1)
if not (i % 2):
astring += str(int(a[0])) + str(int(b[0]))
lon = 24 * a[1]
lat = 24 * b[1]
else:
astring += chr(A+int(a[0])) + chr(A+int(b[0]))
lon = 10 * a[1]
lat = 10 * b[1]
if len(astring) >= 6:
astring = astring[:4] + astring[4:6].lower() + astring[6:]
return astring
def genGoogleMap(mloc: str) -> str:
gpos = toLoc(mloc)
return "http://maps.googleapis.com/maps/api/staticmap?center={},{}&zoom=10&size=320x240&sensor=false".format(gpos[0], gpos[1])
def genNonSense(lat: float, lon: float, level: int = 3) -> str:
mloc = toMaiden(lat, lon, level)
return "http://no.nonsense.ee/qthmap/?qth={}".format(mloc)
|
35d638266300040f9b11441c829f1601e6dec65c | pradeep-gnr/realtime_word_cloud | /utils/nlp.py | 421 | 3.875 | 4 | from nltk import word_tokenize
from nltk.corpus import stopwords
def tokenize(text):
tokens = word_tokenize(text)
words = [w.lower() for w in tokens if w.isalnum()]
return words
def filter_stop_words(tokens):
filtered_words = [word for word in tokens if word not in stopwords.words('english')]
return filtered_words
if __name__=="__main__":
print filter_stop_words(tokenize("A sample sentence to be tokenzied.")) |
549e8eb8b865c152bf9cd0ea0fe3b47f09007305 | LaxmanMaharjan/Python | /venv/Codes/Decorators/with_logging.py | 826 | 3.625 | 4 | import time
import logging
import functools
def logged(method):
"""
Causes the decorated function to run and log the result and some diagnostic info
:param method:
:return:
"""
@functools.wraps(method)
def inner(*args,**kwargs):
#Record start time
start = time.time()
result = method(*args,**kwargs)
#time after completion of method run
end = time.time()
delta = end - start
logger = logging.getLogger("decorator.logged")
logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler()
logger.addHandler(stream_handler)
logger.info(f"Execution Time of {method.__name__} is {delta} seconds")
return result
return inner
@logged
def heavy_function():
time.sleep(2)
heavy_function()
|
fb55f62c6cecf3f2ecd74af7e4b57312235e361f | eldorbaxtiyorov/python-darslar | /20-functions/javoblar-20-06.py | 351 | 3.828125 | 4 | """
18/12/2020
Dasturlash asoslari
#20-dars: FUNKSIYADAN QIYMAT QAYTARISH
Muallif: Anvar Narzullaev
Web sahifa: https://python.sariq.dev
"""
def fibonacci(n):
sonlar = []
for x in range(n):
if x == 0 or x == 1:
sonlar.append(1)
else:
sonlar.append(sonlar[x - 1] + sonlar[x - 2])
return sonlar
print(fibonacci(10))
|
bd239decefaf26c68ddf1b51363914ab2ffadaf5 | Jaymark-Nam/python_basic | /practice4_string.py | 1,091 | 4 | 4 | # string
sentence = 'I wish I were a boy'
print(sentence)
sentence2 = "python is easy"
print(sentence2)
#slicing
jumin= "950120-1654321"
print("sex :" +jumin[7])
print("year :" +jumin[0:2])
print("month :" +jumin[2:4])
print("day :" +jumin[4:6])
#string
python = "Python is Fancy"
print(python.lower()) #all lower
print(python.upper())
print(python[0].isupper())
print(len(python))
print(python.replace("Python","Life"))
index = python.index("n")
print(index)
index = python.index("n", index+1) #finding next "n"
print(index)
print(python.find("n"))
#sting format
print("a"+"b") #ab
print("a","b") #a b
print("I'm %d age years old" % 30)
print("I'm interested to %s" %"climbing")
print("Apple starts from %c" %"A") #one letter
print("I like %s and %s" %("blue","red"))
print("I am {}age years old" .format(20))
print("I like {} and {}" .format("cafe","tabasco"))
print("I like {1} and {0}" .format("cafe","tabasco"))
print("I am {age}years old, like {color}" .format(age=20,color="red"))
age = 80
color = "dark blue"
print(f"I am {age}years old, like {color}") |
de2a2711415b04324770eeb730be2c30904cc3ef | mumarkhan999/python_practice_files | /Dictionaries/2_looping_techniques.py | 1,870 | 4.25 | 4 | # looping technique of dictionary
knights = { ' gallahad ' : ' the pure ' , ' robin ' : ' the brave ' }
print("=====================")
print(1)
print("=====================")
for k in knights.keys():
print(k, knights[k])
# When looping through dictionaries,
# the key and corresponding value
# can be retrieved at the same time using
# the items() method.
print("=====================")
print(2)
print("=====================")
for k,v in knights.items():
print(k, v)
# When looping through a sequence,
# the position index and corresponding value
# can be retrieved at the same
# time using the enumerate() function.
print("=====================")
print(3)
print("=====================")
for i, v in enumerate(["Hello", "Belloe", "Cello"]):
print(i, v)
# To loop over two or more sequences
# at the same time,
# the entries can be paired with the zip() function.
roll_nos = [1, 2, 3, 4]
names = ['sara', 'ali', 'asif', 'wasif']
print("=====================")
print(4)
print("=====================")
for roll, name in zip(roll_nos, names):
print(roll, name)
# To loop over a sequence in reverse,
# first specify the sequence
# in a forward direction and then call the reversed()
# function.
print("=====================")
print(5)
print("=====================")
for i in reversed(range(1,11)):
print(i)
# To loop over a sequence in sorted order,
# use the sorted() function which
# returns a new sorted list while
# leaving the source unaltered.
print("=====================")
print(6)
print("=====================")
basket = [ ' apple ' , ' orange ' , ' apple ' , ' pear ' , ' orange ' , ' banana ' ]
for i in sorted(basket):
print(i)
print("=====================")
print("6b")
print("=====================")
basket = [ ' apple ' , ' orange ' , ' apple ' , ' pear ' , ' orange ' , ' banana ' ]
for i in sorted(set(basket)):
print(i)
|
ab7b0d09e046f4cc26a0349f3001a2f874dfa119 | PouringRain/Algorithmn | /26.py | 626 | 3.59375 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
# 前序+中序-->二叉树
if not tin:
return None
rootVal = pre.pop(0)
root = TreeNode(rootVal)
rootIndex = tin.index(rootVal)
root.left = self.reConstructBinaryTree(pre, tin[:rootIndex])
root.right = self.reConstructBinaryTree(pre,tin[rootIndex+1:])
return root
|
cf6d364266ff340469f803c78844917adb968ec2 | osamascience96/CS50 | /python/lists.py | 189 | 4.0625 | 4 | # define the set of names
names = ["Harry", "Ron", "Hermoine", "Ginny"]
# add the new element to the list
names.append("Draco")
# sort out the list of elements
names.sort()
print(names)
|
0e9422e854a0f8424746d9715314698fc838394d | gamesbrainiac/Project_Euler | /__2.py | 393 | 3.703125 | 4 | __author__ = 'Nafiul Islam'
__title = 'Even Fibonacci numbers'
def fibonacci(start=1):
a, b = start, start
yield start
while True:
_ret = a + b
a, b = b, _ret
yield _ret
if __name__ == '__main__':
total = 0
for i in fibonacci():
if i < 4*10**6 and not i % 2:
total += i
elif i > 4*10**6:
break
print(total) |
47ad326873e8c8cd332de25cce058f8e25e84295 | shetty019/Python | /evenood.py | 146 | 4.21875 | 4 | num=(int(raw_input('enter the input: ')))
if(num%2)==0:
print ('The entered number is even')
else:
print ('the entered number is odd') |
5c7893dcb5cf41fcc90552498f248fddf1cb6d1f | gavinaguiar/challenges | /singleNumber.py | 623 | 3.953125 | 4 | '''
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
'''
def singleNumber(nums):
xor=nums[0]
for n in range(1,len(nums)):
xor = xor^nums[n]
bit = xor ^ ~(xor-1)
num1=0
num2=0
for num in nums:
if(num & bit) > 0:
num1 = num1^num
else:
num2 = num2^num
return num1 , num2
nums = [1, 2, 1, 3, 2, 5]
print(singleNumber(nums)) |
fe9a514d9fa39a22e54ef6d3043357deb5c9def9 | mukuld/python | /again/04_volume.py | 274 | 4.25 | 4 | # Python program # 4
# Programmer: Mukul Dharwadkar
# Date: 3 Nov 2012
# Program to calculate the volume of a cube.
length = 8
width = 5
depth = 4
volume = length * width * depth
print "The volume of the cube having length", length, "width", width, "and depth", depth, "is", volume |
df511ebe0226262ba967674ddc6a679d1ca057a2 | nataliecosta0/curso-python-dn | /semana_1/exercicios_aula_1/Ex06.py | 641 | 4.21875 | 4 | '''
Exercício #6
Faça um programa que pergunte o preço de três produtos e informe qual produto
você deve comprar, sabendo que a decisão é sempre pelo mais barato.
'''
preco1 = float(input("Informe o preço do primeiro produto: "))
preco2 = float(input("Informe o preço do segundo produto: "))
preco3 = float(input("Informe o preço do terceiro produto: "))
if preco1 < preco2 and preco1 < preco3:
produto = preco1
elif preco2 < preco1 and preco2 < preco3:
produto = preco2
elif preco3 < preco1 and preco3 < preco2:
produto = preco3
print("O produto que deve comprar é com valor: {} ".format(produto)) |
ab1253e96f3c262b61b865aa2b549c928009598a | saurabh0471/DataStructure_and_Algorithms_Python_and_cpp | /HackwithInfy/Playing_with_Prime.py | 885 | 3.78125 | 4 | # Function for check prime.
def is_prime(a):
c = 0
if a > 1:
for i in range(2, a // 2):
if a % i == 0:
c += 1
if c == 0:
return True
return False
# Driver Code.
for _ in range(int(input())):
n = int(input())
if n < 1 : print(-1)
c = 0
output = []
for i in range(n + 1):
for j in range(n + 1):
x = list(map(int, str(i)))
y = list(map(int, str(j)))
z = sum(x) + sum(y)
if z > 1:
if z != 2 and z % 2 == 0:
pass
else:
if is_prime(z):
if (j, i) not in output:
c += 1
output.append((i, j))
output.append((j, i))
print((i, j))
print(c) |
d89d269714b0ed96276c48688aa02f454a3da59b | coquelin77/PyProject | /leetcode/I though I have idea/29. 两数相除.py | 1,520 | 4.3125 | 4 | '''给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
返回被除数 dividend 除以除数 divisor 得到的商。
示例 1:
输入: dividend = 10, divisor = 3
输出: 3
示例 2:
输入: dividend = 7, divisor = -3
输出: -2'''
class Solution:
def divide(self, dividend, divisor):
result = 0
if dividend == 0 or divisor == 0:
return 0
if dividend > 0 and divisor > 0: # 全正
while dividend >= divisor:
dividend = dividend - divisor
result = result + 1
return result
elif dividend < 0 and divisor < 0: # 全负
dividend = abs(dividend)
divisor = abs(divisor)
while dividend >= divisor:
dividend = dividend - divisor
result = result + 1
return result
elif dividend > 0 and divisor < 0: # 正负
divisor = abs(divisor)
while dividend >= divisor:
dividend = dividend - divisor
result = result + 1
return 0 - result
elif dividend < 0 and divisor > 0: # 负正
dividend = abs(dividend)
while dividend >= divisor:
dividend = dividend - divisor
result = result + 1
return 0 - result
if __name__ == '__main__':
dd=-2147483648
dr =-1
a = Solution()
p = a.divide(dd, dr)
print(p)
|
7d97479fa1af156f0b9ab4d3cde84b6ebab417c6 | pbandi2020/Election_Analysis | /PyPoll_Datetime.py | 3,542 | 3.96875 | 4 | # A quick test before starting the code
# my_string = "Hello!"
# print(my_string)
#*********************************************************
#Election Analysis Psuedo Code
#********************************************************
# Instantiate the CSV API
import csv
import os
import datetime as dt
# Get the current / system time into a variable.
systemtime = dt.datetime.now()
print(f"Date&Time: {systemtime}")
# Declare the file path
# print(os.path.join("..", "Resources", "election_results.csv"))
input_file = os.path.join("Resources\election_results.csv")
#Declare an output file path
output_file = os.path.join("election_analysis.txt")
# Initialize the total vote count and create an empty list for candidatescandidate option and a empty dictionary for candidate votes
total_votes = 0
candidate_options = []
candidate_votes = {}
#Variables for Winning candidate, winning count and winning percentage
winning_candidate = ""
winning_count = 0
winning_percentage = 0
#Open the input file. Using the with statement closes the file automatically
with open(input_file, newline="") as election_data:
file_reader = csv.reader(election_data,delimiter = ",")
# Read the header row and save into variable before starting to process the election data
header = next(file_reader)
# print(header)
for i in file_reader:
#sum the total votes
total_votes += 1
#candidate name for each row
candidate_name = i[2]
#Start with the first candidate in the spreadsheet to count the votes by candidate. This step is with assumtion the file is already sorted by candidate.
if candidate_name not in candidate_options:
#start populating the candidate options list
candidate_options.append(candidate_name)
candidate_votes[candidate_name] = 0
candidate_votes[candidate_name] +=1
# print(f'{candidate_name} - {total_votes}')
print(f'{candidate_options}')
print(f'{candidate_votes}')
print(total_votes)
#Wite the result to a textfile/outfile
with open(output_file,"w") as txt_file:
election_results =(
f"\nElection Results\n"
f"-------------------\n"
f"Total Votes: {total_votes:,} \n"
f"-------------------\n" )
print(election_results)
#write the elections result o/p to the text file
txt_file.write(election_results)
# Now lets find the winner and the winning percentage
for i in candidate_votes:
votes = candidate_votes[i]
vote_percent = float(votes)/float(total_votes) * 100
candidate_results = f"{i}, got a total of ({votes:,}) which equates to {vote_percent:.1f}% \n"
print(candidate_results)
#Save the text file
txt_file.writelines(candidate_results)
# finalizing the winner
if (votes > winning_count) and (vote_percent > winning_percentage):
winning_candidate = i
winning_percentage = vote_percent
winning_count = votes
# print final summary
winning_candidate_summary = (
f"-----------------------------------------\n"
f"Winning Candidate : {winning_candidate} \n"
f"Winning Vote Count: {winning_count:,} \n"
f"Won By : {winning_percentage:.1f} %\n"
f"--------------------------------------------\n" )
print(winning_candidate_summary)
#complete the project by appending the winner result to he outputfile
txt_file.write(winning_candidate_summary)
|
c569e965e7694ec21c5dd9fbad7d9df8f5e67d60 | edwardcodes/Udemy-100DaysOfPython | /Day-15/CoffeeMachineProject_angela.py | 1,943 | 3.984375 | 4 | from data import MENU, resources
machine_on = True
profit = 0
def is_resources_sufficient(ingredients):
for item in ingredients:
if ingredients[item] > resources[item]:
print(f"Sorry there's no enough {item}")
return False
return True
def process_coins():
print("Please insert coins.")
total = int(input("how many quarters: ")) * 0.25
total += int(input("how many dimes: ")) * 0.1
total += int(input("how many nickels: ")) * 0.05
total += int(input("how many pennies: ")) * 0.01
return total
def is_transaction_successful(money_received, cost_drink):
if money_received >= cost_drink:
global profit
profit += cost_drink
print(f"Here is ${round(money_received - cost_drink,2)} in change")
return True
else:
return "Sorry that's not enough money. Money Refunded"
def make_coffee(drink_selected, resources_default):
for item in resources_default:
resources[item] -= resources_default[item]
print(f"Enjoy your {drink_selected}!!")
while machine_on:
choice = input("what would you like (espresso/latte/cappuccino): ")
if choice == "off".lower():
machine_on = False
elif choice == "report".lower():
print(f"Water: {resources['water']}ml")
print(f"Milk: {resources['milk']}ml")
print(f"Coffee: {resources['coffee']}g")
print(f"Money: ${profit}")
elif choice == "refill".lower():
resources["water"] += abs(300 - resources["water"])
resources["milk"] += abs(200 - resources["milk"])
resources["coffee"] += abs(100 - resources["coffee"])
print("Resources Refilled")
else:
drink = MENU[choice]
if is_resources_sufficient(drink["ingredients"]):
payment = process_coins()
if is_transaction_successful(payment, drink["cost"]):
make_coffee(choice, drink["ingredients"])
|
7b24631c319937f219f898de2f2c624c2d912e89 | Aditya-Pundir/VSCode_python_projects | /VS_Code_Folder_2/python_learning_from_cwh_course/string_slicing.py | 215 | 4.15625 | 4 | myStr = "Aditya is a programmer."
print(len(myStr))
# print(myStr[-11:-2]) # ——> Negative indices(This is same as [12:21])
# print(myStr[12:21])
# To reverse a string:
# print(myStr[::-1])
# print(myStr[::-2]) |
297b6aa43fff09c02d837f1a58ede03ef4a8903b | toeysp130/Lab-Py | /lab2-3.py | 260 | 4.03125 | 4 | #watcharakorn#
qty = int( input( "Enter number product : ") )
price = float( input( "Price per unit : ") )
total = price * qty
print( "Total money : ", total)
pay = float( input( "Enter pay money : ") )
change = pay - total
print( "Money change : ", change)
|
08ef2ed502a2b70362cd47d35d33bc4a94b1a66d | camilooob/pythonisfun | /allmethodtogether.py | 488 | 3.8125 | 4 | class Player:
teamName = 'Liverpool, soy class method' # class variables
def __init__(self, name, text):
self.name = name
self.text = text # creating instance variables
@classmethod
def getTeamName(cls):
return cls.teamName
@staticmethod
def demo():
print ("Soy static method.")
print(Player.getTeamName())
# Liverpool
p1 = Player("p","soy instance Method")
print(p1.text)
p1.demo()
# I am a static method
Player.demo()
# I am a static method
|
d17e7fae336c83b5580327ddbe4ea54b50db304a | Engrsolomighty/my-first-website | /rasheed/calculator.py | 543 | 3.703125 | 4 | def Add(x,y,z):
print(x+y+z)
Add(5,6,7)
class calculator:
color ='red' # properties
battery = 2
def Add(x,y,z): #method
print("addition ",x+y+z)
def Subtr(x,y,z): #method
print("subration ",x-y-z)
def Multiply(x,y,z): # method
print(" Multiply ",x*y*z)
def Divide(x,y,z): # method
print("division ", x/y/z)
print(calculator.color)
print(calculator.battery)
calculator.Add(5,6,7)
calculator.Subtr(5,6,7)
calculator.Multiply(5,6,7)
calculator.Divide(5,6,7)
|
2d1bbd4b78cda602eace995167c23036ada14c3a | 23thibja/code | /thibeault_unit1_practice.py | 2,250 | 3.9375 | 4 | #!/usr/bin/env python3
# PART A
print("welocme to information Technolgy\n\nProgramming and\nWeb Development")
print("")
print(" _ ___________\n| | / /_ __/ |\n| | /| / / / / / /| |\n| |/ |/ / / / / ___ |\n|__/|__/ /_/ /_/ |_|\n")
# PART B
print ("A lighting flash:\nbetween the forest trees\nI have seen water.\n\t- shuki\n")
print("**********\n* *\n* MR. G *\n* RM 119 *\n* *\n**********\n")
print("\"Computer Science is no more about computers\nthan astronomy is abouot telescoped\"\n- Edsger W. Dijkstra\n")
print(" )\n (\n ^ )\n / \ ___\n / \| |\n / _ \ |\n / (_) \|\n / \ \n/| _ _ \ \n | | | | | |\ \n | |_| |_| |\n | __ __ | \n | | | | | | #\n | | @| |__| | ###\n | | | | ##### \n\/\/\/\/\/\/\/\/\/\/\/\/\n ")
# PART C
user_name = input("What is your name? ")
favorite_animal = input("What is your favorite animal? ")
print("Hellow", user_name, ". Your favorite animal is the ", favorite_animal, ".")
number = input("What is your favorite number?")
print(number * 3)
num_1 = int(input("Enter a test score. "))
num_2 = int(input("Enter another test score. "))
num_3 = int(input("Enter one more test score. "))
sum_results = str((num_1 + num_2 + num_3)/3)
print(sum_results)
ani_1 = input("Enter a animal. ")
ani_2 = input("Enter another animal. ")
ani_3 = input("Enter one more. ")
print (ani_3, ani_2, ani_1)
int_1 = int(input("Enter an integer. "))
int_2 = int(input("Enter another integer. "))
print(" ", int_1 ," \n ______\n| |\n| |", int_2, "\n|______|\n")
print("Area = ",int_1 * int_2)
#Part D
F_N = input("Please Print First Name: ")
L_N = input("Please Print Last Name: ")
print( L_N, ",", F_N)
number_1 = int(input("Enter a number: "))
print(number_1 * 8)
number_2 = int(input("Enter a Number: "))
print(number_2 * 12)
#Part E
a = input("Enter an animal: ")
s = input("Enter a sound: ")
e = "E-I-E-I-O"
print ("Old Macdonald had a farm, " + e)
print ("And on his farm he had a " + a + ", " + e)
print ("With a " + s + "-" + s + " here and a " + s + "-" + s + " there")
print ("Here a "+ s+ " there a " +s)
print ("Everywhere a " + s + "-" +s)
print ("Old Macdonald had a farm," + e)
|
ecdb9e59a97ef1a613a2aa5e4af276aebe6ee8ad | vadim0311/python | /1-9.py | 54 | 3.546875 | 4 | a=0
while a!=10:
a=a+1
x=a**2
print(x) |
43b298ac7cdeee8ecc3a88d7d5e45322169e91d4 | PokerAI/Poker-Game | /poker-hand-evaluator/CT.py | 788 | 3.8125 | 4 | """card_translate.py"""
import arrays
"""card_translate(rank, suit):
Translate the card into the evaluator's inner representation and return it.
rank: (Number) (deuce=0,trey=1,four=2,five=3,...,ace=12)
suit: (String) 's','h','c','d'
"""
def card_translate(rank, suit):
suitInt = 0
if suit == 's':
suitInt = 1 << 12
elif suit == 'h':
suitInt = 2 << 12
elif suit == 'd':
suitInt = 4 << 12
else:
suitInt = 8 << 12
prime = ( arrays.primes[rank] |
rank << 8 |
suitInt |
(1 << (16+rank)))
return prime
if __name__ == '__main__':
print(card_translate(0,'s')) #2s
print(card_translate(9,'h')) #Jh
print(card_translate(3,'d')) #5d
print(card_translate(12,'c')) #Ac
|
e47166dcabccfcf8e959a516288c30b0190ecb5b | byrenx/algorithms-exercise | /count_inversion_using_mergesort.py | 1,359 | 4.0625 | 4 | def gelistintegers(file_name):
file_content = open(file_name)
lst = []
for num in file_content:
lst.append(int(num))
file_content.close()
return lst
def mergesort(lst):
'''Recursively divides list in halves to be sorted'''
if len(lst) == 1:
return lst, 0
middle = int(len(lst)/2)
left, s1 = mergesort(lst[:middle])
right, s2= mergesort(lst[middle:])
sortedlist, s3 = merge(left, right)
return sortedlist, (s3+s1+s2)
def merge(left, right):
'''Subroutine of mergesort to sort split lists. Also returns number
of split inversions (i.e., each occurence of a number from the sorted second
half of the list appearing before a number from the sorted first half)'''
i, j = 0, 0
splits = 0
result = []
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
splits += len(left[i:])
result += left[i:]
result += right[j:]
##print result, splits
return result, splits
if __name__ == '__main__':
lst_contents = gelistintegers('IntegerArray.txt')
##print str(lst_contents[3])
##lst_contents = [5,4,3,2,1]
mg_rs, split = mergesort(lst_contents)
print "# of inversions: " + str(split)
|
7cc0c4188ca37edbcd1a6102f082cdc8e0854535 | mjimenez421/QuantLabEx | /build/lib/src/outputBuilder.py | 4,893 | 4 | 4 | import csv
import os
# Throughout class, "row" is used to denote data from the output file
# e.g, "new_row" is data to be written to the output file
class OutputBuilder:
#class attributes to represent fields of the csv file
__iTime = 0
__iSymbol = 1
__iQuant = 2
__iPrice = 3
__oSymbol = 0
__oTime = 1
__oQuant = 2
__oAvg = 3
__oPrice = 4
def __init__(self):
cur_path = os.path.dirname(__file__)
output_path = os.path.relpath("../outputs/output.csv", cur_path)
self.time_diff = dict() #always of format {symbol: (timestamp, max)}
try:
self.output = open(output_path, "w+", newline="")
self.writer = csv.writer(self.output, delimiter=",")
self.reader = csv.reader(self.output)
except:
print("output file creation error")
def find_in_output(self, symbol):
self.output.seek(0)
value = None
method = None
old_row = None
i = 0
for row in self.reader:
if row[OutputBuilder.__oSymbol] == symbol:
value = i
method = "update"
old_row = row
break
elif symbol > row[OutputBuilder.__oSymbol]:
None
else:
value = i
method = "insert"
break
i += 1
return value, method, old_row
# Creates an average, rounded, using the round even rule
# Round even is commonly used in the sciences to reduce
# error between iterations of calculations
def rnd_avg(self, sum, count):
dec_avg = sum/count
int_avg = int(sum/count)
if dec_avg-int_avg > 0.5:
int_avg += 1
elif dec_avg-int_avg == 0.5:
if int_avg%2 == 1:
int_avg += 1
return int_avg
def max_interval(self, old_timeinfo, new_timestamp):
old_timestamp = int(old_timeinfo[0])
time_max = old_timeinfo[1]
time_diff = int(new_timestamp) - old_timestamp
if time_diff > time_max:
return time_diff
else:
return time_max
def build_row(self, line, max):
avg = self.rnd_avg(
int(line[OutputBuilder.__iPrice]),
int(line[OutputBuilder.__iQuant])
)
new_row = [
line[OutputBuilder.__iSymbol], max, line[OutputBuilder.__iQuant],
avg, line[OutputBuilder.__iPrice]
]
return new_row
def insert_line(self, line, location, method):
# In a scenario where the output file is too large for memory,
# write lines to an external file and rename file at end of process
self.output.seek(0)
i = 0
temp_list=[]
for row in self.reader:
if i == location and method == "insert":
symbol = line[OutputBuilder.__iSymbol]
self.time_diff[symbol] = (line[OutputBuilder.__iTime], 0)
new_row = self.build_row(line, 0)
temp_list.append(new_row)
temp_list.append(row)
elif i == location and method == "update":
temp_list.append(line)
else:
temp_list.append(row)
i+=1
self.output.seek(0)
self.writer.writerows(temp_list)
def update_line(self, line, location, old_row):
symbol = line[OutputBuilder.__iSymbol]
new_timestamp = line[OutputBuilder.__iTime]
old_timeinfo = self.time_diff[symbol]
time_max = self.max_interval(old_timeinfo, new_timestamp)
quantity = (int(line[OutputBuilder.__iQuant])
+ int(old_row[OutputBuilder.__oQuant]))
old_total = (int(old_row[OutputBuilder.__oQuant])
* int(old_row[OutputBuilder.__oAvg]))
new_total = int(line[OutputBuilder.__iPrice])
avg = self.rnd_avg(old_total+new_total, quantity)
price_max = old_row[OutputBuilder.__oPrice]
if line[OutputBuilder.__iPrice] > price_max:
price_max = line[OutputBuilder.__iPrice]
self.time_diff[symbol] = (new_timestamp, time_max)
new_row = [symbol, time_max, quantity, avg, price_max]
self.insert_line(new_row, location, "update")
def process_line(self, line):
symbol = line[OutputBuilder.__iSymbol]
line_num, method, old_row = self.find_in_output(symbol)
if method == "insert":
self.insert_line(line, line_num, method)
elif method == "update":
self.update_line(line, line_num, old_row)
else:
self.time_diff[symbol] = (line[OutputBuilder.__iTime], 0)
new_row = self.build_row(line, 0)
self.writer.writerow(new_row)
|
765b9712520f4f8b08ac13ca4bc11629dab9dc11 | adityakangune/HackerRank-Problem-Solving | /Funny String.py | 641 | 3.5625 | 4 | l = []
lr = []
dl = []
dlr = []
def FunnyString(s):
for i in s:
k1 = ord(i)
l.append(k1)
for j in r:
k2 = ord(j)
lr.append(k2)
# print(l)
# print(lr)
for i in range(1 , len(l)):
dl.append(abs(l[i] - l[i-1]))
# print(dl)
for i in range(1 , len(lr)):
dlr.append(abs(lr[i] - lr[i-1]))
# print(dlr)
if dl == dlr:
print("Funny")
else:
print("Not Funny")
l.clear()
lr.clear()
dl.clear()
dlr.clear()
q = int(input())
for i in range(q):
s = input()
r = s[::-1]
FunnyString(s)
|
06222657f38c48b418fb798c3e79d2830a12c5f5 | srinijakalluri/Python-Learning | /Day-4-lists.py | 839 | 4.5625 | 5 | #creating and printing a list
fruits = ['apple', 'mango', 'grapes']
print(fruits)
#adding elements to a list
fruits.append('cherry')
print(fruits)
fruits.insert(1,'kiwi')
print(fruits)
#length of the list
print(len(fruits))
#replacing an element
fruits[1]= 'banana'
print(fruits)
#deleting elements from a list
fruits.pop(1)
print(fruits)
fruits.remove('cherry')
print(fruits)
fruits.append('cherry')
fruits.append('banana')
fruits.append('kiwi')
print(fruits)
#organising a list
fruits.sort()
print(fruits)
fruits.reverse()
print(fruits)
#fetching an element from a list
print(fruits[5])
print(fruits[-1])
#slicing of a list
print(fruits[2:5])
#for loop
print("fruits are :")
for x in fruits :
print(x)
#copying a list
a = fruits[ : ]
b = fruits.copy()
print(a)
print(b)
|
862241736566821695eaa5805f0df4ec209c763b | kucengorenji/Python-tutorial-Youtube | /11_casting/main.py | 457 | 4.1875 | 4 |
# Casting in python
x = int(1)
y = int(4.123)
z = int("3")
print("---------------------------------------------")
print(x)
print(y)
print(z)
print("---------------------------------------------")
x = float(1)
y = float(4.123)
z = float("3")
print(x)
print(y)
print(z)
print("---------------------------------------------")
x = str(1)
y = str(4.123)
z = str("3")
print(x)
print(y)
print(z)
print("---------------------------------------------")
|
ae3d9f5b6dcce57ae5341e9a6f5af2c478209ee2 | saikrishna1909/Python-Programming | /week4(c).py | 235 | 3.734375 | 4 | num = int(input("Enter the length of the list:"))
lis = []
print("Enter the elements of list:")
for i in range(num):
e = eval(input())
lis.append(e)
filters = lambda x:x*2
result = map(filters,lis)
print(list(result))
|
14b146706a8ee3c554725fc56af29cdbac0d7dcc | nyqtofovian/py_folder | /test17.py | 89 | 3.6875 | 4 | list1 = [7, 5, 9, 5, 2, 0, 3, 6, 8, 1]
for i in range(len(list1)):
print(list1[0:i]) |
f1628a947a172dec520221f2f8fc620502ce9adf | AdityaSharma6/Python | /new folder/Project14.py | 1,481 | 4.125 | 4 | # **********************************************************
# Assignment: Project 14: List Remove Duplicates
#
# Description: Write a program (function!) that takes a list
# and returns a new list that contains all the elements of
# the first list minus all the duplicates.
#
# Author: Aditya Sharma
#
# Date Start: (2018/08/17)
# Date Completed: (2018/08/17)
#
# Completion time: 9:15 hours
#
# Honor Code: I pledge that this program represents my own
# program code. I received help from (enter the names of
# others that helped with the assignment; write no one if
# you received no help) in designing and debugging my program.
# *********************************************************
import random
list0 = []
list2 = []
number_of_elements = int( input("Number of elements? "))
max_value = int(input("Max Number? "))
min_value = int(input("Min Number? "))
random_number = random.randint(min_value, max_value)
counter = 0
while counter <= number_of_elements:
random_number = random.randint(min_value, max_value)
list1.append(random_number)
counter += 1
list1 = list0.copy()
index_counter = 0
list1.sort()
eliminations = 0
while index_counter < (number_of_elements - eliminations):
shows_up = list1.count(list1[index_counter])
if shows_up > 1:
counter = 1
while counter < shows_up:
list1.pop(index_counter)
counter += 1
eliminations += 1
index_counter += 1
list2 = list1.copy()
print(list2) |
43c1b02a53a602131446223a590b4e978ea708de | incrediblejustin/PythonProgramming | /Python入门/类-对象/02-protect.py | 994 | 4.125 | 4 | class Point:
def __init__(self, _x, _y):
self.__x = _x # 属性前加__, 变为私有属性,类内可修改, 类外不可修改
self.__y = _y
def __str__(self):
return "__x = %d, __y = %d"%(self.__x, self.__y)
def setx(self, new_x):
self.__x = new_x
def sety(self, new_y):
self.__y = new_y
# self.__print(), 私有方法可以再类内调用
#------------1. 私有方法的定义------------
def __print(self):
print("__x = %d, __y = %d"%(self.__x, self.__y))
a = Point(5, 10)
print("point a: ", a)
# a.__print() 无法使用,函数名前加 __ 表示该方法属于私有,不能再类外调用
#-------------2. 引用计数--------------------
b = a
print("point b: ", b)
a.setx(100) # a --> mem <-- b, mem.x = 100 , a和b都被执行了
print("point a after a.setx: ", a)
print("point b after a.setx: ", b)
#------------3. 私有属性-------------
# a.__x = 999 #不会被修改
# print(a) |
d371c4c13a5d7408967c2d517730a7aa7f39f3fa | syashakash/codeBase | /randoms/8puzzle_bfs.py | 4,489 | 3.890625 | 4 | import random
from collections import deque, namedtuple
from operator import eq
class Puzzle(namedtuple("PuzzleFields", ["board", "width", "zero_at"])):
"""
A class representing an '8-puzzle'.
- 'board' should be a square list of lists with integer entries 0...width²-1
e.g. [[1,2,3],[4,0,6],[7,5,8]]
"""
__slots__ = ()
def __new__(cls, board, width, zero_at=None):
if zero_at is None:
zero_at = board.index(0)
return super().__new__(cls, board, width, zero_at)
def solved(self):
"""
The puzzle is solved if the flattened board's numbers are in
increasing order from left to right and the '0' tile is in the
last position on the board
"""
# 0 is on board, so must be in last place
return all(map(eq, self.board, range(1, self.width**2)))
def actions(self):
"""
Return a list of 'move', 'action' pairs. 'move' can be called
to return a new puzzle that results in sliding the '0' tile in
the direction of 'action'.
"""
at = self.zero_at
if at >= self.width:
yield self._move(at - self.width)
if at + self.width < len(self.board):
yield self._move(at + self.width)
if at % self.width:
yield self._move(at - 1)
if (at + 1) % self.width:
yield self._move(at + 1)
def shuffle(self):
"""
Return a new puzzle that has been shuffled with 1000 random moves
"""
puzzle = self
for _ in range(1000):
puzzle = random.choice(list(puzzle.actions()))
return puzzle
def _move(self, to):
"""
Return a new puzzle where 'zero_at' and 'to' tiles have been swapped.
NOTE: all moves should be 'actions' that have been executed
"""
a, b = min(self.zero_at, to), max(self.zero_at, to)
board = list(self.board)
board[a], board[b] = board[b], board[a]
return Puzzle(tuple(board), self.width, to)
def pprint(self):
for i in range(0, len(self.board), self.width):
print(self.board[i:i+self.width])
class Node(namedtuple("NodeFields", ["puzzle", "parent"])):
"""
A class representing an Solver node
- 'puzzle' is a Puzzle instance
- 'parent' is the preceding node generated by the solver, if any
- 'action' is the action taken to produce puzzle, if any
"""
__slots__ = ()
def __new__(cls, puzzle, parent=None):
return super().__new__(cls, puzzle, parent)
@property
def action(self):
if self.parent is None:
return None
diff_to_action = {
+self.puzzle.width: 'D',
-self.puzzle.width: 'U',
+1: 'R',
-1: 'L',
}
return diff_to_action[self.puzzle.zero_at - self.parent.puzzle.zero_at]
def path(node):
"""
Reconstruct a path from to the root 'parent'
"""
seen = []
while node is not None:
seen.append(node)
node = node.parent
return reversed(seen)
def solve(start):
"""
Perform breadth first search and return a path
to the solution, if it exists (otherwise None).
"""
queue = deque([Node(start)])
seen = {start}
if start.solved():
return path(Node(start, None))
while queue:
node = queue.pop()
for move in node.puzzle.actions():
if move.board not in seen:
if move.solved():
return path(Node(move, node))
queue.appendleft(Node(move, node))
seen.add(move.board)
"""
stack = Stack()
stack.push([Node(start)])
seen = {start}
if start.solved():
return path(Node(start, None))
while not stack.isEmpty():
node = stack.top()
stack.pop()
for move in node.puzzle.actions():
if move.board not in seen:
if move.solved():
return path(Node(move, node))
stack.push(Node(move, node))
seen.add(move.board)
"""
def main():
board = 1, 6, 2, 0, 7, 3, 8, 4, 5
puzzle = Puzzle(board, 3)
#puzzle = puzzle.shuffle()
p = solve(puzzle)
if p is None:
print("No solutions")
for node in p:
print(node.action)
node.puzzle.pprint()
print()
if __name__ == "__main__":
main()
|
043f4a35bcb80f35ebe70d56f860cfeefc35e047 | ksuarz/hundred-days | /text/piglatin.py | 815 | 4.21875 | 4 | #!/usr/bin/env python
'''
Converts words to pig latin. This is a very naive implementation. All
non-alphanumeric, non-whitespace characters are treated as part of a word.
'''
import sys
if len(sys.argv) < 2:
print 'Usage: piglatin.py [TEXT]'
else:
# First, build up our vowels and consonants
start, end = ord('a'), ord('z') + 1
vowels = 'aeiou'
consonants = [chr(i) for i in range(start, end) if chr(i) not in vowels]
# Now, do some text manipulation
text = ' '.join(sys.argv[1:]).lower().strip()
result = []
for word in text.split():
c = word[0]
if c in consonants:
result.append(word[1:] + '-' + c + 'ay')
elif c in vowels:
result.append(word + 'way')
else:
result.append(word)
print ' '.join(result)
|
32ad24dbfb9a5f211b1673db77d339de670664c8 | roaden/adventofcode2015 | /1.py | 242 | 3.65625 | 4 | #Find the floor
floor = 0
#get the input
fin = open('input1.txt', 'r')
theMap = fin.readline().strip('\n')
#( goes up, ) goes down
for i in theMap:
if i == '(':
floor += 1
elif i == ')':
floor -= 1
print(floor)
|
50779020d2baa3bcbef5765289d84cfc64cfba4f | Nanutu/python-poczatek | /module_2/zad_38/main.py | 809 | 3.578125 | 4 | class Product:
pass
class Order:
pass
class Apple:
pass
class Potato:
pass
if __name__ == "__main__":
apple_1 = Apple()
apple_2 = Apple()
potato_1 = Potato()
potato_2 = Potato()
order_1 = Order()
order_2 = Order()
order_3 = Order()
order_4 = Order()
order_5 = Order()
print(apple_1, " typ: ", type(apple_1))
print(apple_2, " typ: ", type(apple_2))
print(potato_1, " typ: ", type(potato_1))
print(potato_2, " typ: ", type(potato_2))
order_list = [Order(), Order(), Order(), Order(), Order()]
product_dict = {"apple_1": Product(),
"apple_2": Product(),
"apple_3": Product(),
"apple_4": Product(),
}
print(order_list)
print(product_dict)
|
7e285caa54b85feb70b2f03f011085a69adceecd | Roberto117/Rush_Hour_Solver | /main/Car.py | 2,763 | 4.03125 | 4 | from Orientation import Orientation
import collections
#Structure to keep the coordinates of a car
Coordinates = collections.namedtuple('Coordinates', ['x1', 'x2', 'y1', 'y2'])
MAX_CAR_SIZE = 3#the biggest size a car can be
MIN_CAR_SIZE = 2#the minumum size a car can be
class Car():
initial_x = 0 #the first x position
initial_y = 0#the first y position
label = ''#the car's label
size = 0#how many blocks the car takes
orientation = Orientation.HORIZONTAL#the orientation of the car
def __init__(self, car_label, initial_x, intial_y , size , orientation):
self.initial_x = initial_x
self.initial_y = intial_y
self.size = size
self.orientation = orientation
self.label = car_label
def isHorizontal(self): return self.orientation == Orientation.HORIZONTAL
def isVertical(self): return self.orientation == Orientation.VERTICAL
def printCar(self):
#prints the cars items
#mostly used for debbuging
print("orientation:%s" % self.orientation)
print("initial_x:%s" %str(self.initial_x))
print("initial_y:%s"%str(self.initial_y))
print("label%s" % self.label)
print("size:%s"% str(self.size))
def getCoordinates(self):
#return the x y coordinates of the car
return Coordinates(self.initial_x, self.initial_x + self.size -1, self.initial_y, self.initial_y) if self.isHorizontal() else Coordinates(self.initial_x, self.initial_x, self.initial_y, self.initial_y + self.size -1)
def checkCollision(self, car2 , amount):
#check if this car collides with the given car
#this function assumes the car has not move yet and
#insted the amount the car is to be moved is given
coord1 = self.getCoordinates()
coord2 = car2.getCoordinates()
#for collision check we do a simple Bounding Box collision check with a small modification
#the difference being that one of the coordinates will expand based on the amount given and the orientation of the car
#for example if the car is horizontal and the amount is negative then the x1 diretion will expand so that the car expands left
#this will simulate all the blocks the car will pass through to get to that position and then we can do a bouding box check
if self.isHorizontal():
if amount >= 0:
return (coord1.x1 <= coord2.x2 and coord1.x2 + amount >= coord2.x1 and coord1.y1 <= coord2.y2 and coord1.y2 >= coord2.y1)
else:
return (coord1.x1 + amount <= coord2.x2 and coord1.x2 >= coord2.x1 and coord1.y1 <= coord2.y2 and coord1.y2 >= coord2.y1)
else:
if amount >= 0:
return (coord1.x1 <= coord2.x2 and coord1.x2 >= coord2.x1 and coord1.y1 <= coord2.y2 and coord1.y2 + amount >= coord2.y1 )
else:
return (coord1.x1 <= coord2.x2 and coord1.x2 >= coord2.x1 and coord1.y1 + amount <= coord2.y2 and coord1.y2 >= coord2.y1 )
|
a84a8226495e5017648ee8e165d5d85091ddbe25 | github-mohsinalam/Python | /Advance Function/together.py | 402 | 4.15625 | 4 | #Write a function called together that takes three parameters, the first is a required parameter that is a number (integer or float),
#the second is a required parameter that is a string, and the third is an optional parameter whose default is ” “.
#What is returned is the first parameter, concatenated with the second, using the third.
def together(x, s, t = ' '):
return str(x) + t + s
|
61f3ca6f7ebf4a82b83fb05e7a1a4be9bb8c02f5 | Leownhart/My_Course_of_python | /Geek University/Seção 5/Exercicios/EX15.py | 601 | 3.609375 | 4 | '''
15 - Usando um switch, escreva um programa que leia um inteiro entre 1 e 7 e imprima o dia
da semana correspondente a este numero. Isto é, domingo se 1, segunda-feira se 2, e assim
por diante.
Obs: if, elif, else no caso do Python.
'''
opção = int(input('Informe um número [1 a 7]: '))
if opção == 1:
print('Dómingo')
elif opção == 2:
print('Segunda-Feira')
elif opção == 3:
print('Terça-Feira')
elif opção == 4:
print('Quarta-Feira')
elif opção == 5:
print('Quinta-Feira')
elif opção == 6:
print('Sexta-Feira')
elif opção == 7:
print('Sábado') |
3eddbb39c4e97b6b7149901622885d397580ed3c | sheikh210/LearnPython | /functions/is_palindrome.py | 188 | 3.796875 | 4 | def is_palindrome(string: str) -> bool:
return string[::-1].casefold() == string.casefold()
print(is_palindrome("racecar"))
print(is_palindrome("cat"))
print(is_palindrome("Radar"))
|
811a99f35ac4ed58849835db81539e01035e3b62 | miaopei/MachineLearning | /LeetCode/github_leetcode/Python/shortest-unsorted-continuous-subarray.py | 1,708 | 3.90625 | 4 | # Time: O(n)
# Space: O(1)
# Given an integer array, you need to find one continuous subarray that
# if you only sort this subarray in ascending order,
# then the whole array will be sorted in ascending order, too.
#
# You need to find the shortest such subarray and output its length.
#
# Example 1:
# Input: [2, 6, 4, 8, 10, 9, 15]
# Output: 5
# Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order
# to make the whole array sorted in ascending order.
#
# Note:
# Then length of the input array is in range [1, 10,000].
# The input array may contain duplicates, so ascending order here means <=.
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
left, right = -1, -2
min_from_right, max_from_left = nums[-1], nums[0]
for i in xrange(1, n):
max_from_left = max(max_from_left, nums[i])
min_from_right = min(min_from_right, nums[n-1-i])
if nums[i] < max_from_left: right = i
if nums[n-1-i] > min_from_right: left = n-1-i
# Time: O(nlogn)
# Space: O(n)
class Solution2(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = sorted(nums) #sort the list
left, right = 0, len(nums) -1 #define left and right pointer
while (nums[left] == a[left] or nums[right] == a[right]):
if right - left <= 1:
return 0
if nums[left] == a[left]:
left += 1
if nums[right] == a[right]:
right -= 1
return right - left + 1
|
522b1b01a64b08202f162b7fae780dbf2219066e | szhongren/leetcode | /473/main.py | 1,692 | 4.3125 | 4 | """
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.
Example 1:
Input: [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
Note:
The length sum of the given matchsticks is in the range of 0 to 10^9.
The length of the given matchstick array will not exceed 15.
"""
class Solution(object):
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
total = 0
max_match = 0
count = 0
for v in nums:
count += 1
total += v
max_match = max(v, max_match)
if count < 4 or max_match > total // 4 or total % 4 != 0:
return False
nums.sort()
side = total // 4
return self.makeSquareRecur(nums, [side for _ in range(4)], side)
def makeSquareRecur(self, nums, sides, side):
return True
ans = Solution()
print(ans.makesquare([1, 1, 2, 2, 2]))
print(ans.makesquare([3, 3, 3, 3, 4]))
|
8c4e51b1a4ef78adced5b5577f13e07e987183ed | Aasthaengg/IBMdataset | /Python_codes/p03085/s321247736.py | 132 | 3.609375 | 4 | b = input()
lst = [["A", "T"], ["G", "C"]]
print(lst[0][lst[0].index(b) - 1]) if b in lst[0] else print(lst[1][lst[1].index(b) - 1]) |
c4191ac7113c9fb584a04e1831409eb421abb7eb | Md-Saif-Ryen/roc-pythonista | /Competitive Codes/is_sastry_num.py | 273 | 3.515625 | 4 | import math
#183 is a sastry number as 183184 is a #perfect square number of 432
def sastry_num(n):
"""returns True if a number n is sastry number,False otherwise"""
num = str(n) + str(n+1)
sqt = math.sqrt(int(num))
if int(sqt) - sqt == 0:
return True
return False
|
81ba5b9b1c7b45750c69d29eae90e0c5d9503677 | vijaykarthik123/icing | /icing/__old/parallel_distance_old.py | 10,948 | 3.671875 | 4 | import numpy as np
import multiprocessing as mp
def _dense_distance_dual(lock, list1, list2, global_idx, shared_arr, dist_function):
"""Parallelize a general computation of a distance matrix.
Parameters
----------
lock : multiprocessing.synchronize.Lock
Value returned from multiprocessing.Lock().
input_list : list
List of values to compare to input_list[idx] (from 'idx' on).
shared_arr : array_like
Numpy array created as a shared object. Iteratively updated with the
result.
Example:
shared_array = np.frombuffer(mp.Array('d', n*n).get_obj()).reshape((n,n))
Returns
-------
"""
list_len = len(list1)
# PID = os.getpid()
# print("PID {} takes index {}".format(PID, index_i))
while global_idx.value < list_len:
with lock:
if not global_idx.value < list_len: return
idx = global_idx.value
global_idx.value += 1
# if idx % 100 == 0: progressbar(idx, list_len)
elem_1 = list1[idx]
for idx_j in range(len(list2)):
shared_arr[idx, idx_j] = dist_function(elem_1, list2[idx_j])
def dense_dm_dual(list1, list2, dist_function, condensed=False):
"""Compute in a parallel way a distance matrix for a 1-d array.
Parameters
----------
input_array : array_like
1-dimensional array for which to compute the distance matrix.
dist_function : function
Function to use for the distance computation.
Returns
-------
dist_matrix : array_like
Symmetric NxN distance matrix for each input_array element.
"""
n, m = len(list1), len(list2)
n_proc = min(mp.cpu_count(), n)
index = mp.Value('i', 0)
shared_array = np.frombuffer(mp.Array('d', n*m).get_obj()).reshape((n,m))
ps = []
lock = mp.Lock()
try:
for _ in range(n_proc):
p = mp.Process(target=_dense_distance_dual,
args=(lock, list1, list2, index, shared_array, dist_function))
p.start()
ps.append(p)
for p in ps:
p.join()
except (KeyboardInterrupt, SystemExit): _terminate(ps,'Exit signal received\n')
except Exception as e: _terminate(ps,'ERROR: %s\n' % e)
except: _terminate(ps,'ERROR: Exiting with unknown exception\n')
dist_matrix = shared_array.flatten() if condensed else shared_array
# progressbar(n,n)
return dist_matrix
def _dense_distance(lock, input_list, global_idx, shared_arr, dist_function):
"""Parallelize a general computation of a distance matrix.
Parameters
----------
lock : multiprocessing.synchronize.Lock
Value returned from multiprocessing.Lock().
input_list : list
List of values to compare to input_list[idx] (from 'idx' on).
shared_arr : array_like
Numpy array created as a shared object. Iteratively updated with the result.
Example:
shared_array = np.frombuffer(mp.Array('d', n*n).get_obj()).reshape((n,n))
Returns
-------
"""
list_len = len(input_list)
# PID = os.getpid()
# print("PID {} takes index {}".format(PID, index_i))
while global_idx.value < list_len:
with lock:
if not global_idx.value < list_len: return
idx = global_idx.value
global_idx.value += 1
if (idx) % 100 == 0: progressbar(idx, list_len)
elem_1 = input_list[idx]
for idx_j in range(idx+1, list_len):
shared_arr[idx, idx_j] = dist_function(elem_1, input_list[idx_j])
def dense_dm(input_array, dist_function, condensed=False):
"""Compute in a parallel way a distance matrix for a 1-d array.
Parameters
----------
input_array : array_like
1-dimensional array for which to compute the distance matrix.
dist_function : function
Function to use for the distance computation.
Returns
-------
dist_matrix : array_like
Symmetric NxN distance matrix for each input_array element.
"""
n = len(input_array)
n_proc = min(mp.cpu_count(), n)
index = mp.Value('i', 0)
shared_array = np.frombuffer(mp.Array('d', n*n).get_obj()).reshape((n,n))
# np.savetxt("shared_array", shared_array, fmt="%.2f", delimiter=',')
ps = []
lock = mp.Lock()
try:
for _ in range(n_proc):
p = mp.Process(target=_dense_distance,
args=(lock, input_array, index, shared_array, dist_function))
p.start()
ps.append(p)
for p in ps:
p.join()
except (KeyboardInterrupt, SystemExit): _terminate(ps,'Exit signal received\n')
except Exception as e: _terminate(ps,'ERROR: %s\n' % e)
except: _terminate(ps,'ERROR: Exiting with unknown exception\n')
dist_matrix = shared_array + shared_array.T
if condensed: dist_matrix = scipy.spatial.distance.squareform(dist_matrix)
progressbar(n,n)
return dist_matrix
def _sparse_distance(lock, input_list, global_idx, rows, cols, data, dist_function):
"""Parallelize a general computation of a sparse distance matrix.
Parameters
----------
lock : multiprocessing.synchronize.Lock
Value returned from multiprocessing.Lock().
input_list : list
List of values to compare to input_list[idx] (from 'idx' on).
shared_arr : array_like
Numpy array created as a shared object. Iteratively updated with the result.
Example:
shared_array = np.frombuffer(mp.Array('d', n*n).get_obj()).reshape((n,n))
Returns
-------
"""
list_len = len(input_list)
# PID = os.getpid()
# print("PID {} takes index {}".format(PID, index_i))
while global_idx.value < list_len:
with lock:
if not global_idx.value < list_len: return
idx = global_idx.value
global_idx.value += 1
if (idx) % 100 == 0: progressbar(idx, list_len)
elem_1 = input_list[idx]
for idx_j in range(idx+1, list_len):
_res = dist_function(elem_1, input_list[idx_j])
if _res > 0:
i, j, d = idx, idx_j, list_len
c_idx = d*(d-1)/2 - (d-i)*(d-i-1)/2 + j - i - 1
data[c_idx] = _res
rows[c_idx] = i
cols[c_idx] = j
def sparse_dm(input_array, dist_function, condensed=False):
"""Compute in a parallel way a distance matrix for a 1-d input array.
Parameters
----------
input_array : array_like
1-dimensional array for which to compute the distance matrix.
dist_function : function
Function to use for the distance computation.
Returns
-------
dist_matrix : array_like
Sparse symmetric NxN distance matrix for each input_array element.
"""
n = len(input_array)
nproc = min(mp.cpu_count(), n)
idx = mp.Value('i', 0)
c_length = int(n*(n-1)/2)
data = mp.Array('d', [0.]*c_length)
rows = mp.Array('d', [0.]*c_length)
cols = mp.Array('d', [0.]*c_length)
ps = []
lock = mp.Lock()
try:
for _ in range(nproc):
p = mp.Process(target=_sparse_distance,
args=(lock, input_array, idx, rows, cols, data,
dist_function))
p.start()
ps.append(p)
for p in ps:
p.join()
except (KeyboardInterrupt, SystemExit): _terminate(ps,'Exit signal received\n')
except Exception as e: _terminate(ps,'ERROR: %s\n' % e)
except: _terminate(ps,'ERROR: Exiting with unknown exception\n')
data = np.array(data)
idx = data > 0
data = data[idx]
rows = np.array(rows)[idx]
cols = np.array(cols)[idx]
# print (data)
D = scipy.sparse.csr_matrix((data,(rows,cols)), shape=(n,n))
dist_matrix = D + D.T
if condensed: dist_matrix = scipy.spatial.distance.squareform(dist_matrix)
progressbar(n,n)
return dist_matrix
def _sparse_distance_opt(lock, input_list, global_idx, rows, cols, data, func):
"""Parallelize a general computation of a sparse distance matrix.
Parameters
----------
lock : multiprocessing.synchronize.Lock
Value returned from multiprocessing.Lock().
input_list : list
List of values to compare to input_list[idx] (from 'idx' on).
shared_arr : array_like
Numpy array created as a shared object. Iteratively updated with the
result.
Example:
shared_array = np.frombuffer(mp.Array('d', n*n).get_obj()).reshape((n,n))
Returns
-------
"""
list_len = input_list.shape[0]
# PID = os.getpid()
# print("PID {} takes index {}".format(PID, index_i))
while global_idx.value < list_len:
with lock:
if not global_idx.value < list_len: return
idx = global_idx.value
global_idx.value += 1
if (idx) % 100 == 0: progressbar(idx, list_len)
for i in range(idx, list_len-1):
_res = func(input_list[i], input_list[i + 1])
if _res > 0:
j, d = i+1, list_len
c_idx = d*(d-1)/2 - (d-i)*(d-i-1)/2 + j - i - 1
data[c_idx] = _res
rows[c_idx] = i
cols[c_idx] = j
def sparse_dm_opt(input_array, dist_function, condensed=False):
"""Compute in a parallel way a distance matrix for a 1-d input array.
Parameters
----------
input_array : array_like
1-dimensional array for which to compute the distance matrix.
dist_function : function
Function to use for the distance computation.
Returns
-------
dist_matrix : array_like
Sparse symmetric NxN distance matrix for each input_array element.
"""
n = input_array.shape[0]
nproc = min(mp.cpu_count(), n)
idx = mp.Value('i', 0)
c_length = int(n*(n-1)/2)
data = mp.Array('d', [0.]*c_length)
rows = mp.Array('d', [0.]*c_length)
cols = mp.Array('d', [0.]*c_length)
ps = []
lock = mp.Lock()
try:
for _ in range(nproc):
p = mp.Process(target=_sparse_distance_opt,
args=(lock, input_array, idx, rows, cols, data,
dist_function))
p.start()
ps.append(p)
for p in ps:
p.join()
except (KeyboardInterrupt, SystemExit): _terminate(ps, 'Exit signal received\n')
except Exception as e: _terminate(ps, 'ERROR: %s\n' % e)
except: _terminate(ps, 'ERROR: Exiting with unknown exception\n')
data = np.array(data)
idx = data > 0
data = data[idx]
rows = np.array(rows)[idx]
cols = np.array(cols)[idx]
# print (data)
D = scipy.sparse.csr_matrix((data, (rows, cols)), shape=(n, n))
dist_matrix = D + D.T
if condensed: dist_matrix = scipy.spatial.distance.squareform(dist_matrix)
progressbar(n, n)
return dist_matrix
|
77fe1c9610212c84a5cd3ea2793392603d5564fb | gkouretas/evision-scraper | /directory_setup.py | 753 | 3.578125 | 4 | import os
from datetime import datetime
def create_dir(dir):
if not os.path.exists(dir): # checks to ensure no duplicate directories exist (shouldn't ever happen)
os.makedirs(dir) # creates directory
return dir
def dir_exists(dir): # checks to see if file downloaded before resuming
while(True):
if os.path.exists(dir): # resumes when .csv is downloaded to desired directory
break
def directory(): # creates necessary directory for
dir_loc = os.getcwdb().decode() # gets current directory
dir_name = 'Database ' + datetime.now().strftime('%Y-%m-%d %H:%M:%S')
dir = create_dir(dir_loc + '/' + dir_name) # sends name to create_dir() to create main directory that will store everything
return dir |
a82e9d7d1b991d87b9686d4079d6ccae2edf125b | xiaoruijiang/algorithm | /.leetcode/108.将有序数组转换为二叉搜索树.py | 1,438 | 3.796875 | 4 | #
# @lc app=leetcode.cn id=108 lang=python3
#
# [108] 将有序数组转换为二叉搜索树
#
# https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/description/
#
# algorithms
# Easy (67.94%)
# Likes: 325
# Dislikes: 0
# Total Accepted: 49K
# Total Submissions: 70.8K
# Testcase Example: '[-10,-3,0,5,9]'
#
# 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
#
# 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
#
# 示例:
#
# 给定有序数组: [-10,-3,0,5,9],
#
# 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
#
# 0
# / \
# -3 9
# / /
# -10 5
#
#
#
from typing import List
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
"""
1. 递归
BST 左子树小于根,右子树大于根
"""
if not nums:
return None
ind = len(nums) // 2
root = TreeNode(nums[ind])
root.left = self.sortedArrayToBST(nums[:ind])
root.right = self.sortedArrayToBST(nums[ind + 1:])
return root
# @lc code=end
|
b16a43a1a498394691bb400a7b4d5a6c9420ee23 | klo9klo9kloi/TJHSST-AI | /ai/Graph Search/bfs_Torbert_1_2017jzou.py | 1,909 | 3.59375 | 4 | def findInfo(start, end, dict):
queue = Queue()
nextlevel = Queue()
lvl = {}
parents = {}
level = 1
lvl[start] = 0
parents[start] = None
nextlevel.put(start)
queue.put(nextlevel)
found = False
while queue.empty() == False:
current = queue.get()
nextlevel = Queue()
while current.empty() == False:
node = current.get()
if node == end:
found = True
break
else:
for neighbour in dict[node]:
if neighbour not in lvl:
lvl[neighbour] = level
parents[neighbour] = node
nextlevel.put(neighbour)
if found == True:
break
queue.put(nextlevel)
level = level + 1
global shortest
shortest = findPath(parents, start, end)
global edges
edges = findLevel(lvl, end)
def findPath(parents, start, end):
pathqueue = Queue()
tempqueue = LifoQueue()
pathqueue.put(end)
while pathqueue.empty() == False:
pathpart = pathqueue.get()
if pathpart == start:
break
tempqueue.put(pathpart)
pathqueue.put(parents[pathpart])
finallist = []
finallist.append(start)
while tempqueue.empty() == False:
finallist.append(tempqueue.get())
return finallist
def findLevel(level, end):
return level[end]
from pickle import load
from time import time
from queue import Queue, LifoQueue
dictionary = load(open('neigh.pkl', 'rb'))
shortest = []
edges = 0
puzzle = open('puzzle.txt').read().split()
for x in range(0, len(puzzle), 2):
target = puzzle[x]
destination = puzzle[x+1]
findInfo(target, destination, dictionary)
print(shortest)
print(edges)
print()
|
4c8c7a899992a034872fd606fcf1f6f36990617f | Saikiran2457/Innomatics_Internship | /Day - 5/3_Groups and Group addict.py | 112 | 3.578125 | 4 | import re
S=input()
a = re.search(r'([A-Za-z0-9])\1+',S)
if a:
print(a.group(1))
else:
print(-1)
|
264f48813c2c9115d7ce7947e5af1165eaaf2370 | u101022119/NTHU10220PHYS290000 | /student/100022141/HW3/Sorting.py | 576 | 3.921875 | 4 | import random
def random_list(N,a,b):
x=[]
for i in range(N):
x.append(random.randint(a,b))
return x
def selection_sort(x,N):
print random.sample(x,N)
def insertion_sort(x,N):
for i in range(N):
x.append(random.randint(a,b))
print x
def bubble_sort(x):
for i in range(len(x)):
for j in range(len(x)-1):
if x[j] < x[j+1]:
temp = x[j]
x[j] = x[j+1]
x[j+1] = temp
print x
a = 0
b = 100
insertion_sort(random_list(6,0,100),10)
bubble_sort(random_list(6,0,100))
|
e67ce16a2e1da2a679c0b6a4a38ba1944596d0de | eturanalp/Python-read-Excel-and-left-join | /rs_credit_debit_data_proc_exercise.py | 4,253 | 3.625 | 4 |
# coding: utf-8
# In[ ]:
# OVERVIEW and APPROACH
# This python program separates the matched records from the unmatched ones after reading data from URL.
#
# I had two possible solutions in my mind. The first one was to iterate through the data set and
# for each record identify if there is matching credit\debit. Write the record to the corresponding output file
# depending on the condition. For examle, if there is not a matching credit for a debit record then write it to the
# file for the unmatched.
# The second approach which I decided to pursue is to use SQL-like features of Pandas\datasets. I used the merge()
# function to make self-joins in order to match the credits to the debits on the specified fields.
# This option was less robust\flexible compared to the first option but resulted in a more easily maintainable code.
# Author: Mehmet Emin Turanalp, 12/28/2017
#References\Resources:
#1. https://stackoverflow.com/questions/25685545/sql-how-to-return-rows-from-left-table-not-found-in-right-table
#2. http://nbviewer.jupyter.org/urls/bitbucket.org/hrojas/learn-pandas/raw/master/lessons/03%20-%20Lesson.ipynb
#3. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html
# In[39]:
import pandas as pd
# In[40]:
url="https://s3-us-west-1.amazonaws.com/roofstock-test/data+assignment+dataset.xlsx"
df=pd.read_excel(url)
# In[41]:
print('OK!')
# In[42]:
df.dtypes
# In[43]:
#dfs=df.query('Property == "1601 MADISON COURT PALATKA, FL 32177"')
dfs=df.copy()
print('data set size is', len(dfs))
# In[44]:
# Assumption: all debit transactions are the ones with Debit not equal to null (same for credits)
dfs_all_debit=dfs[dfs['Debit'].notnull()]
dfs_all_credit=dfs[dfs['Credit'].notnull()]
# In[45]:
# Join the Credits and Debits tables such that Credits.Credit==Debits.Debit and the other 5 fields are equal.
# This is the list of matching debits and matching credits
dfs_debit=dfs_all_debit.merge(dfs_all_credit, right_on=('Property','Date','Payee / Payer','Type','Reference','Credit'), left_on=('Property','Date','Payee / Payer','Type','Reference','Debit'), how='inner')
dfs_credit=dfs_all_credit.merge(dfs_all_debit, right_on=('Property','Date','Payee / Payer','Type','Reference','Debit'), left_on=('Property','Date','Payee / Payer','Type','Reference','Credit'), how='inner')
dfs_credit
# In[46]:
# If the desired output is a single list containing all the matching debits and credits then we concatinate
matched=pd.concat([dfs_credit,dfs_debit])
# In[47]:
# We take a set difference of all debits and matched debits(subtract latter from the former). This gives us the unmatched debits:
# A left-join of all debits with matched debits such that the matched debit is null.
# This is normaly straightforward in SQL(see ref #1) but we can do it in two steps in Python.
# First left-join the two tables such that all rows from the left table (dfs_all_debit) is present in the interim result.
# This means that some of the matching rows in the right table (dfs_debit) are going to be null
#
dfs_debit_leftj=dfs_all_debit.merge(dfs_debit, right_on=('Property','Date','Payee / Payer','Type','Reference','Debit_x'), left_on=('Property','Date','Payee / Payer','Type','Reference','Debit'), how='left')
# In the second step we simply select those rows with the right debit value null.
unmatched_debit=dfs_debit_leftj[dfs_debit_leftj['Debit_x'].isnull()]
# In[48]:
#Repeat above step for credits
dfs_credit_leftj=dfs_all_credit.merge(dfs_credit, right_on=['Property','Date','Payee / Payer','Type','Reference','Credit_x'], left_on=['Property','Date','Payee / Payer','Type','Reference','Credit'], how='left')
unmatched_credit=dfs_credit_leftj[dfs_credit_leftj['Credit_x'].isnull()]
unmatched_credit
# In[50]:
# Write matched records to excel file
writer = pd.ExcelWriter('Matched.xlsx')
matched[matched.columns[0:10]].to_excel(writer,'Sheet1')
writer.save()
# Write unmatched records to excel file
writer = pd.ExcelWriter('UnMatched_Credits.xlsx')
unmatched_credit[unmatched_credit.columns[0:10]].to_excel(writer,'Sheet1')
writer.save()
writer = pd.ExcelWriter('UnMatched_Debits.xlsx')
unmatched_debit[unmatched_debit.columns[0:10]].to_excel(writer,'Sheet1')
writer.save()
# In[ ]:
|
530b48ac50ee05590c4a7010a3720ea4b666ec02 | nyakerariomokaya/andelabs3 | /missing_number_lab.py | 539 | 3.859375 | 4 | def find_missing(list1, list2):
list3 = []
l1 = len(list1)
l2 = len(list2)
for x in range(len(list1)):
for y in range(len(list2)):
if len(list1) ==0:
return 0
if len(list2) == 0:
return 0
elif l1 ==l2:
return 0
elif x == y:
return 0
elif l1 ==0 and l2 ==0:
return 0
break
else:
list3.append(1)
return list3
|
c3e043df404931e4b4c92bc70b9965787b95e7d5 | Lusius045/LucioRP | /Primeros Condicionales/Iniciales2/complementarios/TP5.py | 490 | 4.09375 | 4 | print("-------------------------------------------------------")
print("VELOCIDAD DE DOS VEHÍCULOS")
print("-------------------------------------------------------")
print("Ingrese la velocidad de dos vehículos:")
v1 = float("Vehìculo 1: ")
v2 = float("Vehìculo 2: ")
print("Ingrese la distancia:")
dis = float("Distancia: ")
if v1>0 and v2>0:
tiem = dis/(v1+v2)
print("Tiempo de encuentro: ",tiem)
else:
print("Ingrese otras velocidades a los vehículos") |
de167b900a5edb09e4d6f8cad0150da0800c0825 | extraname/sometask | /task.py | 6,589 | 3.546875 | 4 | from math import factorial
"""
Task 1.
Если мы из корректно записанного арифметического выражения, содержащего числа,
знаки операций и открывающие и закрывающие круглые скобки выбросим числа и знаки
операций, а затем запишем оставшиеся в выражении скобки без пробелов между ними,
то полученный результат назовем правильным скобочным выражением [скобочное
выражение "(()(()))" - правильное, а "()(" и "())(" - нет].
Найти число правильных скобочных выражений, содержащих N открывающихся и N
закрывающихся скобок. N вводится с клавиатуры. N неотрицательное целое число.
1 step - create main function only_nice_brackets with low level validator
2 step - create recursion wrapper _only_nice_brackets
3 step - return result
"""
def only_nice_brackets(n):
string_ = [""] * 2 * n
if n > 0:
_only_nice_brackets(string_, 0, n, 0, 0)
return
def _only_nice_brackets(string_, position, n, open_bracket, close_bracket):
if close_bracket == n:
for i in string_:
print(i, end="")
print()
return
else:
if open_bracket > close_bracket:
string_[position] = ')'
_only_nice_brackets(string_, position + 1, n, open_bracket, close_bracket + 1)
if open_bracket < n:
string_[position] = '('
_only_nice_brackets(string_, position + 1, n, open_bracket + 1, close_bracket)
print(only_nice_brackets(0))
'''
Task 2.
You are given a list of cities. Each direct connection between two cities has its transportation
cost (an integer bigger than 0). The goal is to find the paths of minimum cost between pairs of
cities. Assume that the cost of each path (which is the sum of costs of all direct connections
belonging to this path) is at most 200000. The name of a city is a string containing characters
a,...,z and is at most 10 characters long.2)
The Floyd algorithm is used to solve the problem. First, we create a matrix class,
instances of the class will be input.
The main problem for solving the problem is to create a layout of the correct matrix
'''
class Matrix:
inf = 100000
def __init__(self, ssize):
self.size = ssize
self.matrix = [[self.inf for x in range(ssize)] for x in range(ssize)]
for i in range(self.size):
self.matrix[i][i] = 0
def __getitem__(self, i):
return self.matrix[i]
def floyd(self):
for k in range(self.size):
for i in range(self.size):
for j in range(self.size):
if self.matrix[i][k] != self.inf and self.matrix[k][j] != self.inf:
self.matrix[i][j] = min(self.matrix[i][k] + self.matrix[k][j],
self.matrix[i][j])
def input(self, i, j, value=inf):
self.matrix[i][j] = value
def print(self):
for i in range(self.size):
for j in range(self.size):
if self.matrix[i][j] == self.inf:
print("inf\t", end='')
else:
print(self.matrix[i][j], "\t", end='')
print()
while True:
try:
number_of_tests = int(input("Number of tests: "))
if number_of_tests > 0:
print(number_of_tests)
else:
raise ZeroDivisionError
break
except:
print("Please, input correct number of cities!")
while True:
try:
number_of_cities = int(input("Number of cities: "))
if 0 < number_of_cities <= 100000:
print(number_of_cities)
else:
raise ZeroDivisionError
break
except:
print("Please, input correct number of cities!")
matrix = Matrix(number_of_cities)
current_city_number = 0
city_names = [number_of_cities]
for test in range(number_of_tests):
for i in range(number_of_cities):
while True:
try:
name = input("City name: ")
if len(city_names) < 10:
city_names.append(name)
p = int(input("Number of neighbours in " + name + ": "))
if p >= number_of_cities:
raise NameError
break
except:
print("BAD INPUT!!!\n")
for j in range(p):
while True:
try:
nr_cost = input("Number of city and cost: ").split(' ')
neighb_city_number = int(nr_cost[0]) - 1
transport_cost = int(nr_cost[1])
if (neighb_city_number == current_city_number
or neighb_city_number < 0
or transport_cost < 1):
raise ZeroDivisionError
matrix[current_city_number][neighb_city_number] = transport_cost
break
except:
print("BAD INPUT!\n")
current_city_number += 1
matrix.floyd()
while True:
try:
number_of_test_travels = int(input("Number of test travels: "))
if number_of_test_travels > 0:
print(number_of_test_travels)
else:
raise ZeroDivisionError
break
except:
print("Please, input correct number of cities!")
for i in range(number_of_test_travels):
while True:
cost_btw_cities = input("Input start and end cities of your travel: ").split(' ')
try:
start_city = int(city_names.index(cost_btw_cities[0])) - 1
end_city = int(city_names.index(cost_btw_cities[1])) - 1
break
except:
print("Input correct name of cities!")
print(matrix[start_city][end_city])
"""
Task 3.
Find the sum of the digits in the number 100! (i.e. 100 factorial)
1 step - from math import factorial
2 step - create a generic function to find the sum of the digits in the number
3 step - return result
"""
def sum_factorial(number):
result = 0
for digit in str(factorial(number)):
result += int(digit)
return result
print(sum_factorial(100))
|
4e559e59d88e0fc08927505b2aca7591f7cfb042 | SnehalSutar9823/PythonAssignment4 | /Assg4_1.py | 165 | 3.765625 | 4 | def main():
number=int(input("Enter number:"))
ans=lambda number : number * number
print(ans(number))
if __name__=="__main__":
main()
|
0e0d2f4d12c5d503f50997bdd6ef6941b56f2695 | adinhobl/GeneticAlg | /GA.py | 10,695 | 3.984375 | 4 | import numpy as np
import random
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from typing import List, Dict, Tuple, Any
# Inspired by: http://alturl.com/f6mot
class City:
def __init__(self, x: float, y: float) -> None:
# init defines a single city's location using x and y coordinates
self.x = x
self.y = y
def distance(self, city: 'City') -> float:
# Calculates the distance between City and another city
xDist = abs(self.x - city.x)
yDist = abs(self.y - city.y)
distance = np.sqrt(xDist ** 2 + yDist ** 2)
return distance
def to_tupl(self) -> Tuple:
return (self.x, self.y)
def __repr__(self) -> str:
# Defines the printable representation of the City
return "(" + str(self.x) + "," + str(self.y) + ")"
class Route:
def __init__(self, route: List['City']) -> None:
# init defines a route between cities
self.route = route
self.distance: float = 0.0
self.fitness: float = 0.0
self.numStops: int = len(self.route)
def routeDistance(self) -> float:
# calculates the total distance of a route
if self.distance == 0: # prevents recalculating fitness for a route
pathDistance = 0.0 # temporary calculation variable
for i in range(self.numStops):
fromCity = self.route[i]
# if you are not at the last city, the next city is the next
# in the route. Else, you must go back to the first city.
if i + 1 < self.numStops:
toCity = self.route[i + 1]
else:
toCity = self.route[0]
pathDistance += fromCity.distance(toCity)
self.distance = pathDistance
return self.distance
def routeFitness(self) -> float:
# calculates the fitness of a route from its distance
if self.fitness == 0:
self.fitness = calcFitness(self.routeDistance())
return self.fitness
def coordinates(self) -> Tuple[List[float], List[float]]:
x_list, y_list = [], []
for city in self.route:
x_list.append(city.to_tupl()[0])
y_list.append(city.to_tupl()[1])
return x_list, y_list
def __repr__(self) -> Any:
# Defines the printable representation of the City
return str(self.route)
def calcFitness(routeDistance: float):
return 1 / routeDistance
# for generating random lists of cities
def initialPopulation(popSize: int, numCities: int, cityListIn: List = None) -> List[List['City']]:
# creates a list of random cities with k entries or use cityListIn, if provided
# note that if you use cityListIn, you still must provide its numCities and popSize
cityList: List = []
if cityListIn is not None:
for city in cityListIn:
cityList.append(city)
else:
for _ in range(numCities):
cityList.append(City(x=round(random.random()*200),
y=round(random.random()*200)))
population = []
for _ in range(popSize):
if cityListIn is not None:
random.seed(11)
population.append(random.sample(cityList, len(cityList)))
return population
def rankRoutes(population: List[List['City']]) -> List[Tuple[int, float]]:
# ranks the routes in a list of routes according to fitness
fitnessResults: Dict = {}
for i in range(len(population)):
# makes a list of cities into a route, then finds fitness
fitnessResults[i] = Route(population[i]).routeFitness()
# can also use itemgetter(2)
return sorted(fitnessResults.items(), key=lambda x: x[1], reverse=True)
def selection(popRanked: List[Tuple[int, float]], numElites: int = 0) -> List[int]:
# select which individuals are saved as parents of the next generation
# Fitness propporionate selection implemented with pd.sample
# Eliteness implemented by picking top individuals
df = pd.DataFrame(np.array(popRanked), columns=["Index", "Fitness"])
df["weights"] = 100 * df.Fitness / df.Fitness.sum()
selection_results = df.sample(n=len(popRanked)-numElites,
replace=True,
weights=df.weights
).values[:, 0]
elite_results = df.iloc[0:numElites, 0].values
# print(df) # to see the dataframe for checking
selection_results = list(map(int, np.concatenate(
(selection_results, elite_results)).tolist()))
return selection_results
def matingPool(population: List[List['City']], selection_results: List[int]) -> List[List['City']]:
# picks the mating individuals out of the population based on their selection_results
mating_pool: List = []
for i in range(len(selection_results)):
index = selection_results[i]
mating_pool.append(population[index])
return mating_pool
def breed(parent1: List['City'], parent2: List['City']) -> List['City']:
# uses ordered crossover to breed 2 parents to make a new individual
# print("Parent1: ", parent1, "\n")
# print("Parent2: ", parent2, "\n")
child: List = [None] * (len(parent1))
# print("Child initialization: ", child, "\n")
geneFromParent1 = (random.randint(0, len(child) - 1),
random.randint(0, len(child) - 1))
geneFromParent1_start = min(geneFromParent1)
geneFromParent1_end = max(geneFromParent1)
# print(geneFromParent1, geneFromParent1_start, geneFromParent1_end, "\n")
for gene in range(geneFromParent1_start, geneFromParent1_end + 1):
child[gene] = parent1[gene]
# print("Child after p1: ", child, "\n")
for i in range(0, len(child)):
for j in parent2:
if j not in child:
if child[i] is None:
child[i] = j
# print("Child after p2: ", child, "\n")
return child
def breedPopulation(mating_pool: List[List['City']], numElites: int = 0):
children: List = [] # final list of children
numNonElite = len(mating_pool) - numElites
pool = random.sample(mating_pool, len(mating_pool)
) # shuffles the pool around
# Carry elites over to next breeding population
for i in range(1, numElites+1):
children.append(mating_pool[-i])
# breed population - numElites number of individuals mate with the elites.
for i in range(0, numNonElite):
child = breed(pool[i], pool[len(mating_pool)-i-1])
children.append(child)
return children
def swapMutation(individual: List['City'], mutationRate):
for swapped in range(len(individual)):
if random.random() < mutationRate:
swapWith = int(random.random() * len(individual))
individual[swapped], individual[swapWith] = \
individual[swapWith], individual[swapped]
return individual
def mutatePopulation(children: List[List['City']], mutationRate=0):
mutatedPop: List = []
for individual in range(0, len(children)):
mutatedIndividual = swapMutation(children[individual], mutationRate)
mutatedPop.append(mutatedIndividual)
return mutatedPop
def nextGeneration(currentGen: List[List['City']], numElites: int, mutationRate: float = 0):
popRanked = rankRoutes(currentGen)
# extracting the best route of this generation
bestCurrentGenRoute = Route(currentGen[popRanked[0][0]])
bestCurrentGenFitness = bestCurrentGenRoute.routeFitness()
bestCurrentGenDistance = bestCurrentGenRoute.routeDistance()
selectionResults = selection(popRanked, numElites)
matingpool = matingPool(currentGen, selectionResults)
children = breedPopulation(matingpool, numElites)
nextGeneration = mutatePopulation(children, mutationRate)
return nextGeneration, bestCurrentGenRoute, bestCurrentGenFitness, bestCurrentGenDistance
def geneticAlgorithm(popSize: int, numCities: int, numElites: int, numGens: int, mutationRate: float = 0.01, cityListIn: List = None):
pop = initialPopulation(popSize, numCities, cityListIn)
bestInitialRoute = Route(pop[rankRoutes(pop)[0][0]])
print("Initial Distance: " + str(bestInitialRoute.routeDistance()))
bestRouteByGen: List = []
bestFitnessByGen: List = []
bestDistanceByGen: List = []
for _ in range(0, numGens):
pop, bestCurrentGenRoute, bestCurrentGenFitness, bestCurrentGenDistance = \
nextGeneration(pop, numElites, mutationRate)
bestRouteByGen.append(bestCurrentGenRoute)
bestFitnessByGen.append(bestCurrentGenFitness)
bestDistanceByGen.append(bestCurrentGenDistance)
# used for testing convergence
# if bestCurrentGenDistance < 852:
# print(_)
# break
bestFinalRoute = Route(pop[rankRoutes(pop)[0][0]])
print("Final Distance: " + str(bestFinalRoute.routeDistance()))
params = [popSize, numCities, numElites, numGens, mutationRate, cityListIn]
return bestFinalRoute, bestRouteByGen, bestFitnessByGen, bestDistanceByGen, params
def distancePlot(bestDistanceByGen: List[int], params: List):
plt.plot(bestDistanceByGen)
plt.ylabel('Distance')
plt.xlabel('Generation')
s = "popSize: " + str(params[0]) + "\nnumCities: " + str(params[1]) + \
"\nnumGens: " + str(params[3]) + "\nmutationRate: " + str(params[4])
plt.text(330, 2010, s)
plt.text(0, bestDistanceByGen[0], bestDistanceByGen[0].round(1))
plt.text(len(bestDistanceByGen),
bestDistanceByGen[-1], bestDistanceByGen[-1].round(1))
plt.show()
def evolutionPlot(bestRouteByGen, bestDistanceByGen, cityListIn):
fig, ax = plt.subplots()
xdata = []
ydata = []
line, = plt.plot([], [], 'C3', animated=True)
gen_text = ax.text(150, 185, '')
for i in range(len(bestRouteByGen)):
x, y = bestRouteByGen[i].coordinates()
xdata.append(x)
ydata.append(y)
def init():
x = [i[0] for i in cityListIn]
y = [i[1] for i in cityListIn]
ax.scatter(x, y, s=60)
gen_text.set_text('')
return line,
def animate(i):
numGens = len(bestRouteByGen)
line.set_data(xdata[i % numGens], ydata[i % numGens])
gen_text.set_text("Generation:" + str(i % numGens) +
"\nDistance: " + str(round(bestDistanceByGen[i % numGens], 2)))
return line, gen_text
ani = animation.FuncAnimation(
fig, animate, init_func=init, blit=True, repeat_delay=2000, interval=50, save_count=500)
ani.save("GA4TSM.gif")
plt.show()
|
645912292753b747440d66dbd1ba49e09f16bb12 | TJSGITTO/Project01 | /Test01.py | 1,252 | 4.1875 | 4 | #populate a list of students
student_names = ["Mark","Katarina","Jessica","Connor","Ian","Natalie", "Brad","Amy","Sarah","Kelly"]
Building_materials = ["Studs", "Sheetrock", "Fastners", "Doors", "Lights"]
#Adding a name to the list
#student_names.append("Homer")
#Printing the list using for loop
#x=0
#for name in student_names:
# print (student_names [x])
# x+=1
#Printing the list using a for loop
#for name in student_names:
# print("student_name is {0}".format(name))
#Printing the list using format statement
#x = 0
#for materials in Building_materials:
# print("The building material is {0}".format(materials))
#Printing the list using for loop and the Range statement
#x=0
#for index in range(8):
# print("The name of the", x, "student is ",student_names[x])
# x += 1
#Using For and Break statement
#for m in Building_materials:
# if m == "Sheetrock":
# print ("Found it at")
# break
# print (m)
# Using Dictionaries
Student = {
"First_Name": "Nick",
"Last_Name": "Sudelski",
"Student_ID": 5422
}
try:
Family_Name = Student["Name"]
except KeyError:
print("Error found in last name")
except TypeError:
print("this is a good code!")
except:
print("Unknown Error")
|
576913e1b39a6e703fe2e433de664d031a481e3c | Fischerlopes/EstudosPython | /cursoEmVideoMundo3/ex093.py | 911 | 3.984375 | 4 | # Crie um programa que gerencie o aproveitamento de um jogador de futebol.
# O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida.
# No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato.
jogador = dict()
gols = list()
tot = 0
jogador['nome'] = str(input('Nome do jogador: '))
print(jogador)
n = int(input(f'Quantas partidas {jogador["nome"]} jogou?'))
for c in range(1,n + 1):
g = int(input(f'Quantos gols na partida {c} ? '))
gols.append(g)
tot = sum(gols)
jogador['gols'] = gols
jogador['Total'] = tot
print('-=' * 30)
print(jogador)
print('-=' * 30)
for k , v in jogador.items():
print(f'O campo {k} tem valor {v}')
print('-=' * 30)
print(f'O jogador {jogador["nome"]} fez {n} partidas')
for k, v in enumerate(jogador['gols']):
print(f' ==> Na partida {k}, fez {v} gols') |
2b8c44fd3cbeffdfd1ba11fe7e842e6bc3c6df3c | dtrodger/undergrad-python | /lists.py | 1,356 | 4.1875 | 4 | import random
# David Rodgers
# INFO-I 210
# Define functions that contain nouns, verbs, and abjective in lists.
# Each function should return an item from its list when called.
def random_noun():
nouns = ["Carrot People","Zombie Fat Albert","potato salad","Nick Cage","Steve Buscemi"]
return nouns[random.randrange(5)]
def random_verb():
verbs = ["smooth talked","twerked with","anticipated confrontation with","fell for","halved"]
return verbs[random.randrange(5)]
def random_adjective():
adjectives = ["spastic","gigantic","standard","fierce","unexpected"]
return adjectives[random.randrange(5)]
# Define a function that generates a random sentace using the previously
# defined functions.
def random_sentance():
return "The "+random_adjective()+" "+random_noun()+" "+random_verb()+" the "+random_adjective()+" "+random_noun()+". "
# Define a function that takes a number as an input, and outputs a string
# containing the specified number of sentances.
def random_essay(number):
num = number
output_str = ""
while num > 0:
output_str += random_sentance()
num = num-1
return output_str
# Ask the user how many sentances they want in a paragraph and print it.
number = int(raw_input("How many sentances would you like in your essay? "))
print "\nHere's your automatically-generated essay:\n"
print random_essay(number) |
ac5066fb72fb52966c523a9d0fe350d4b376712d | Hanjongwon/algorithm | /11_dynamic programming/fibonacci.py | 628 | 3.9375 | 4 | import time
start_time = time.time()
# def fibonacci(n):
# if n < 2:
# return n
# else:
# return fibonacci(n-1) + fibonacci(n-2)
#
#
# print(fibonacci(36))
# print(time.time() - start_time)
def fibonacci_td(n):
if n < 2:
return n
if _memo[n] is None:
_memo[n] = fibonacci_td(n-1) + fibonacci_td(n-2)
return _memo[n]
_memo = [None] * 100
print(fibonacci_td(int(input())))
# def fibonacci_bu(n):
# memo = [0, 1]
#
# for i in range(2, n+1):
# memo.append(memo[i - 1]+ memo[i - 2])
#
# return memo[-1]
#
#
# print(fibonacci_bu(int(input())))
#
#
|
80b841980f8bae50f9663229d67897a4221a0fa4 | ZuoYaoyao/python_ML1 | /udacity/python/Project2/sort.py | 698 | 3.8125 | 4 | import operator
x = {'china':2, 3:4, 4:3, 2:1, 0:0}
x['china'] += 1
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
print(sorted_x)
location = {'大陆': 0, '美国': 0, '香港': 0, '台湾': 0, '日本': 0, '韩国': 0,
'英国': 0, '法国': 0, '德国': 0, '意大利': 0, '西班牙': 0,
'印度': 0, '泰国': 0, '俄罗斯': 0, '伊朗': 0, '加拿大': 0,
'澳大利亚': 0, '爱尔兰': 0, '瑞典': 0, '巴西': 0, '丹麦': 0}
three_type = [location, location, location]
three_type[0]['大陆'] += 1
for item in three_type:
print(item)
sorted_x = sorted(location.items(), key=operator.itemgetter(1),reverse=True)
print (sorted_x[0]) |
55f625c2b9c535bdb3a89b923fa0020d7ce8582d | Yang-Jianlin/python-learn | /pycharm/day17_3_22/fibo.py | 148 | 3.6875 | 4 | def fibo(num):
n, a, b = 0, 0, 1
while n < num:
yield b
a, b = b, a+b
n += 1
f = fibo(6)
for n in f:
print(n)
|
3838ade06500d2165fd00bcb89ec3d54a27acd69 | raunaklakhwani/Algorithms | /Combinations/MainHandlingDuplicates.py | 816 | 3.734375 | 4 |
count = 0
def generateCom(lists,r):
'''
This method takes the input list and generates all the combinations. Does handle duplicates
'''
lists.sort()
if r > len(lists):
return
else:
generateComUtil(lists,r,[],0)
def generateComUtil(lists,r,gen,index):
global count
#print lists,r,gen,index,len(lists) - r + 1
if len(gen) == r:
count = count + 1
print gen
else:
i = index
while i < len(lists) - r + len(gen) + 1:
x = gen[:]
x.append(lists[i])
generateComUtil(lists,r,x,i+1)
while i+1 < len(lists) and lists[i] == lists[i+1]:
i = i + 1
i = i + 1
if __name__ == '__main__':
generateCom([1,2,2,4,5], 4)
print count |
acfff741192c081a6853db45ed11f334fd2304fc | barathviknesh/Python | /miniex1.py | 127 | 4 | 4 | name=str(input("ENTER UR NAME: "))
year=int(input("UR DOB YEAR:"))
age=2020-year
print(name+" age is approx. "+str(age))
|
ca7e8853f6fe5fa32fd2932cdc5cd49d1c3f626a | amalfiyd/explore-repo | /11 - HackerRank/HackerRank/DrawingBook.py | 482 | 3.546875 | 4 | def drawingBook(n,p):
if p <= n // 2:
# start from left
print('left')
counter = 0
curPage = 1
while curPage < p:
curPage += 2
counter += 1
else:
# start from right
print('right')
counter = 0
curPage = n + 1 if n % 2 == 0 else n
while p < curPage - 1:
curPage -= 2
counter += 1
return counter
n = 7
p = 4
temp = drawingBook(n,p)
print(temp) |
24d111c81fc7f6ed12a15e96f75faf9765457c1f | temirbekbalabek/webdev2019 | /week 10/HackerRank/14.py | 281 | 3.6875 | 4 | def mutate_string(s, p, c):
l = ""
for i in range(len(s)):
if i == p:
l += c
else:
l += s[i]
return l
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new) |
863c0a4827563e86a5859d69c3c50ff9200011dd | bemarte/Exercicios-Basicos-Python | /Estrutura_Repetição/Ex_ER_2.py | 286 | 4.125 | 4 | #Faça um programa que receba dois números inteiros e
# gere os números inteiros que estão no intervalo
# compreendido por eles.
num1 = int(input("Insira o numero x: "))
num2 = int(input("Insira o numero y: "))
lista = range(num1,num2+1)
for item in lista:
print(item,end=" ") |
f42842bb034e4f8baf44912a3be4d1fda694a471 | carlygrizzaffi/Girls-Who-Code-2019 | /chatbot.py | 1,618 | 4.40625 | 4 | # --- Define your functions below! ---
# --- Put your main program below! ---
def default():
print("Welcome to Sugars! My name is Jeff.")
def say_default():
print("Hint: try saying hi")
def say_hello(name):
print ("Hi,\n" + name)
def location(x):
print()
if x == "New York":
print()
def toppings(y):
print()
if y == "yes":
print()
elif y == "no":
print()
def sprinkles(z):
if z == "yes":
print()
elif z == "no":
print()
return()
def bye(c):
if c == "yes":
print()
return()
elif c == "no":
print ()
return()
def main():
default()
answer = input(" What is your name?")
say_hello(answer)
answer = input("What flavor of ice cream would you like?")
while answer == "chocolate":
print("Bad choice, choose a new flavor.")
#We use else instead of elif because we are not looking for any particular answer
else:
print("Wonderful! I will get that for you right away.")
mylocation = input("Where do you live?")
location(mylocation)
mysprinkles = input("Did you know that we offer free sprinkes for any customer in NYC?! Would you like some?")
sprinkles(sprinkles)
mytoppings = input("Nice! Would you like any other toppings?")
toppings(mytoppings)
mybye = input("Here's your ice cream. Thank You! Have a nice day come back again!")
bye(mybye)
# DON'T TOUCH! Setup code that runs your main() function.
main()
|
acd547227a90ffe1a23d913e8950197b37253e20 | ludovici-philippus/projetos_tkinter_excript | /Aula 18.py | 423 | 3.640625 | 4 | from tkinter import *
janela = Tk()
lb1 = Label(janela, text="ESPAÇO", width="20", height="3", bg="blue")
lb_horizontal = Label(janela, text="HORIZONTAL", width="10", bg="yellow")
lb_vertical = Label(janela, text="VERTICAL", bg="green")
lb1.grid(row=0, column=0)
lb_horizontal.grid(row=1, column=0, sticky=E)
lb_vertical.grid(row=0, column=1, sticky=N)
janela.geometry("300x300+200+200")
janela.mainloop() |
5cd4312f7ea771f7eec6e722c6dc641cd3a6df66 | flightdutch/Python-HomeTasks | /L3/first_simple_n.py | 408 | 3.734375 | 4 | # Вывести на экран 10 первых простых чисел
def is_prime(n):
for i in range(2, n):
if (n % i) == 0:
print('{} % {} = {}'.format(n, i, n % i))
return False
return True
n = 1
i = 1
while True:
if is_prime(n):
print('Simple Number N {} : {}'. format(i, n))
i += 1
n += 1
if i > 10:
break
print('End')
|
43172380454490320135fb51b43bf414aa51c708 | github653224/HogwartsLG7 | /python_practice/hero.py | 636 | 3.875 | 4 | class Hero:
hp = 0
power = 0
name = ""
def fight(self, enemy_hp, enemy_power):
"""
两方进行一回合制的对打
:param enemy_hp: 敌人的血量
:param enemy_power: 敌人的攻击力
:return:
"""
# 我的血量
# 通过实例变量的方式调用类变量
final_hp = self.hp - enemy_power
enemy_final_hp = enemy_hp - self.power
if final_hp > enemy_final_hp:
print(f"{self.name}赢了")
elif final_hp < enemy_final_hp:
print("敌人赢了")
else:
print("我们打平了")
|
9868df6b8c5f26a3bea3dce58fa4b701447d7803 | s18011/programming-term2 | /src/basic-c2/task20180712.py | 228 | 3.921875 | 4 | for x in range(1, 10):
str_line = ""
for y in range(1, 10):
ans_int = x * y
ans_str = str(ans_int)
ans_str = ans_str.rjust(3)
str_line = str_line + ans_str
print(str_line)
print()
|
3a63c1336d4a73999221e0a97ad8819637c84d8c | divyagahlot99/Interview_Prep | /sorting_techniques/insertion_sort.py | 310 | 3.984375 | 4 | def insertion_sort(arr):
n = len(arr)
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
arr = [4, 2, 8, 6, 4, 1, 0, 15, 4, 3]
print(insertion_sort(arr))
|
e6cd59d4bc1ec26de1904bdf299cea4b1c303e6a | samaromku/python_lessons | /server/ClassTest.py | 985 | 3.546875 | 4 | class MyClass:
variable = "blah"
def function(self):
return "This is a message inside the class." + str(self)
myObject = MyClass()
class UserFirstLastNames:
def __init__(self, first_name):
self.first_name = first_name
first_name = ""
lest_name = ""
user = UserFirstLastNames("first_name")
user.first_name = "Andrey"
user.last_name = "Savchenko"
anotherUser = UserFirstLastNames("second_name")
anotherUser.first_name = "Andrey"
class UserWithFirstLastAgeSex:
first_name = ""
last_name = ""
age = 0
sex = ""
def __init__(self, first_name, last_name, age, sex):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.sex = sex
userWithConstructor = UserWithFirstLastAgeSex("Borja", "Martin", 30, "male")
def doSomethingWithUserData(user: UserWithFirstLastAgeSex):
print(vars(user))
doSomethingWithUserData(userWithConstructor)
doSomethingWithUserData(user)
|
8eb55a84b955da5159e3c61ff48b61547009a2a7 | ucsb-cs8-s18/LECTURE-05-29-Recursion-part-2 | /sumOfListRecursive.py | 507 | 3.5625 | 4 |
def sumList(intList):
if intList==[]:
return 0
else:
return intList[0] + sumList(intList[1:])
def sumList2(intList):
if intList==[]:
return 0
first = intList[0]
rest = intList[1:]
return first + sumList2(rest)
def sumList3(intList):
return sumListHelper(0,intList)
def sumListHelper(totalSoFar, intList):
if intList==[]:
return totalSoFar
first = intList[0]
rest = intList[1:]
return sumListHelper(totalSoFar + first, rest)
|
cc3432197f62e8fc7cd9806215f690d5c5bab038 | hdb169/git | /python/examples/three.py | 627 | 4 | 4 |
import math#continued to basics oct 30, 2019
def areaofcircle(r):# so need top give value of r
PI = 3.1416
return (PI * r* r)
print ("Area of circle is %.6f" % areaofcircle(19))
def area_square(l):
return(l*l)
print("Area of square is %.2f" % area_square(25.67) )
c = 3 *100000000
def energy(p,m):
return(math.sqrt(p*p *c *c + m *m *c *c *c *c))
print("energy = %.4f" % energy(2.6, 2.6))
#one number ^ (other number)
def power(x,y):
return(x**y)
print("x to the power y is = %.3f" % power(6,3))
#4^4
print (4**4)
m= 20.
n =90.
print (m/n)
print (m*n)
print (m**n)
print(n % m) # remainder of 90/20
|
55b2f9d36a20286347641e906c13dd11c40dda01 | savvyknee/OOP100 | /numbers.py | 3,012 | 4.125 | 4 | # Andrew Savini CST100 23Feb2014 numbers.py
# Takes a bunch of numbers that the user enters, computes their total average, the average of the positive numbers, and the averages
# of the negative numbers, then outputs the list of numbers and the key:value dictionary entries of everything.
def main():
# get a list of numbers from the user
# -9999 is the sentinel value. when entered, we exit the while loop
# otherwise each number is appended to listOfNumbers list
# program returns a list of user inputted numbers
def getNumbers():
"getNumbers() prompts the user for numbers, entering the numbers in a returned list. Sentinel value \
is -9999."
numList = []
numbers = 0
while numbers != -9999:
try:
numbers = eval(input("Enter a number(-9999 to end):"))
except:
print("You have entered an illegal value. Terminating.")
return 1
if numbers < -9999 or numbers > -9999:
numList.append(numbers)
elif numbers == -9999:
return numList
# Use numbers in numList to find the average of all numbers
def allNumAvg(numList):
"allNumAvg(numList) takes the numbers input originally and computes their average."
counter = 0.0
runningTotal = 0.0
finalAvg = 0.0
for i in numList:
counter += 1
runningTotal = runningTotal + i
finalAvg = runningTotal/counter
return finalAvg
# Use numbers in numList to find the average of all the positive numbers in numList
# If there are no positive numbers, we change the counter to a 1, so we are not dividing by 0, avoiding an error.
def posNumAvg(numList):
"posNumAvg(numList) takes only the positive numbers input by user to compute the average."
counter = 0.0
runningTotal = 0.0
finalAvg = 0.0
for i in numList:
if i >= 0.0:
counter += 1
runningTotal = runningTotal + i
if counter == 0:
counter = 1
finalAvg = runningTotal/counter
return finalAvg
# Use numbers in numList to find the average of all the negative numbers in numList
# If there are no negative numbers, we change the counter to a 1, so we are not dividing by 0, avoiding an error.
def nonPosAvg(numList):
counter = 0.0
runningTotal = 0.0
finalAvg = 0.0
for i in numList:
if i < 0.0:
counter += 1
runningTotal = runningTotal + i
if counter == 0:
counter =1
finalAvg = runningTotal/counter
return finalAvg
inputNumbers = getNumbers()
# If the user enters anything other than a number, we exit the program. Ain't nobody got time for that.
if inputNumbers == 1:
return
# Create the dictionary with key:value pairs
dictionary = {'AvgPositive':0,'AvgNonPos':0,'AvgAllNum':0}
# Change the dictionary values to reflect the computed averages as input by the user
dictionary['AvgAllNum'] = allNumAvg(inputNumbers)
dictionary['AvgPositive'] = posNumAvg(inputNumbers)
dictionary['AvgNonPos'] = nonPosAvg(inputNumbers)
# Provide the user with some output
print("The list of all the numbers entered is: ")
print(inputNumbers)
print("The dictionary with averages is:")
print(dictionary)
main()
|
cd414ead6a256ce54815e1a8a41bbbe7d702810c | VikramVikrant/Python-DS | /palindrome2.py | 287 | 4.15625 | 4 | ## To check whether a string is palindrome or not.
x=input()
w=''
for i in x: ## if we take input string as mada
w = i + w ## see here i + w ,so it's added like this m,am,dam,adam
if(x==w):
print('Yes it is a palindrome.')
if(x!=w):
print("It's not a palindrome.") |
312d7e349baf0f5f695bb3b17d06df6901072569 | NoctemLeges/School-Project_again | /prog1.py | 366 | 4.15625 | 4 | l1 = eval(input('Enter a list:'))
l2 = eval(input('Enter another list:'))
intersection = []
for i in l1:
if i in l2:
intersection.append(i)
print("The intersection of the two lists is:",intersection)
union = []
for i in l1:
union.append(i)
for i in l2:
if i not in union:
union.append(i)
print("The union of the two lists is:",union)
|
e84a741192a6713014d4f5e1cf34e6d75b3261da | rolmos14/Loan_Calculator | /Problems/What day is it/main.py | 159 | 3.953125 | 4 | hour_offset = int(input())
if -12 <= hour_offset <= -11:
print("Monday")
elif -10 <= hour_offset <= 13:
print("Tuesday")
else:
print("Wednesday")
|
1b72c7c7bca2364040744b842e874ded0da04c13 | edu-athensoft/stem1401python_student | /sj200917_python2m6/day10_201119/file_4_open.py | 980 | 3.890625 | 4 | """
open a file at a specified location
error-free
mode of file opening
r for reading
w for writing
x for creating
a for appending
t in text mode
b in binary mode
rb mode for reading a binary file
rt mode for reading a text file
wt
wb
default: none (rt)
default: w (wt)
default: r (rt)
+ plus
r+ r/w
a+ w/r
w+ w/r
combination:
r+b r/w binary file
r+t r/w text file
w+b r/w binary file
"""
import os
try:
# filename = "sample/file1_open.txt"
# file = open(filename)
filepath = "sample"
filename = "file1_open.txt"
fullname = filepath+os.path.sep+filename
print(f"fullname = {fullname}")
file = open(fullname)
print("Opening sample/file1_open.txt ...")
file.close()
print("Opened.")
except FileNotFoundError as fe:
print(fe)
except IOError as ioe:
print(ioe)
except Exception as e:
print("cannot open")
print(e)
|
0fd63668918236256c1d6a3f6ef4e5efe2999bed | AllenZhangzz/learnPyhton1 | /class.py | 896 | 3.765625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'Allen'
'Class Learing'
# class Student(object):
# def __init__(self,name,age):
# self.name=name
# self.age=age
# def print_age(self):
# print self.age
# def print_name(self):
# pass
# ss=Student('SDfsdf',23)
# ss.print_age()
class Student(object):
"""docstring for Student"""
def __init__(self,name,age):
# super(Student, self).__init__()
self._name = name
self._age = age
def get_name(self):
return self._name
def get_age(self):
return self._age
def set_name(self,sttt):
# if not isinstance(sttt,str):
# raise ValueError('Name is not ......')
self._name = sttt
def set_age(self,value):
if not isinstance(value,int):
raise ValueError('Age must be an integer!')
if value <0 or value > 130:
raise ValueError('Age must between 0~130')
self._age = value
stu = Student()
stu.get_name()
stu.get_age()
|
e5f350a72462fcab1115463eb5db717db0d90a0f | Pyk017/Competetive-Programming | /HackerRank/Data_Structures/Arrays/Array-DS.py | 228 | 3.875 | 4 | """
An array is a data structure in which element or data can be stored of same data type in a contiguous block of memory.
Problem : Reversing an Array
"""
n = int(input())
ar = list(map(int, input().split()))
print(*ar[::-1])
|
3401831eec04868d25359746319abc0ffce66190 | python-the-snake/mai_informatics | /theme 8/f.py | 154 | 3.578125 | 4 | x = float(input())
y = float(input())
def IsPointInArea(x, y):
return
if IsPointInArea(x, y):
print("YES")
else:
print("NO")
|
689136e6586bebeac25a3722611bd0bd9a4af570 | jakubov/pyjkstra | /tests/queue_tests.py | 1,746 | 3.765625 | 4 | import unittest
from pyjkstra.data_structures.queue import Queue
class QueueTestCase(unittest.TestCase):
def setUp(self):
""" Init the Queue """
self.q = Queue()
def tearDown(self):
""" Empty the Queue """
self.q = []
def test_is_empty(self):
""" Test Empty Queue """
self.assertTrue(self.q.is_empty())
def test_is_not_empty(self):
""" Test Non-Empty Queue """
self.q.enqueue(1)
self.assertFalse(self.q.is_empty())
def test_size(self):
""" Test Queue Size """
self.assertEquals(self.q.size(), 0)
self.q.enqueue("One")
self.assertEquals(self.q.size(), 1)
self.q.enqueue("Two")
self.assertEquals(self.q.size(), 2)
self.q.enqueue("Three")
self.assertEquals(self.q.size(), 3)
self.q.dequeue()
self.q.dequeue()
self.assertEquals(self.q.size(), 1)
self.q.enqueue("wow")
self.assertEquals(self.q.size(), 2)
def test_enqueue(self):
""" Test Enqueue """
self.q.enqueue("One")
self.assertEquals(self.q.size(), 1)
self.assertFalse(self.q.is_empty())
self.q.enqueue("Two")
self.q.enqueue("Three")
self.assertEquals(self.q.size(), 3)
def test_dequeue(self):
""" Test Dequeue """
self.q.enqueue("One")
self.q.enqueue("Two")
self.q.enqueue("Three")
self.assertEquals(self.q.size(), 3)
self.q.dequeue()
self.assertEquals(self.q.size(), 2)
self.q.dequeue()
self.assertEquals(self.q.size(), 1)
self.q.dequeue()
self.assertEquals(self.q.size(), 0)
self.assertTrue(self.q.is_empty())
|
f7679dd84367addc37f8c3e4a9f6827df248b456 | wyounas/python_training_hq | /blog_iterator_code_samples/iterate_over_builtin_types.py | 1,071 | 3.984375 | 4 | """
Source code given in the third section of the blog article (Iterating over built-in types)
URL: http://www.pythontraininghq.com
Author: Waqas Younas <waqas@pythontraininghq.com>
"""
file_name = "somefile.txt"
some_int = 10
try:
iterator = iter(some_int) # throws exception
except TypeError as type_error:
print(type_error)
data = [1, 2, 3]
for item in data:
print(item)
iterator = iter(data)
print(iterator.__next__())
print(iterator.__next__())
print(iterator.__next__())
try:
print(iterator.__next__()) # throws exception
except StopIteration as stop_iteration:
print("Iterator ran out of items")
# Now demonstrating the concept of multiple scans supported by an iterator
list_one = [1, 2, 3]
list_two = [4, 5, 6]
zipped = zip(list_one, list_two)
for item_one, item_two in zipped:
print(item_one, item_two)
print("Iterating again")
for item_one, item_two in zipped:
print(item_one, item_two)
some_file = open(file_name)
for line in some_file:
print(line)
# Going to try to print the file content again
for line in some_file:
print(line)
|
f77aee88a2909537f8063be98bc6ec16f278a101 | codingnoye/eachday-algo | /10814.py | 192 | 3.515625 | 4 | n = int(input())
l = []
for i in range(n):
age, name = input().split()
l.append((int(age), name))
l.sort(key = lambda x:x[0])
for item in l:
print('{} {}'.format(item[0], item[1])) |
4469f2ed23e044c2c43bc4603b5b408ac6a847b1 | om-henners/advent_of_code | /2018/day13/solution_combined.py | 5,611 | 4.40625 | 4 | """
Navigating the cart maze, using a numpy array to represent a maze.
A cart with a centre square X has a value of the sum of the directions that can
be travelled as below:
1 2 4
8 X 16
32 64 128
So, according to the map the directions get numbered as follows:
- => 24
| => 66
/ => 80 or 10
\ => 72 or 18
+ => 90
Other squares will have a value as zero. To check whether a corner is at the
top or bottom of a square we check the current index in the row above
(assuming there is one) - if the value there is 66, then the corder is at the
bottom of square and gets the second value as desceibed above, otherwise it
gets the first. Note, carts can't move diagonally, so the 1, 4, 32 and 128 are
probably superfluous.
If you get a minecart, it is assigned a value as below, and a new minecart is
created at that index:
< or > => 24 (with a direction of 16 and 8 respectively)
^ or V => 66 (with a direction of 64 and 2 respectively)
Note that the direction determines which way the minecart is coming from, and
is used to determine where the cart can go from its current location.
"""
from itertools import cycle
import numpy as np
track_layout = [] # placeholder for what will be a numpy array
class MineCartCollision(Exception):
def __init__(self, moving_cart, other_cart):
self.moving_cart = moving_cart
self.other_cart = other_cart
def __str__(self):
return f'Cart {self.moving_cart} hit cart {self.other_cart}'
class Cart:
all_carts = []
movement_directions = {
2: (0, -1), # note, up is negative y
8: (-1, 0), # left is negative x
16: (1, 0),
64: (0, 1),
16 + 64 + 8: [(1, 0), (0, 1), (-1, 0)], # coming from 2
2 + 16 + 64: [(0, -1), (1, 0), (0, 1)], # coming from 8
64 + 8 + 2: [(0, 1), (-1, 0), (0, -1)], # coming from 16
8 + 2 + 16: [(-1, 0), (0, -1), (1, 0)], # coming from 64
}
new_direction = {
(0, -1): 64,
(-1, 0): 16,
(1, 0): 8,
(0, 1): 2
}
def __init__(self, x, y, direction):
self.x = x
self.y = y
self.direction = direction
self.next_turn = cycle([0, 1, 2])
self.dead = False
Cart.all_carts.append(self)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __lt__(self, other):
return (self.y, self.x) < (other.y, other.x)
def __gt__(self, other):
return (self.y, self.x) > (other.y, other.x)
def __repr__(self):
return f'<Cart {self.x} {self.y} {self.direction}>'
def tick(self):
current_location = track_layout[self.y, self.x]
try:
movement = self.movement_directions[
current_location - self.direction
]
except KeyError:
print(self)
import matplotlib.pyplot as plt
plt.imshow(
track_layout[self.y - 2: self.y + 2, self.x - 2: self.x + 2]
)
plt.show()
raise
try:
self.x += movement[0]
self.y += movement[1]
except TypeError:
turn = next(self.next_turn)
movement = movement[turn]
self.x += movement[0]
self.y += movement[1]
finally:
self.direction = self.new_direction[movement]
for cart in Cart.all_carts.copy(): # copy, so on remove don't bork iterator
if cart is self or cart.dead:
continue
if self == cart:
# remove both carts
self.dead = True
cart.dead = True
Cart.all_carts.remove(self)
Cart.all_carts.remove(cart)
raise MineCartCollision(self, cart)
track_values = {
'-': 24,
'|': 66,
'/': (80, 10),
'\\': (72, 18),
'+': 90,
'<': 24,
'>': 24,
'^': 66,
'v': 66,
' ': 0,
}
corners = {'/', '\\'}
cart_directions = {
'<': 16,
'>': 8,
'^': 64,
'v': 2
}
print("Building the minecart track")
for y, line in enumerate(open('input.txt')):
row = []
for x, location in enumerate(line.strip('\n')):
cell_value = track_values[location]
if location in corners:
try:
if track_layout[-1][x] in (66, 90): # bottom corner
cell_value = cell_value[1]
else:
cell_value = cell_value[0]
except IndexError:
cell_value = cell_value[0]
row.append(cell_value)
try:
Cart(x, y, cart_directions[location])
except KeyError:
pass
track_layout.append(row)
track_layout = np.array(track_layout)
print(f'Built track {track_layout.shape} and {len(Cart.all_carts)} mine carts')
ticks = 0 # store the number of generations
crash_happened = False
while not crash_happened:
for cart in sorted(Cart.all_carts):
if cart.dead:
continue
try:
cart.tick()
except MineCartCollision as e: # still want to finish the tick for part 2
print(e)
print(f'Solution 1: moving cart location {e.moving_cart}')
crash_happened = True
ticks += 1
while len(Cart.all_carts) > 1:
for cart in sorted(Cart.all_carts):
if cart.dead:
continue
try:
cart.tick()
except MineCartCollision as e: # make sure we get to the end of the tick
print(e)
ticks += 1
print(f'Solution 2: Remaining cart {Cart.all_carts[0]}')
|
a946a2084232627bb4f755eff398e71e65d86a29 | kmishra9/Suitcase-Class-Utility-Scripts | /homeworkChecker.py | 9,376 | 3.640625 | 4 | """
Python Script designed to output names of all students who did not complete the homework
usage: python3 homeworkChecker.py
Outputs the name of each student who missed a homework, sorted by their UGSI and the number of homework assignments missed. In addition, creates a file named (students_without_submissions) that *only* contains their emails for easy copy/paste into an email reminder and or notification.
Dependencies: use python3 -m pip install [package1] [package2] [...]
numpy
datascience
matplotlib
pandas
scipy
fuzzywuzzy
termcolor
Example: python3 -m pip install numpy datascience matplotlib pandas scipy fuzzywuzzy termcolor
Example of Homework Checking Roster File:
https://docs.google.com/spreadsheets/d/1w51h2umKCFJWbAVPUWw0HjtTaZVZ3H-qcj395t5oFZw/edit?usp=sharing
Example of Homework Submissions File:
https://docs.google.com/spreadsheets/d/1AwTrX-xcn-kTpx9yfBtdkU4McitKRSt6Ct8TSg33Xr8/edit?usp=sharing
"""
import sys
import numpy as np
import pandas as pd
import os
from termcolor import *
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
def load_data_into_frame(url):
#Doing some URL reformatting
separated = url.split(sep='/')
gid = separated[-1].split(sep='gid=')[-1]
separated[-1] = 'export?gid=' + gid + '&format=csv'
reconstructed_url = '/'.join(separated)
df = pd.read_csv(reconstructed_url)
assert df is not None, "Data did not load!"
if "Email Address" in df.columns: df["Email"] = df["Email Address"]
if "First Name" in df.columns and "Last Name" in df.columns: df["Name"] = np.core.defchararray.add(df["First Name"].values.astype(str), df["Last Name"].values.astype(str))
assert "Email" in df.columns, "The input file given did not have the correct structure -- it needs (at least) an 'Email' column but these were the columns given: " + str(df.columns.values.tolist())
cprint(".\n..\n...\nSuccess -- loading complete!\n", 'green')
return df
def find_fuzzy_matches(all_emails, submission_emails):
"""Given an array of all emails and an array of submission emails, uses fuzzy string matching to find all emails that did not submit
============Suite 1============
>>> all_emails = ['kunalmishra9@gmail.com', 'kmishra9@berkeley.edu', 'oski@berkeley.edu']
>>> submission_emails = ['kunalmishra9@gmail.com', 'kmishra9@berkeley.edu', 'oski@berkeley.edu']
>>> find_fuzzy_matches(all_emails, submission_emails)
[]
>>> submission_emails = ['kunalmishra9@gmial', 'kmishra9@berkeley.edu', 'oski@berkeley.edu']
>>> find_fuzzy_matches(all_emails, submission_emails)
[]
>>> submission_emails = ['kunalmishra9@gmial ', 'kmishra9@berkeley', 'oski@berkeley.edu ']
>>> find_fuzzy_matches(all_emails, submission_emails)
[]
============Suite 2============
>>> all_emails = ['kunalmishra9@gmail.com', 'kmishra9@berkeley.edu', 'oski@berkeley.edu']
>>> submission_emails = ['oski@berkeley.edu ']
>>> find_fuzzy_matches(all_emails, submission_emails)
['kunalmishra9@gmail.com', 'kmishra9@berkeley.edu']
>>> submission_emails = ['kmishra9@berkeley ','oski@berkeley.edu ']
>>> find_fuzzy_matches(all_emails, submission_emails)
['kunalmishra9@gmail.com']
============Suite 3============
>>> all_emails = ['kunalmishra9@gmail.com', 'kmishra9@berkeley.edu', 'oski@berkeley.edu']
>>> submission_emails = ['kunalmishra9@gmail.com', 'kmishra9@berkeley.edu', 'oski@berkeley.edu', 'rando@berkeley']
>>> find_fuzzy_matches(all_emails, submission_emails)
[]
>>> submission_emails = ['kunalmishra9@gmail.com', 'oski@berkeley.edu', 'rando@berkeley']
>>> find_fuzzy_matches(all_emails, submission_emails)
**********
Please check on kmishra9@berkeley.edu. The most similar email we found in the submissions was rando@berkeley with a similarity score of 86 out of 100.
**********
['kmishra9@berkeley.edu']
"""
# Sanitizing input email lists
submission_emails = [email for email in submission_emails if type(email) == str]
all_emails = [email for email in all_emails if type(email) == str]
submission_emails = [student_email.split('@')[0] for student_email in submission_emails]
num_students, num_submissions = len(all_emails), len(submission_emails)
matches = [ process.extract(query=student_email.split('@')[0], choices=submission_emails) + [(student_email, -1)] for student_email in all_emails ]
#Removes all perfect matches -- need to take the top X matches, where X = submissions - perfect matches
get_top_similarity_score = lambda processed_query: processed_query[0][1]
get_most_similar_email = lambda processed_query: processed_query[0][0]
get_email = lambda processed_query: processed_query[-1][0]
missing_submissions = [processed_query for processed_query in matches if get_top_similarity_score(processed_query) != 100]
num_missing_submissions = len(missing_submissions)
#False negatives -- people inputted their email incorrectly
if num_missing_submissions + num_submissions > num_students:
num_false_negatives = num_missing_submissions + num_submissions - num_students
missing_submissions = sorted( missing_submissions, key=lambda processed_query: processed_query[0][1], reverse=True )
count = 0
flagged = []
for missing_submission in missing_submissions:
if (get_top_similarity_score(missing_submission) < 80 or get_most_similar_email(missing_submission)[0] != get_email(missing_submission)[0]) and count < num_false_negatives:
cprint("**********", 'blue')
cprint("Please check on " + get_email(missing_submission) + ". The most similar email we found was suspicious", 'red' )
cprint("**********", 'blue')
print("")
flagged.append(missing_submission)
count += 1
#Getting rid of false negatives (people who were the closest fuzzy matches)
missing_submissions = missing_submissions[num_false_negatives:] + flagged
#Logical error or issue with input files
elif num_missing_submissions + num_submissions < num_students:
error_msg = "Something went wrong -- most likely, your roster is incomplete or a student submitted twice, please correct the input files\n\n"
error_msg += "Here are the students with 'missing' submissions' " + str(missing_submissions)
assert False, error_msg
missing_submissions = [get_email(processed_query) for processed_query in missing_submissions]
return missing_submissions
try:
os.system('clear')
roster_url = input("Please input the URL of the Google Sheet with the " + colored('Suitcase Class Roster', 'green') + ":\n")
roster = load_data_into_frame(roster_url)
homework_responses = []
while True:
homework_response_url = input("Please input the URL of the Google Sheet with " + colored('each Homework submission', 'green') + " you would like to grade. Press 'Enter' after each one and press '.' when you are done:\n")
if homework_response_url == "" or homework_response_url == ".":
if len(homework_responses) == 0: quit()
else: break
homework_responses.append( load_data_into_frame(homework_response_url) )
except:
os.system('clear')
error_msg = colored('Something went wrong while trying to load the data', 'red') + ' in from the URL!\n\n'
error_msg += "Make sure:\n\t1) the URL is from the " + colored("URL BAR", 'red') + " (for the sheet)"
error_msg += "\n\t2) you have clicked " + colored('Share', 'red') + " and " + colored('Get Shareable Link', 'red') + " (for the sheet)\n"
print(error_msg)
quit()
#Getting students who are on class roster but didn't submit this homework
all_student_emails = set( roster['Email'] )
all_submitted_student_emails = [set(homework_response['Email']) for homework_response in homework_responses]
students_without_submissions = [find_fuzzy_matches(all_student_emails, submitted_student_emails) for submitted_student_emails in all_submitted_student_emails]
#Figuring out the number of times each student missed a homework
missed_homeworks = dict() #Maps from student's email -> # of missed homeworks
for student_set in students_without_submissions:
for student in student_set:
if student not in missed_homeworks:
missed_homeworks[student] = 0
missed_homeworks[student] += 1
#Get all students who missed homework and sort them by their UGSI, and the number of homeworks they've missed
columns = ["Name", "Email", "UGSI"]
assert all(column in roster.columns for column in columns), "Structure of Roster File is incorrect -- need the following columns:\n\t" + str(columns)
output = roster[ roster['Email'].isin(missed_homeworks.keys()) ].reset_index()
output['Num missing'] = [ missed_homeworks[student] for student in output['Email'] ]
output = output.sort_values(by=["Num missing", "UGSI"], ascending=False)
cprint("========================================================================", 'blue')
print( output[columns+['Num missing']].head(len(output)) )
cprint("========================================================================", 'blue')
#Outputting emails into a file
path = "students_without_submissions.txt"
output.to_csv( path, columns=["Email"], index=False, header=False )
if __name__ == "__main__":
#import doctest
#doctest.testmod()
"" |
8423c822e2c16941fe38c2467aabf5fd847bc2fe | TomD0wning/DataStructuresAndAlgorithms | /Sorting.py | 2,789 | 3.71875 | 4 | #!/usr/bin/env python3
import time
aList = [1, 2, 54, 96, 31, 305, 232, 3023492, 3243, 22, 3, 12, 2345,64,23421,9862,9076523,1144,65,19,8,55,34,29,163578,789641,3984841,1000000,101010101]
def bubbleSort(aList):
start = time.time()
for x in range(len(aList)-1, 0, -1):
for i in range(x):
if aList[i] > aList[i+1]:
temp = aList[i]
aList[i] = aList[i+1]
aList[i+1] = temp
end = time.time()
return aList, end - start
print("Bubblesort ",bubbleSort(aList))
def shortBubblesort(aList):
start = time.time()
exchanges = True
x = len(aList)-1
while x > 0 and exchanges:
exchanges = False
for i in range(x):
if aList[i] > aList[i+1]:
exchanges = True
temp = aList[i]
aList[i] = aList[i+1]
aList[i+1] = temp
x = x - 1
end = time.time()
return aList, end - start
print("ShortBubblesort ",shortBubblesort(aList))
def selectionSort(aList):
start = time.time()
for x in range(len(aList)-1,0,-1):
max = 0
for element in range(1,x+1):
if aList[element]>aList[max]:
max = element
temp = aList[x]
aList[x] = aList[max]
aList[max] = temp
end = time.time()
return aList, end - start
print("SelectionSort ",selectionSort(aList))
def iterationSort(aList):
start = time.time()
for index in range(1,len(aList)):
currentValue = aList[index]
position = index
while position>0 and aList[position-1]>currentValue:
aList[position]=aList[position-1]
position = position-1
aList[position]=currentValue
end = time.time()
return aList, end-start
print("IterationSort ",iterationSort(aList))
def mergeSort(aList):
start = time.time()
# print("Splitting ", aList)
if len(aList) > 1:
mid = len(aList)//2
leftHalf = aList[:mid] #note that the python slice operator is O(k) where k is the list size
rightHalf = aList[mid:]
mergeSort(leftHalf)
mergeSort(rightHalf)
i=0
j=0
k=0
while i<len(leftHalf) and j<len(rightHalf):
if leftHalf[i]<rightHalf[j]:
aList[k]=leftHalf[i]
i=i+1
else:
aList[k]=rightHalf[j]
j=j+1
k=k+1
while i<len(leftHalf):
aList[k]=leftHalf[i]
i=i+1
k=k+1
while j<len(rightHalf):
aList[k]=rightHalf[j]
j=j+1
k=k+1
# print("Merging ", aList)
end = time.time()
return aList, end-start
print("MergeSort ", mergeSort(aList))
|
b50d86677d4f84808863cb70f3892a95dd872ecb | DedaLenya/python_baisik_31.10.2020 | /les1_31.10.20/HomeWork_les1_31.10.20/task3_1.py | 299 | 3.796875 | 4 | # 3. Узнайте у пользователя число n. Найдите сумму чисел
# n + nn + nnn. Например, пользователь ввёл число 3.
# Считаем 3 + 33 + 333 = 369
n = str(input('input number >>'))
a = f"{int(n) + int(n*2) + int(n*3)}"
print(a)
|
ce7eb09e8859142a7b6dfd1371027e28ea253fb1 | Wwwangi/LeetCode-Competition | /Wangi/448.py | 1,211 | 3.59375 | 4 | #可运行
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
if(nums==[]):
return []
n=len(nums)
temp=set([n for n in range(1,n+1)])
nums=sorted(set(nums))
result=temp.difference(nums)
return result
#using hash table
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
hashtable=dict.fromkeys([n for n in range(1,len(nums)+1)], 0)
for i in range(len(nums)):
hashtable[nums[i]]=1
return [k for k, v in hashtable.items() if v == 0]
#还有点问题
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
if(nums==[]):
return []
n=len(nums)
nums.sort()
print(nums)
result=[]
pointer=1
for i in range(n):
if(nums[i]>pointer):
result.append(pointer)
pointer+=1
elif(nums[i]==pointer):
pointer+=1
if(nums[-1]<=pointer):
for i in range(nums[-1]+1,n+1):
result.append(i)
return result |
32ca96a91a77166afca3a22c613d40562ed0f65e | BryanBumgardner/dsp | /python/advanced_python_csv.py | 660 | 3.828125 | 4 | import pandas as pd
from pandas import DataFrame, read_csv
#where is your file? here!
path = '/Users/bryanbumgardner/anaconda/faculty.csv'
#convert into pandas dataframe, and be picky about your column names.
df = pd.read_csv(path, header=0)
df.columns = ['Name', 'Degree', 'Title', 'Email']
#you must create variables, right?
title = [x for x in df['Title']]
#because some people have multiple degrees you have to break this one up. It splits with spaces between the degrees.
degrees =[x.split(" ") for x in df['Degree']]
email = [x for x in df['Email']]
new_df = pd.DataFrame(email, columns=['Email'])
new_df.to_csv("profemails.csv")
#thanks pandas, ily
|
e4a18819c3a3003bf0ada3a51e3cea0871f7da8e | Hardik-Sihmar/string-functions | /stringfunctions.py | 406 | 4.53125 | 5 |
# Some functions of Strings
hello = "my name is Hardik"
standard = "I am in eleventh standard."
print(hello + standard)
# 1. Len
print(len(hello))
# 2. endswith
print(hello.endswith('Hardik'))
# 3. capitalize
print(hello.capitalize())
# 4. count
print(hello.count('a'))
# 5. replace
print(hello.replace('name', 'hardik'))
# 6. find
print(hello.find('hardik'))
|
7b554d3d1a784aa74818f63e0594b1eec75a3c8d | mengyangbai/leetcode | /tree/recoverbinarysearchtree.py | 628 | 3.609375 | 4 |
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def recoverTree(self, root):
swap = [None, None]
self.prev = TreeNode(float('-inf'))
def dfs(node):
if node:
dfs(node.left)
if node.val < self.prev.val:
if not swap[0]: swap[0] = self.prev
swap[1] = node
self.prev = node
dfs(node.right)
dfs(root)
swap[0].val, swap[1].val = swap[1].val, swap[0].val |
c5db5acabf371ba9a991a5f0156e65c1b0c286c8 | krishnaqa64/Pythonlearning | /pandas cleaningData.py | 882 | 3.671875 | 4 |
import pandas as pd
import numpy as np
people = {
'first': ['Corey', 'Jane', 'John', 'Chris', np.nan, None, 'NA'],
'last': ['Schafer', 'Doe', 'Doe', 'Schafer', np.nan, np.nan, 'Missing'],
'email': ['CoreyMSchafer@gmail.com', 'JaneDoe@email.com', 'JohnDoe@email.com', None, np.nan, 'Anonymous@email.com', 'NA'],
'age': ['33', '55', '63', '36', None, None, 'Missing']
}
df = pd.DataFrame(people,index=[1,2,3,4,5,6,7])
df.replace('NA', np.nan, inplace=True)
df.replace('Missing', np.nan, inplace=True)
print(df)
print("\n")
print(df.dropna())
print("\n")
#print(df.dropna(axis="index",how='any')) # default arguments :- axis="index",how='any'
print(df.dropna(axis="index",how='any'))
print(df.dropna(axis="index",how='all'))
print("\n")
print(df.dropna(axis="columns",how='all'))
print(df.dropna(axis="columns",how='any'))
print("\n")
print(df.dropna(axis="index",how='any',subset=['email']))
print(df.isna()) |
ec92f238fa0c3658c8e8a71fd60fd0d4bdd6cf3f | beber89/pcap-instructor-samples | /recursion example.py | 208 | 3.703125 | 4 | def mydigit(p):
s = 0
for x in p:
s += int(x)
if s < 10:
return s
else:
return mydigit(str(s))
user_input = input("birthday \n")
print(mydigit(user_input))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.