blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
88cb4acb21c5ec419f4abb6dd0ff34f01ed49fb4 | VolodymyrKLymenko/PythonStudy | /files.py | 159 | 3.671875 | 4 | f = open ('text.txt') # params of file https://itproger.com/course/python/14
print (f.read (1))
for line in f:
print (line)
f.write ('Hi it')
f.close () |
c4a2e6bb9efdbf30c6feec351297b57f56fc7d77 | BAF95/Pyhon-Challenge | /pybank/main.py | 2,269 | 3.828125 | 4 | import os
import csv
# sets source data path
filepath = "resources/budget_data.csv"
# sets output path(used at end of script)
output_path = os.path.join("..", "pybank", "analysis", "pybank.csv")
with open(filepath) as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
print(csvreader)
# read the header row first (skip this step if there is now header)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
# set count for total months
total = 0
# set value for total profits
total_profits = 0
# sets min/max value to be compared as rows are iterated
max_val = 0
min_val = 0
for row in csvreader:
# total months calculation
count = 0
count =+ 1
total = total + count
# converts profit/loss to integer for later use
monthly_value = int(row[1])
# calculates total profit
total_profits = total_profits + monthly_value
# determines max value in set by profit and stores variable
if max_val < int(row[1]):
max_val = int(row[1])
max_out = row
# determines min value in set by profit and stores variable
if min_val > int(row[1]):
min_val = int(row[1])
min_out = row
# adds up total profits
# calculates average via net profit / total months
average = total_profits / total
# prints result to terminal
print(f"Data output: Total Months:{total} ")
print(f"Net Profit:{total_profits} ")
print(f"Average Profit:{average}")
print(f"Most Profitable Month{max_out} ")
print(f"Most Value Lost by Month: {min_out}")
# begins writing process
with open(output_path, 'w', newline='') as csvfile:
# Initialize csv.writer
csvwriter = csv.writer(csvfile, delimiter=',')
# Write the first row (column headers)
csvwriter.writerow(['Total Months', 'Net Profit', 'Average Profit', 'Best Month', 'Best Month Profit', 'Worst Month', 'Worst Month Profit'])
# Write the second row(reference variables above)
csvwriter.writerow([total, total_profits, average, max_out[0], max_out[1], min_out[0], min_out[1]])
|
3f0811b777d413f3dd4dd3895eb59afda2588b67 | Mnguyener/computer-guess-project | /main.py | 780 | 3.921875 | 4 | from random import randint
def main():
def comp_guess():
low = 1
high = 10
user_num = int(input("Provide a number.\n"))
comp_num = randint(low, high)
print(comp_num)
while True:
if comp_num > user_num:
print("Too high.")
high = comp_num - 1
comp_num = randint(low, high)
print(comp_num)
continue
if comp_num < user_num:
print("Too low.")
low = comp_num + 1
comp_num = randint(low, high)
print(comp_num)
continue
else:
print("Correct")
break
comp_guess()
if __name__ == '__main__':
main() |
e9fe0a3fc9b9e66e0ae1e15610d83a690291be21 | bscott110/mthree_Pythonpractice | /BlakeScott_Mod2_activities.py | 1,105 | 3.765625 | 4 | #Blake Scott 08/05/2021
#Activity 1 thru 4
name = input("0.What is your name?")
age = input("1.How old are you?")
bd = input("2.What is your birthdate?")
live = input("3.Where do you live?")
occ = input("4.Whats your occupation?")
ulist0 = [name, age, bd, live, occ]
print(ulist0)
color = input("5.Fav color?")
song = input("6.Fav song?")
ulist0.append(color)
ulist0.append(song)
print(ulist0)
p = int(input("Enter the number of the question that you'd like to delete."))
ulist0.pop(p)
print(ulist0)
p1 = int(input("Enter the index of the question that you'd like to update."))
update = input("Enter your new value.")
ulist0[p1] = update
print(ulist0)
#Activity 5
flname = tuple(input("First and Last name?"))
prof = tuple(input("Current Profession?"))
cadd = tuple(input("Current address?"))
padd = tuple(input("Previous address?"))
t0 = tuple(flname+prof+cadd+padd)
print(t0)
#Activity 7
ulist1 = ["this", "is", "a", "test", "list", "1", "", "hi"]
ulist2 = []
for x in ulist1:
if len(x) >= 2:
ulist2.append(x)
print(ulist1)
print(ulist2)
|
3a2b891d25644a0134a4a16e2435aecaf5aabe66 | Ramonsoe/heuristiek | /code/classes/standardobjects/cables.py | 2,251 | 4.03125 | 4 | """
cables.py
Layla Hoogeveen, Leon Brakkee and Ramon Soesan
File in which cable objects are created and a list of cables is filled.
"""
from .cable import Cable
class Cables():
"""Create different lists of cable coordinates from house to battery"""
def __init__(self, house, battery):
self.x1 = house.x
self.y1 = house.y
self.x2 = battery.x
self.y2 = battery.y
self.cable_list = []
self.cable_x = []
self.cable_y = []
# automatically start the process of placing cables
self.place_cables(house)
def distance(self):
"""Return Manhattan distance of two coordinates"""
distance = abs(self.x1 - self.x2) + abs(self.y1 - self.y2)
return distance
def add_cable_coords(self, X, Y):
"""Append cable x and y coordinates to seperate lists"""
self.cable_x.append(X)
self.cable_y.append(Y)
def get_all_coordinates(self):
"""Append the x and y coordinates in separated lists for visualisation purposes"""
Xi, Yi = self.x1, self.y1
Xf, Yf = self.x2, self.y2
self.add_cable_coords(Xi, Yi)
for i in range(self.distance()):
if Xi < Xf:
Xi += 1
self.add_cable_coords(Xi, Yi)
continue
elif Xi > Xf:
Xi -= 1
self.add_cable_coords(Xi, Yi)
continue
if Yi < Yf:
Yi += 1
self.add_cable_coords(Xi, Yi)
continue
elif Yi > Yf:
Yi -= 1
self.add_cable_coords(Xi, Yi)
return self.cable_x, self.cable_y
def make_cable_list(self, list_x, list_y):
"""Put all x and y coordinates into one list"""
for i in range(len(self.cable_x)):
cable_points = [self.cable_x[i], self.cable_y[i]]
self.cable_list.append(cable_points)
return self.cable_list
def place_cables(self, house):
"""Add all cables to house"""
X_segments, Y_segments = self.get_all_coordinates()
house_to_battery_cable = self.make_cable_list(X_segments, Y_segments)
house.add_cable(house_to_battery_cable)
|
e3564a8ea0620dd38514cfad406e44d508e01ae8 | serovvitaly/project01 | /neuronet/neuron.py | 2,253 | 3.859375 | 4 | from math import exp
class Relation:
"""Связь между нейронами"""
def __init__(self, neuron, weight):
self.neuron = neuron
self.weight = weight
def get_calculated_value(self):
val = self.neuron.get_output_value()
return val * self.weight
class Input:
"""Заглушка для входного слоя"""
def __init__(self):
self.output_value = 0
def set_output_value(self, output_value):
self.output_value = output_value
def get_output_value(self):
return self.output_value
class Neuron:
def __init__(self, name=None):
self.name = name
self.output_value = None
self.relations = []
pass
def set_output_value(self, val):
"""Устанавливает выходное значение"""
self.output_value = val
def get_output_value(self, recalculate=True):
"""
Возвращает выходное значение, если установлен recalculate,
то предварительно пересчитывает выходное значение
"""
if self.output_value is None or recalculate is True:
self.calculate_output_value()
return self.output_value
def calculate_output_value(self):
"""Расчитывает выходное значение"""
output_value = 0
for relation in self.relations:
output_value += relation.get_calculated_value()
output_value = self.calculate_transfer_function(output_value)
self.set_output_value(output_value)
def add_relation(self, neuron, weight=0.5):
"""Добавление связи с нейроном"""
self.relations.append(Relation(neuron, weight))
def calculate_transfer_function(self, value):
"""Вычисление передаточной функции"""
v = 1 / value
return int(value >= 0.5)
def train(self, data_set, weight_set):
"""Функция тренировки нейрона"""
# print(data_set)
# print(weight_set)
return 2
|
ef7bae8c45fca188a3d166a4f4d9a11d881eea4a | OldSkyTree/ExpressionParser | /expression_parser.py | 2,502 | 3.859375 | 4 | import operator
import re
import argparse
operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "^": operator.pow}
operators_priority = {"+": 0, "-": 0, "*": 1, "/": 1, "^": 2}
def main():
parser = create_parser()
namespace = parser.parse_args()
if namespace.file:
with open(namespace.file, "r") as file:
exp = file.readline()
elif namespace.expression:
exp = namespace.expression
else:
exp = input("Enter expression: ")
rev_polish_note = reverse_polish_notation(exp)
print("Answer: ", execute(rev_polish_note))
def create_parser():
parser = argparse.ArgumentParser()
parser.add_argument("expression", nargs="?")
parser.add_argument('-f', "--file")
return parser
def check_expression(expression):
input_string = str(expression)
input_string.replace(" ", "")
if "," in input_string:
raise ValueError()
def execute(reverse_polish):
stack = []
for lexeme in reverse_polish:
if is_number(lexeme):
stack.append(lexeme)
else:
stack.append(operators[lexeme](float(stack.pop(-2)), float(stack.pop())))
return stack.pop()
def reverse_polish_notation(expression):
lexemes = get_lexemes(expression)
output = []
stack = []
for lexeme in lexemes:
if is_number(lexeme):
output.append(lexeme)
elif lexeme == "(":
stack.append(lexeme)
elif lexeme == ")":
current_lexeme = stack.pop()
while current_lexeme != "(":
output.append(current_lexeme)
current_lexeme = stack.pop()
elif lexeme in operators_priority:
while stack and stack[-1] in operators_priority and \
operators_priority[stack[-1]] >= operators_priority[lexeme]:
output.append(stack.pop())
stack.append(lexeme)
while stack:
output.append(stack.pop())
return output
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def get_lexemes(expression):
lexemes = []
i = 0
while i < len(expression):
number = re.match(r"[0-9]+\.*[0-9]+", expression[i:])
if number:
lexemes.append(number.group())
i += number.end() - 1
else:
lexemes.append(expression[i])
i += 1
return lexemes
if __name__ == "__main__":
main()
|
1e9e535aeb542810c9489cd9bee9a2b77bf87ddd | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/knnsad001/question3.py | 327 | 4.25 | 4 | import math
denominator = math.sqrt(2)
a=2
y=2
while denominator<2:
x = a/denominator
y= x*y
denominator = math.sqrt(2 + denominator)
b = round(y,3)
print("Approximation of pi:",b)
r = eval(input("Enter the radius:\n"))
area = float(y*(r**2))
c = round(area, 3)
print("Area:",c)
|
4b64aab5133961c910c7c4efef740159bb3d2dd4 | avengerryan/daily_practice_codes | /five_sept/programiz/eighteen.py | 649 | 4.65625 | 5 |
# check whether a string is palindrome or not
# A palindrome is a string that is the same read forward or backward
# example: 'dad' is the same in forward or reverse direction.
# e.g. 'aibohphobia' - meaning irritable fear of palindrome
# checking if a string is palindrome or not
# my_str = 'aIbohPhoBiA'
my_str = 'RajeshAWankhade'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print('the string is a palindrome.')
else:
print('the string is not a palindrome.')
|
ee7dd7f2c30f846c772f1ddc3ae4a095542690ce | JemmyH/model_text | /design_pattern_test/factory_pattern.py | 966 | 3.78125 | 4 | # _*_ coding:utf-8_*_
from abc import ABCMeta, abstractmethod
class Pay(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
class AliPay(Pay):
def pay(self, money):
print("使用支付宝支付{}元".format(money))
class Wechat(Pay):
def pay(self, money):
print("使用微信支付{}元".format(money))
class FactoryPattern(metaclass=ABCMeta):
@abstractmethod
def use_payment(self):
pass
class AlipayFactory(FactoryPattern):
def use_payment(self):
return AliPay()
class WechatFactory(FactoryPattern):
def use_payment(self):
return Wechat()
# 如果要新增支付方式
class ApplePay(Pay):
def pay(self, money):
print("使用苹果支付{}元".format(money))
class AppleFactory(FactoryPattern):
def use_payment(self):
return ApplePay()
if __name__ == '__main__':
af = AlipayFactory()
ali = af.use_payment()
ali.pay(120)
|
6c96d1eb30c9df3f0b8edef90464b5fea4ff7c32 | xiaoerlaigeid/Udacity_P4_Smartcab | /smartcab/agent.py | 4,609 | 3.59375 | 4 | import random
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
class LearningAgent(Agent):
"""An agent that learns to drive in the smartcab world."""
def __init__(self, env):
super(LearningAgent, self).__init__(env) # sets self.env = env, state = None, next_waypoint = None, and a default color
self.color = 'red' # override color
self.planner = RoutePlanner(self.env, self) # simple route planner to get next_waypoint
# TODO: Initialize any additional variables here
self.epslion = 0.8
self.alpha = 0.8
self.gamma = 0.2
self.q = {}
self.action_counts = 0.
self.fall_count = 0.
def getQ(self, state, action):
return self.q.get((state, action), 0.0)
def reset(self, destination=None):
self.planner.route_to(destination)
# TODO: Prepare for a new trip; reset any variables here, if required
self.epslion = self.epslion * 0.9
self.alpha = self.alpha * 0.95
def update(self, t):
# Gather inputs
self.next_waypoint = self.planner.next_waypoint() # from route planner, also displayed by simulator
inputs = self.env.sense(self)
deadline = self.env.get_deadline(self)
# TODO: Update state
#question2 :Inform the Driving Agent
self.state = (inputs['light'],
inputs['oncoming'],
inputs['left'],
inputs['right'],
self.next_waypoint)
#,deadline)
# TODO: Select action according to your policy
#Implement a Basic Driving Agent
#action = random.choice(self.env.valid_actions)
#question3 :Implement a Q-Learning Driving Agent
if random.random() < self.epslion :
action = random.choice(self.env.valid_actions)
else :
q = [self.getQ(self.state, a) for a in self.env.valid_actions]
maxQ = max(q)
count = q.count(maxQ)
if count > 1:
best = [i for i in range(len(self.env.valid_actions)) if q[i] == maxQ]
i = random.choice(best)
else:
i = q.index(maxQ)
action = self.env.valid_actions[i]
# Execute action and get reward
reward = self.env.act(self, action)
self.action_counts += 1
if reward < 0:
self.fall_count += 1
print "The action counts is {} and the fall is {}".format(self.action_counts,self.fall_count)
# TODO: Learn policy based on state, action, reward
#get the next state
new_inputs = self.env.sense(self)
new_state = ( new_inputs['light'],
new_inputs['oncoming'],
new_inputs['left'],
new_inputs['right'],
self.next_waypoint)
#print "The old state is {}".format(self.state)
#print "The new state is {}".format(new_state)
maxqnew = max([self.getQ(new_state, a) for a in self.env.valid_actions])
oldv = self.q.get((self.state, action), None)
if oldv is None:
self.q[(self.state, action)] = reward
else:
self.q[(self.state, action)] = oldv + self.alpha * (reward + self.gamma * maxqnew - oldv)
#print "LearningAgent.update(): deadline = {}, inputs = {}, action = {}, reward = {}".format(deadline, inputs, action, reward) # [debug]
def run():
"""Run the agent for a finite number of trials."""
# Set up environment and agent
e = Environment() # create environment (also adds some dummy traffic)
a = e.create_agent(LearningAgent) # create agent
e.set_primary_agent(a, enforce_deadline=True) # specify agent to track
# NOTE: You can set enforce_deadline=False while debugging to allow longer trials
# Now simulate it
sim = Simulator(e, update_delay=1, display= True) # create simulator (uses pygame when display=True, if available)
# NOTE: To speed up simulation, reduce update_delay and/or set display=False
sim.run(n_trials=100) # run for a specified number of trials
#print "action_times = {}, action_fall = {}".format(action_times, action_fall)
# NOTE: To quit midway, press Esc or close pygame window, or hit Ctrl+C on the command-line
if __name__ == '__main__':
run()
|
817bcd761b6126c54721f8b4ecb4e478a332fc73 | Sabareeswaran123/vci | /codekata5.py | 216 | 3.734375 | 4 | k=input()
v=['a','e','i','o','u','A','E','I','O','U']
if (ord(k)>64 and ord(k)<91) or (ord(k)>96 and ord(k)<123):
if k in v:
print("Vowel")
else:
print("Consonant")
else:
print("Invalid")
|
8700f02350908070515610af8c15abac907f087d | saazcona/Python_2020 | /Clase_d5-2020-09-26_Interfaz_Grafica_Usuario/programa_grafico.py | 1,165 | 3.890625 | 4 | # Importar tkinter
from tkinter import *
# from tkinter.ttk import *
# Creamos un objeto del tipo Tk
ventana = Tk()
# Agregar un marco
marco1 = Frame(ventana, bg = "black")
marco1.pack(side = "top")
marco2 = Frame(ventana)
marco2.pack(side = "bottom")
# Agregar un Widget del tipo label
label1 = Label(marco1, text = 'Hola Mundo', font = ("Arial Bold", 20), fg = "blue")
label1.pack()
label2 = Label(marco2, text = 'Quiero azotar a María', font = ("Arial", 15), fg = "#545454")
label2.pack()
### Se agrega un botón
# Esto es un callback
nombre = StringVar()
textbox = Entry(ventana, textvariable = nombre)
textbox.pack()
labelnom = Label(ventana, text = "", textvariable = nombre)
labelnom.pack()
def boton_click(fulano):
label1.configure(text = f"{fulano} Haz hecho Click en el puto botón")
nombre.set(fulano)
boton = Button(ventana, text = "Bottom_text", bg = "red", fg = "white", command = lambda: boton_click("El Manin"))
boton.pack()
# Se establece el tamaño de la ventana
ventana.geometry("600x400") # Dimension de la ventana
# Se establece el mainloop para que la ventana queda abierta hasta que el usuario quiera
ventana.mainloop()
|
b239e9d7bba3838af9f705d715ddb287e3f22c9b | Zhenye-Na/leetcode | /python/399.evaluate-division.py | 3,051 | 3.734375 | 4 | #
# @lc app=leetcode id=399 lang=python3
#
# [399] Evaluate Division
#
# https://leetcode.com/problems/evaluate-division/description/
#
# algorithms
# Medium (48.60%)
# Likes: 1814
# Dislikes: 140
# Total Accepted: 108.1K
# Total Submissions: 216.8K
# Testcase Example: '[["a","b"],["b","c"]]\n[2.0,3.0]\n[["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]'
#
# Equations are given in the format A / B = k, where A and B are variables
# represented as strings, and k is a real number (floating point number). Given
# some queries, return the answers. If the answer does not exist, return -1.0.
#
# Example:
# Given a / b = 2.0, b / c = 3.0.
# queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
# return [6.0, 0.5, -1.0, 1.0, -1.0 ].
#
# The input is: vector<pair<string, string>> equations, vector<double>&
# values, vector<pair<string, string>> queries , where equations.size() ==
# values.size(), and the values are positive. This represents the equations.
# Return vector<double>.
#
# According to the example above:
#
#
# equations = [ ["a", "b"], ["b", "c"] ],
# values = [2.0, 3.0],
# queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]
# ].
#
#
#
# The input is always valid. You may assume that evaluating the queries will
# result in no division by zero and there is no contradiction.
#
#
# @lc code=start
class UnionFind:
def __init__(self):
self.parents = {}
def find(self, a):
while a != self.parents[a][0]:
root = self.find(self.parents[a][0])
self.parents[a][0] = root[0]
self.parents[a][1] * root[1]
return self.parents[a]
def union(self, a, b, multiplier):
if a not in self.parents and b not in self.parents:
self.parents[a] = [b, multiplier]
self.parents[b] = [b, 1.0]
elif a not in self.parents:
self.parents[a] = [b, multiplier]
elif b not in self.parents:
self.parents[b] = [a, 1 / multiplier]
else:
# a and b both in self.parents
root_a, root_b = self.find(a), self.find(b)
if root_a[0] != root_b[0]:
root_a[0] = root_b[0]
root_a[1] *= (root_b[1] * multiplier)
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
print("hello?")
solver = UnionFind()
print(solver)
for i in range(len(equations)):
a = equations[i][0]
b = equations[i][1]
multiplier = values[i]
print(a, b, multiplier)
# a = b * multiplier
solver.union(a, b, multiplier)
print(a, b, multiplier)
results = []
for a, b in queries:
ra = solver.find(a)
rb = solver.find(b)
result = -1.0
if ra[0] == rb[0]:
result = (ra[1] / rb[1])
results.append(result)
return results
# @lc code=end
|
c05607a826e9524835fbf0c84bf7f26b2a4d7c46 | giuice/DataSciencePath | /rascunho.py | 2,781 | 3.703125 | 4 | # %%
def set_goals(board):
flat = sum(board, [])
return [flat[0:3],flat[3:6],flat[6:9],flat[0:9:3],flat[1:9:3],flat[2:9:3],flat[0:9:4],flat[2:7:2]]
def draw(posicoes):
print("---------")
print("| " + " ".join(posicoes[0]) + " |")
print("| " + " ".join(posicoes[1]) + " |")
print("| " + " ".join(posicoes[2]) + " |")
print("---------")
def fill_grid(arr, entrada):
ii = 0
for i in range(3):
arr[i][0] = entrada[ii]
arr[i][1] = entrada[ii+1]
arr[i][2] = entrada[ii+2]
ii += 3
def enter_cells():
ent = input("Enter cells:").replace('_',' ')
l = abs(9 - len(ent))
if l > 0:
ent += (l*" ")
return ent
def winner(goals):
winners = []
for i in goals:
if i == ['X','X','X'] or i == ['O','O','O']:
winners.append(i)
if len(winners) >= 2:
print('Impossible')
return True
elif len(winners) == 0:
if " " in goals: print('Game not finished')
else:
print('Draw')
return True
else:
print(winners[0][0], 'wins')
return True
def read_player(board):
while True:
try:
num = [int(x)-1 for x in input('Enter the coordinates:').split()]
if min(num) >= 0 and max(num) <= 2:
dim = board[num[0]][num[1]]
if dim != " ":
print('This cell is occupied! Choose another one!')
else:
board[num[0]][num[1]] = 'X'
goals = set_goals(board)
draw(board)
if winner(goals): break
else:
print("Coordinates should be from 1 to 3!")
except ValueError:
print("You should enter numbers!")
# %%
board = [[' ', ' ', ' '] for _ in range(3)]
entrada = enter_cells()
fill_grid(board,entrada)
draw(board)
read_player(board)
# %%
import random
n = int(input())
random.seed(n)
print(random.choice("Voldemort"))
# %%
n = int(input())
random.seed(n)
print(random.uniform(0,1))
# %%
random.seed(3)
# call the function here
print(random.betavariate(.9, .1))
# %%
Class House():
construction = "building"
elevator = True
# object of the class House
new_house = House()
# %%
str1 = 'AB'
str2 = '34'
[x + y for y in str1 for x in str2]
# %%
superhero_list = ['thor', 'hulk']
def to_upper(x):
for i in x:
yield i.upper()
print(to_upper(superhero_list))
# %%
x = [2, 4, 1, 5]
squares = {y : y*y for y in sorted(x)}
print(squares)
# %%
teams = [['barry', 'cisco', 'caitlin'],
['oliver', 'john', 'felicity']]
[member[-1] for member in teams]
# %%
int_list = [-2, 4, 1, 6, -3]
print(x for x in int_list if x > 0)
# %%
|
8a42cece0f245c091f174637d73af822080008c2 | vladGriguta/leetcode | /JulyChallenge/10July20.py | 2,494 | 3.90625 | 4 |
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
class Solution:
def flatten(self, head: 'Node') -> 'Node':
# Strategy:
# 1. Iterate through an infinite loop
# 2. If find a child to the current node, store the node and go to it's child
# 3. Else if find the next element, go to that element
# 4. Else if list of stored nodes connected by child is not null, get the last item in the list
# and check if it has a next element.
# If it does, go to that element.
# If it does not, delete element from the list and go to 4
# initialize new list
if head:
if head.child:
new_list = Node(head.val,None,head.child,None)
elif head.next:
new_list = Node(head.val,None,head.next,None)
else:
return head
else:
return head
res = []
node_child_list = []
while True:
res.append(head.val)
if head.child:
node_child_list.append(head)
print('child ',head.val)
head = head.child
new_list.next = Node(head.val,None,None,None)
new_list.next.prev = new_list
new_list = new_list.next
elif head.next:
print('next ',head.val)
head = head.next
new_list.next = Node(head.val,None,None,None)
new_list.next.prev = new_list
new_list = new_list.next
elif node_child_list:
print('prev node ',head.val)
if node_child_list[-1].next:
head = node_child_list[-1].next
new_list.next = Node(head.val,None,None,None)
new_list.next.prev = new_list
new_list = new_list.next
del node_child_list[-1]
else:
break
print('gets here')
print(res)
while new_list.prev:
new_list = new_list.prev
return new_list
test1 = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
|
bbd1a3dea939d3badeb871462da9b0086f69376f | RahulKB31/ShapeAI-Data-Science-Complete | /Day_4_Scripting/input_number.py | 75 | 3.90625 | 4 | # int as input .
num = int(input("Enter an integer"))
print("hello" * num)
|
3a9dd23710cbcfee415c0d33a3cdfe759cf3c5bb | mattjp/leetcode | /practice/medium/0573-Squirrel_Simulation.py | 2,450 | 3.546875 | 4 | class Solution:
def minDistance(self, height: int, width: int, tree: List[int], squirrel: List[int], nuts: List[List[int]]) -> int:
"""
1. have squirrel go to closest nut
squirrel should go to a nut that is closer to the squirrel than the tree
2. have squerrel go to tree
3. repeat until no more nuts
"""
# for each nut, calculate dist to tree, dist to squirrel
# if squirrel-nut dist < tree-nut dist, save this as the optimal nut
def optimal_nut(t, s, nuts):
dist = row = col = None
for nut_row, nut_col in nuts:
squirrel_dist = abs(nut_row - s[0]) + abs(nut_col - s[1])
tree_dist = abs(nut_row - t[0]) + abs(nut_col - t[1])
if squirrel_dist <= tree_dist or not dist:
if dist:
if tree_dist - squirrel_dist > dist:
dist = tree_dist - squirrel_dist
row = nut_row
col = nut_col
else:
dist = tree_dist - squirrel_dist
row = nut_row
col = nut_col
return row, col
# this is dumb and could just be sorting (same time complexity)
def closest_nuts(row, col, nuts):
result = []
for nut_row, nut_col in nuts:
dist = abs(row - nut_row) + abs(col - nut_col)
result.append((dist, nut_row, nut_col))
heapq.heapify(result) # O(n)
return result
total_dist = 0
# 1. have squirrel go to closest nut
opt_nut_row, opt_nut_col = optimal_nut(tree, squirrel, nuts)
opt_nut_dist = abs(opt_nut_row - squirrel[0]) + abs(opt_nut_col - squirrel[1])
total_dist += opt_nut_dist
# 2. have squirrel go to tree
tree_dist = abs(opt_nut_row - tree[0]) + abs(opt_nut_col - tree[1])
total_dist += tree_dist
# 3. collect all nuts
remaining_nuts = closest_nuts(tree[0], tree[1], nuts)
while remaining_nuts:
dist, row, col = heapq.heappop(remaining_nuts)
if (row, col) == (opt_nut_row, opt_nut_col):
continue
total_dist += dist * 2
return total_dist
|
c8280b14baa36cc39bebf4bca8c72befa693a0d2 | pradg73/assign | /calc.py | 1,838 | 3.5 | 4 | #!/usr/bin/python
import sys
class Val(object):
val = None
def __init__(self, _val):
self.val = int(_val)
def eval(self):
return self.val
@staticmethod
def is_number(s):
try:
int(s)
return True
except ValueError:
pass
class Op(object):
op = None
# operator -> calculation , priority
oper = {
'*' : [lambda x,y : Val(x*y), 2],
'+' : [lambda x,y : Val(x+y),1],
'-' : [lambda x,y : Val(x-y),1],
'/' : [lambda x,y : Val(x/y),3],
}
def __init__(self, _op):
self.op = _op
# precedence
def isGreater(self, rhs):
return Op.oper[self.op][1] > Op.oper[rhs.op][1]
def eval(self, rhs, lhs):
print "eval op ",self.op
return Op.oper[self.op][0](rhs.eval(), lhs.eval())
class Expr(object):
@staticmethod
def eval(exprs):
print "eval ", exprs
lastLowestOp = None
lastLowestOpLocation = -1
if len(exprs) == 1:
token = exprs[0]
assert(Val.is_number(token))
return Val(token)
for i,token in enumerate(exprs):
print "token ",token
if token in Op.oper.keys():
op = Op(token)
if lastLowestOp is None:
lastLowestOp = op
lastLowestOpLocation = i
elif lastLowestOp.isGreater(op): # op < lastLowestOp
lastLowestOp = op
lastLowestOpLocation = i
assert(lastLowestOpLocation != -1)
lhs = Expr.eval(exprs[:lastLowestOpLocation])
rhs = Expr.eval(exprs[lastLowestOpLocation+1:])
return lastLowestOp.eval(lhs, rhs)
if __name__ == "__main__":
exprs = sys.argv[1];
print Expr.eval(exprs).eval()
|
bd911a444b8a842b6c415934a21b7a347bac88b9 | coldmax88/PyGUI | /Tests/15-dialog.py | 1,085 | 4.03125 | 4 | from GUI import Dialog, Label, Button, application
from GUI.StdButtons import DefaultButton, CancelButton
from testing import say
class TestDialog(Dialog):
def ok(self):
say("OK")
def cancel(self):
say("Cancel")
dlog = TestDialog(width = 250)
lbl = Label(text = "Eject the tomato?")
ok_btn = DefaultButton()
cancel_btn = CancelButton()
dlog.place(lbl, left = 20, top = 20)
dlog.place(ok_btn, left = 20, top = lbl + 20)
dlog.place(cancel_btn, right = -20, top = lbl + 20)
dlog.height = ok_btn.bounds[3] + 20
dlog.show()
instructions = """
There should be a non-modal dialog with two buttons in 'default' and
'cancel' styles. The window should be movable but not resizable.
Messages should be printed when the buttons are pressed (although they
should not dismiss the dialog). Return and Enter should activate the
OK button, and Escape should activate the Cancel button.
On platforms without an application-wide menu bar, the window should
not have a menu bar, but the keyboard equivalent of the Quit command
should still work.
"""
say(instructions)
application().run()
|
348bb0fe7911ae2e207bd6554d0f42880c3ccf6d | joscor34/ArduPy | /ArduPy.py | 4,416 | 3.59375 | 4 | import os
import time
import sys
if sys.version_info.major < 3:
print("ArduPy solo esta soportado para python3.")
exit(0)
vx = 1
wl = 1
wh = 1
oh = 1
piness = []
varles = []
while oh == 1:
nombre = str(input("Como se va a llamar tu programa: "))
f = open("{}.ino".format(nombre), 'w')
variables = int(input("Cuantas variables deseas generar?(escriba '0' si no desea generar ninguna): "))
for var in range (variables):
print("""
1)byte
2)int
3)bool
4)char(ingresar el valor entre comillas)
5)String(ingresar el valor entre comillas)
6)float
""")
dato = int(input("Ingrese el tipo de variable: "))
if dato == 1:
dat = "byte"
if dato == 2:
dat = "int"
if dato == 3:
dat = "bool"
if dato == 4:
dat = "char"
if dato == 5:
dat = "String"
if dato == 6:
dat = "float"
val = str(input("nombre de la variable: "))
print("\n")
varles.append(val)
valor = str(input("valor de la variable (Si no quieres ningun valor dejalo en blanco): " ))
if len(valor) == 0:
print("\n")
f.write(dat + " " + val + " " +valor+ ";" + "\n")
elif len(valor) != 0:
print("\n")
f.write(dat + " " + val + " " + "=" + " " +valor+ ";" + "\n")
print("Generando el setup")
for i in range(3):
print(".")
time.sleep(1)
f.write("""
void setup(){
""")
while vx == 1:
print("""
1)configuar pines
2)habilitar el puerto serial
3)generar el loop
""")
accion = int(input("Que deseas hacer?: "))
print("\n")
if accion == 1:
pins = int(input("Cuantos pines deseas habilitar?: "))
for p in range(pins):
Pn = str(input("Dame el numero del pin que deseas configuar: "))
piness.append(Pn)
print("""
1)Entrada
2)Salida
""")
Pv = int(input("En que estado deseas poner el pin?: "))
if Pv == 1:
valorpin = "INPUT"
elif Pv == 2:
valorpin = "OUTPUT"
f.write("pinMode(" + Pn + "," + valorpin + ");" + "\n")
if accion == 2:
print("""
1)300
2)1200
3)2400
4)4800
5)9600
6)19200
7)38400
8)57600
9)74880
10)115200
11)230400
12)250000
13)500000
14)1000000
15)2000000
""")
baudRate = int(input("Selecciona el Buad-Rate por favor: "))
if baudRate == 1:
baudR = 300
if baudRate == 2:
baudR = 1200
if baudRate == 3:
baudR = 2400
if baudRate == 4:
baudR = 4800
if baudRate == 5:
baudR = 9600
if baudRate == 6:
baudR = 19200
if baudRate == 7:
baudR = 38400
if baudRate == 8:
baudR = 57600
if baudRate == 9:
baudR = 74880
if baudRate == 10:
baudR = 115200
if baudRate == 11:
baudR = 230400
if baudRate == 12:
baudR = 250000
if baudRate == 13:
baudR = 500000
if baudRate == 14:
baudR = 1000000
if baudRate == 15:
baudR = 2000000
f.write("Serial.begin("+ str(baudR) +");"+"\n")
if accion == 3:
vx = vx + 1
f.write("}")
f.write("\n")
print("Generando loop")
for u in range(3):
print(".")
time.sleep(1)
f.write("""
void loop(){
""")
print("""
1)Hacer una escritura digital/analogica
2)Hacer una lectura digital/analogica
3)Colocar un delay
4)Colocar un ciclo
5)Colocar un if/else/else if
6)Colocar un Switch
7)Hacer un print/println
8)Ingresar una nueva variable
9)Otro
""")
respuestaL = int(input("Ingresa tu respuesta: "))
if respuestaL == 1:
while wh == 1:
print("""
1)analogico
2)digital
""")
Write = int(input("Selecciona la opcion: "))
if Write == 1:
print(piness)
loop = "analog"
pon = str(input("Selecciona el pin: "))
if pon in piness:
rango = int(input("Seleccions un rango de 0 a 255"))
if rango > 255:
print("No se puede configurar ese rango")
elif rango < 255:
f.write(loop * "Write(" + pon + rango + ");")
else:
print("Ese pin NO esta declarado")
elif Write == 2:
print(piness)
loop = "digital"
pon = str(input("Selecciona el pin: "))
if pon in piness:
print("""
1)HIGH
2)LOW
""")
estados = int(input("En que estado quieres poner el pin: "))
if estados > 2:
print("Ingresa un valor valido")
else:
print("Ese pin NO esta declarado")
elif Write > 3:
print("selecciona una opcion valida")
f.close
|
1114d186848e1be5220f56368f0ace0e5d9bb4f5 | leandrotartarini/python_exercises | /secondWorld/ex041.py | 299 | 4.03125 | 4 | from datetime import date
actual = date.today().year
db = int(input('Year of birth: '))
age = actual - db
print(f'The athlete is {age} year old')
if age <= 9:
print('Child')
elif age <= 14:
print('Young')
elif age <= 19:
print('Teen')
elif age <= 25:
print('Adult')
else:
print('Master') |
8e6c1b947f50ad97ae3c92185245584fc1ad114b | VincentChiu/OpenBookProject | /LovelyPython/exercise/part1-CDays/cday3/script/cdays+3-exercise-3.py | 1,501 | 4 | 4 | #!/bin/python
#coding:utf-8
'''cdays+3-exercise-3.py 使用Thread和Event实现简单的线程间通信
@see: Event(http://docs.python.org/lib/event-objects.html)
@author: U{shengyan<mailto:shengyan1985@gmail.com>}
@version:$Id$
'''
from threading import Thread
from threading import Event
import time
class myThread(Thread):
'''myThread
自定义线程
'''
def __init__(self, threadname):
Thread.__init__(self, name = threadname)
def run(self):
global event
global share_var
if event.isSet(): #判断event的信号标志
event.clear() #若设置了,则清除
event.wait() #并调用wait方法
#time.sleep(2)
share_var += 1 #修改共享变量
print '%s ==> %d' % (self.getName(), share_var)
else:
share_var += 1 #未设置,则直接修改
print '%s ==> %d' % (self.getName(), share_var)
#time.sleep(1)
event.set() #设置信号标志
if __name__ == "__main__":
share_var = 0
event = Event() #创建Event对象
event.set() #设置内部信号标志为真
threadlist = []
for i in range(10): #创建10个线程
my = myThread('Thread%d' % i)
threadlist.append(my)
for i in threadlist: #开启10个线程
i.start()
|
f1481e19efcc6a8194d8ebe6d80c599544a36d92 | Choojj/acmicpc | /단계별/06. 1차원 배열/02. 최댓값.py | 222 | 3.65625 | 4 | import sys
max_num = -float("inf")
max_num_order = 0
for i in range(9):
num = int(sys.stdin.readline())
if (num > max_num):
max_num_order = i + 1
max_num = num
print(max_num)
print(max_num_order) |
23cd595643d9e86498e9768b59384135f446399f | odonnell31/python-mathematics | /calculate/elfi.py | 999 | 3.890625 | 4 | import math
def elfi(array, strict=True):
"""
The ELFI is a simplified method for calculating the
Ethnic Diversity Index.
Accepts a list of decimal percentages, which are used
to calculate the Ethnolinguistic Fractionalization Index (ELFI).
Returns a decimal value as a floating point number.
By default, the list must add up to one. If you don't want to enforce
that check, set the kwarg strict to False.
h3. Example usage
>>> import calculate
>> calculate.elfi([0.2, 0.5, 0.05, 0.25])
0.64500000000000002
h3. Dependencies
* "math":http://docs.python.org/library/math.html
h3. Documentation
* "ethnic diversity index":http://www.ed-data.k12.ca.us/articles/EDITechnical.asp
"""
if not isinstance(array, list):
raise TypeError('input must be a list')
if strict and sum(array) != 1.0:
raise ValueError('values of submitted array must add up to one. your list adds up to %s' % sum(array))
elfi = 1 - sum([math.pow(i, 2) for i in array])
return elfi |
fd17ed3af9dd365245ff22b3a480253c3f74bd2d | soyoonjeong/python_basic | /7_예외처리.py | 2,668 | 3.6875 | 4 | 10-1 예외처리 : 에러가 발생했을 때 처리
try: #try안에서 에러가 발생하면 그 에러에 해당하는 except를 찾아 실행한다.
print("나누기 전용 계산기입니다.")
nums = []
nums.append(int(input("첫 번째 숫자를 입력하세요 : ")))
nums.append(int(input("두 번째 숫자를 입력하세요 : ")))
#nums.append(int(num[0]/num[1]))
print("{0} / {1} = {2}".format(nums[0], nums[1], nums[2]))
except ValueError:
print("에러! 잘못된 값을 입력하였습니다.")
# 에러! 잘못된 값을 입력하였습니다.
except ZeroDivisionErrror as err:
print(err)
# division by zero
except Exception as err: # 나머지 에러에 대해
print("알 수 없는 에러가 발생하였습니다.")
print(err) #에러메시지
# 10-2 에러 발생시키기, 10-3 사용자 정의 예외처리
class bignumbererror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
print("한 자리 숫자 나누기 전용 계산기입니다.")
num1 = int(input("첫 번째 숫자를 입력하세요 : "))
num2 = int(input("두 번째 숫자를 입력하세요 : "))
if num1>=10 or num2>=10:
raise bignumbererror(f"입력값 : {num1}, {num2}") # 에러를 발생시킴
print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except bignumbererror as err:
print("에러가 발생하였습니다. 한 자리 숫자만 입력하세요.")
print(err)
finally:
print("계산기를 이용해 주셔서 감사합니다.")
# 10,5 입력하면
# 에러가 발생하였습니다. 한 자리 숫자만 입력하세요.
# 입력값 : 10, 5
# 계산기를 이용해 주셔서 감사합니다. 출력됨
# 퀴즈 10
chicken = 10
waiting = 1
class SoldOutError(Exception):
pass
while(True):
try:
print("남은 치킨 : {0}".format(chicken))
order = int(input("치킨 몇 마리를 주문하시겠습니까?"))
if order<1:
raise ValueError
elif order>chicken:
print("재료가 부족합니다.")
else:
print("[대기번호 {0}] {1}마리 주문이 완료되었습니다."\
.format(waiting, order))
waiting+=1
chicken-=order
if chicken==0:
raise SoldOutError
except ValueError: #1보다 작거나 숫자가 아닌 입력값
print("잘못된 값을 입력하였습니다.")
except SoldOutError: #치킨이 소진되었을 때
print("재고가 소진되어 더 이상 주문을 받지 않습니다.")
break #프로그램 종료 |
e0ee61930cdaf89e2a77a88a7072546a4bfb710c | szczybur/Adafruit_IO_Python | /examples/basics/digital_out.py | 1,347 | 3.5 | 4 | """
'digital_out.py'
===================================
Example of turning on and off a LED
from the Adafruit IO Python Client
Author(s): Brent Rubell, Todd Treece
"""
# Import standard python modules
import time
# import Adafruit Blinka
import digitalio
import board
# import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, RequestError
# Set to your Adafruit IO key.
# Remember, your key is a secret,
# so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY'
# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME'
# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
try: # if we have a 'digital' feed
digital = aio.feeds('digital')
except RequestError: # create a digital feed
feed = Feed(name="digital")
digital = aio.create_feed(feed)
# led set up
led = digitalio.DigitalInOut(board.D5)
led.direction = digitalio.Direction.OUTPUT
while True:
data = aio.receive(digital.key)
if int(data.value) == 1:
print('received <- ON\n')
elif int(data.value) == 0:
print('received <- OFF\n')
# set the LED to the feed value
led.value = int(data.value)
# timeout so we dont flood adafruit-io with requests
time.sleep(0.5)
|
d11a4ba2e6b3b5f4df7c9420ede033520abc4cf3 | YaroslavKahaniak/Python-11 | /managers/CleaningToolsManager.py | 1,201 | 3.53125 | 4 | def find_by_producer():
print("Found by producer:")
class CleaningToolsManager:
cleaning_tools = []
def add_element_to_list(self, cleaning_tool):
self.cleaning_tools.append(cleaning_tool)
def show_list_elements(self):
print("\nAll elements in list:")
for element in self.cleaning_tools:
print(element)
print("\n")
def sort_by_price (self, reverse):
self.cleaning_tools.sort(key=lambda cleaning_tools: cleaning_tools.price,
reverse=reverse)
def sort_by_costs_per_month (self, reverse):
self.cleaning_tools.sort(key=lambda cleaning_tools: cleaning_tools.costs_per_month, reverse=reverse)
def find_by_producer(self, producer):
temp_list = []
for cleaning_tools in self.cleaning_tools:
if cleaning_tools.producer == producer:
temp_list.append(cleaning_tools)
print("\nFind by name result:")
for cleaning_tools in temp_list:
print(cleaning_tools)
return temp_list
print("")
def __del__(self):
print("\nCleaning tools manager is deleted!")
|
adeee1ce32d9065cd6120ec42fe3d8b6fe07dd6c | lalit97/DSA | /linked-list/delete-all-occurence.py | 758 | 3.78125 | 4 | '''
https://practice.geeksforgeeks.org/problems/delete-keys-in-a-linked-list/1
'''
def deleteAllOccurances(head, k):
if head is None:
return None
if head.next is not None and head.data == k:
head = head.next
current = head
while current is not None and current.next is not None:
if current.data == k: # in case of 2 or more consecutive deletions
current.data = current.next.data
to_del = current.next
current.next = current.next.next
to_del.next = None
elif current.next.data == k:
to_del = current.next
current.next = current.next.next
to_del.next = None
else:
current = current.next
return head
|
d332b8e0ff5a645c9bb13fdb8ce9a3fb043c77a1 | AnjanaPT/PythonLab | /Exercise__2/Color.py | 211 | 3.9375 | 4 | n = int(input("Enter The Number Of Colors : "))
cl = []
print("Enter ",n," Colors")
for i in range(n):
cl.append(input())
print("Given Colors : ",cl,"\nFirst Color : ",cl[0],"\nLast Color : ",cl[-1]) |
faf619ebc20a5abda2eba40e5020f53f817d895b | jatin9909/python_programs | /Basic/armstrong.py | 242 | 3.59375 | 4 | def check(x):
a=x
len=int(0)
while(int(a)!=0):
a = a / 10
len+=1
sum=0;
temp = x
while(temp!=0) :
r = temp%10
sum=sum+pow(r,len)
temp=temp//10
print(sum)
return (sum==x)
n = int(input("Enter "))
print(check(n)) |
5d96cd355bb4ba8cbace64126038403415052662 | mtrdazzo/CTCI | /Ch4_Trees_and_Graphs/tests/test_CTCI_Ch4_Ex4.py | 1,216 | 3.53125 | 4 | from unittest import TestCase
from CTCI.Ch4_Trees_and_Graphs.exercises.CTCI_Ch4_Ex4 import BalancedBST
class TestBSTBalanced(TestCase):
def setUp(self):
self.bst = BalancedBST()
def tearDown(self):
pass
def test_empty_bst(self):
"""Test empty binary search tree"""
self.assertIsNone(self.bst.is_balanced())
def test_single_element(self):
"""Test single element bst"""
self.bst.add(1)
self.assertTrue(self.bst.is_balanced())
def test_balanced(self):
"""Test balanced bst"""
nodes = [5, 7, 6, 2, 3, 4, 0, 9, 8, 10, 1]
for node in nodes:
self.bst.add(node)
self.assertTrue(self.bst.is_balanced())
def test_unbalanced_left_tree(self):
"""Test unbalanced left tree"""
nodes = [5, 7, 6, 2, 3, 4, 0, 9, 8, 10, 1, 0, 0, 0]
for node in nodes:
self.bst.add(node)
self.assertFalse(self.bst.is_balanced())
def test_unbalanced_right_tree(self):
"""test unbalanced right tree"""
nodes = [5, 7, 6, 2, 3, 4, 0, 9, 8, 10, 1, 11]
for node in nodes:
self.bst.add(node)
self.assertFalse(self.bst.is_balanced())
|
511fdcaf6eeb4ae27535e835ec6853d624965021 | ivychen/w4156-lecture-code | /tests/testing/theory/test_wraparound.py | 1,379 | 4.15625 | 4 | import unittest
from lectures.testing.theory.wrap_around_counter import WrapAroundCounter
class MyTestCase(unittest.TestCase):
"""
A more realistic example of a test case file. Note the use of setUp which is inherited from unittest.TestCase
"""
def setUp(self):
self.wrap_around_counter = WrapAroundCounter(1000)
def push_assert(self, input, expected):
"""
A helper method I wrote so I dont have to repeatedly type boring code to push in values and assert.
Note - you are allowed to write helpers within test cases to make your code more readable
:param input:
:param expected:
:return:
"""
self.assertEqual(self.wrap_around_counter.increment(input), expected)
def test_wac(self):
"""
Remember: any method beginning 'test' will be run and is assumed to contain test cases and assertions
:return:
"""
# As personal taste I like the format where you prepare a datastructure with inputs and expected output
# It makes it very easy to read the test cases.
cases = [(-1, 1),
(0, 1),
(1, 2),
(999, 1000),
(1000, 1),
(1001, 1)]
list(map(lambda x: self.push_assert(x[0], x[1]), cases))
if __name__ == '__main__':
unittest.main()
|
258ddfcb6e2aa9372cc3e5a01aa79d15ecd39c6e | CJ8664/hackerrank | /Algorithms/Implementations/easy/electronics_shop.py | 513 | 3.59375 | 4 | # Program URL : https://www.hackerrank.com/challenges/electronics-shop
s,n,m = input().strip().split(' ')
s,n,m = [int(s),int(n),int(m)]
keyboards = [int(x) for x in input().strip().split(' ') if int(x) < s]
pendrives = [int(x) for x in input().strip().split(' ') if int(x) < s]
max_exp = -1
for keyboard in keyboards:
for pendrive in pendrives:
if(keyboard+pendrive <= s):
if(keyboard+pendrive>max_exp):
max_exp = keyboard+pendrive
print(str(max_exp)) |
b24316622db9265a99cf5b13ead5b81065e937c4 | gieseladev/andesite.py | /examples/music_bot/cli.py | 3,306 | 3.59375 | 4 | """CLI for interacting with the music bot example."""
from argparse import ArgumentParser
from typing import Sequence, cast
def build_argument_parser() -> ArgumentParser:
"""Build the `ArgumentParser` used to extract the important information.
Calling `parse_args` on the returned parser will return a `Namespace` which has the
attributes of the `OptionsType` class, however it is not an instance of `OptionsType`.
You could call `parse_args` with namespace=`OptionsType` to get an instance of `OptionsType`.
"""
parser = ArgumentParser(description="A sample music bot for andesite.py")
parser.add_argument("discord_token", help="Discord bot token")
andesite_group = parser.add_argument_group("andesite")
andesite_group.add_argument("--andesite-ws", required=True, help="Web socket endpoint of Andesite")
andesite_group.add_argument("--andesite-http", required=True, help="HTTP endpoint of Andesite")
andesite_group.add_argument("--andesite-password", default=None, help="Password for the Andesite node")
misc_group = parser.add_argument_group("misc")
misc_group.add_argument("--command-prefix", default="a.", help="Command prefix to respond to")
return parser
def configure_logging():
"""Configure the logging library.
Automatically tries to use `colorlog.ColoredFormatter`, if available.
"""
import logging
handler = logging.StreamHandler()
try:
import colorlog
except ImportError:
formatter = logging.Formatter("{levelname:8} {name:30} {message}", style="{")
else:
formatter = colorlog.ColoredFormatter("{log_color}{levelname:8}{reset} {name:30} {blue}{message}", style="{")
handler.setFormatter(formatter)
root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(handler)
andesite = logging.getLogger("andesite")
andesite.setLevel(logging.DEBUG)
def ensure_environment() -> None:
"""Makes sure the bot can be run.
This mainly checks the discord version.
"""
import warnings
try:
import discord
except ImportError:
raise RuntimeError("discord.py is not installed!") from None
try:
version_info = discord.version_info
if version_info.major != 1:
raise RuntimeError(f"discord.py library major version 1 needed, not {version_info.major}") from None
if version_info.minor not in {0, 1}:
warnings.warn(f"This bot was written for version 1.0.0, you're using {version_info}. "
f"No guarantee that things will work out")
except Exception:
warnings.warn("Couldn't access discord's version information! "
"Don't be surprised if something doesn't work as it should")
def main(args: Sequence[str] = None) -> None:
"""Main entry point which does everything."""
parser = build_argument_parser()
ns = parser.parse_args(args)
ensure_environment()
configure_logging()
import logging
log = logging.getLogger(__name__)
log.debug("creating bot")
from .bot import create_bot, OptionsType
bot = create_bot(cast(OptionsType, ns))
log.info("starting bot")
bot.run(ns.discord_token)
log.info("exited")
if __name__ == "__name__":
main()
|
24b9bc4babb7decdfcd54db92232fc496f45f875 | pratikbongale/CRLS_IMPL | /s4_advanced_design_and_analysis/ch15_dynamic_programming/lcs.py | 1,016 | 3.65625 | 4 | from utilities.helper_functions import print_matrix
def lcs_length(x, y):
m = len(x)
n = len(y)
c = [[0] * (n+1) for _ in range(m+1)]
b = [[''] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if x[i-1] == y[j-1]:
c[i][j] = c[i-1][j-1] + 1
b[i][j] = "\\"
elif c[i-1][j] >= c[i][j-1]:
c[i][j] = c[i-1][j]
b[i][j] = "|"
else:
c[i][j] = c[i][j-1]
b[i][j] = "_"
return c, b
def print_lcs(b, x, i, j):
if i == 0 or j == 0:
return
if b[i][j] == "\\":
print_lcs(b, x, i-1, j-1)
print(x[i-1], end='')
elif b[i][j] == "|":
print_lcs(b, x, i-1, j)
else:
print_lcs(b, x, i, j-1)
if __name__ == '__main__':
x = "abcbdab"
y = "bdcaba"
m = len(x)
n = len(y)
c, b = lcs_length(x, y)
print_matrix(c)
print_matrix(b)
print_lcs(b, x, m, n)
|
fe16c7c164dc73f54e31e7ffc2fcb04dc6ecf06d | ulisseslimaa/SOLUTIONS-URI-ONLINE-JUDGE | /Solutions/1924_Vitória_e_a_Indecisão.py | 82 | 3.75 | 4 | a = int(input())
for i in range(a):
b = input()
print("Ciencia da Computacao") |
8bbdb6e9157642e89e718d51a76f674d5fa177be | ethirajmanoj/Python-14-6-exercise | /14-quiz.py | 1,062 | 4.1875 | 4 | # Create a question class
# Read the file `data/quiz.csv` to create a list of questions
# Randomly choose 10 question
# For each question display it in the following format followed by a prompt for answer
"""
<Question text>
1. Option 1
2. Option 2
3. Option 3
4. Option 4
Answer ::
"""
import csv
score = 0
score = int(score)
f = open("quiz.csv",'r')
d=csv.reader(f)
next(f) #To Skip Header Row
k = 0
adm = str(input(""))
for row in d:
if str(row[0])==adm:
print("Que:= ", row[1])
print("01 = ", row[2])
print("02 = ", row[3])
print("03 = ", row[4])
print("04 = ", row[5])
#print("Key = ", row[6])
answer = input("Key: ")
if answer ==str(row[6]):
print("Correct!")
score = score + 1
else:
print("Incorrect, Correct Answer is " + str(row[6]))
print("Your current score is " + str(score) + " out of 10")
# Keep score for all right and wrong answer
# Take an extra step and output the correct answer for all wrong answers at the end
|
03a6346f7691a023106710c21db4e1410aef0008 | yejineer/Study | /BigData/Lab2/q6.py | 179 | 3.90625 | 4 | def max(*ints):
max = -1
for n in ints:
if max < n:
max = n
return max
print(max(1, 4, 6))
print(max(10, 5, 87, 57, 38))
print(max(4, 3, 2, 1))
|
90fdc0fa344376e196be9a2741bbb204c14fc162 | playi/WonderPyExamples | /misc/twitterBot.py | 9,755 | 3.625 | 4 | import WonderPy.core.wwMain
from WonderPy.core.wwConstants import WWRobotConstants
from threading import Thread
import twitter
from queue import *
'''
This example requires you to set up a Twitter Application (https://apps.twitter.com/)
and provide your key and token below.
This example will listen for tweets to a specified account and parse the message looking for an action to perform.
Currently only drive and turn actions will be performed. Below are example tweets of valid actions assuming
we are listening to the Twitter account @twitterBot:
@twitterBot drive forward 40
@twitterBot drive left 50
@twitterBot turn right 90
'''
class Direction(object):
LEFT = 0
RIGHT = 1
FORWARD = 2
BACK = 3
class ActionType(object):
DRIVE = 0
ROTATE = 1
DRIVE_ACTION_WORDS = ['GO', 'DRIVE', 'MOVE']
ROTATE_ACTION_WORDS = ['TURN', 'ROTATE', 'SPIN']
FORWARD_DIRECTION_WORDS = ['FORWARD']
BACK_DIRECTION_WORDS = ['BACK']
LEFT_DIRECTION_WORDS = ['LEFT']
RIGHT_DIRECTION_WORDS = ['RIGHT']
ROTATION_MAX = 180
ROTATION_MIN = -180
DRIVE_MAX = 100
DRIVE_MIN = -100
# populate these values with the values given by the Twitter API
# see https://python-twitter.readthedocs.io/en/latest/getting_started.html for instruction on how set up keys and tokens
TWITTER_CONSUMER_KEY = ""
TWITTER_CONSUMER_SECRET = ""
TWITTER_ACCESS_TOKEN_KEY = ""
TWITTER_ACCESS_TOKEN_SECRET = ""
# populate this list with the Twitter accounts you want to listen to
TWITTER_USERS = [""]
TWITTER_LANG = ["en"]
def is_numeric(s):
'''
Determines if a string is numeric (including negative and decimal numbers)
:param s: string to check
:return: Bool
'''
try:
float(s)
return True
except ValueError:
return False
class TwitterBot(object):
def __init__(self):
self._action_queue = Queue()
self._twitter_api = None
self._robot = None
def on_connect(self, robot):
'''
Kick off async threads
:param robot: The robot that was connected to
:return: None
'''
if not robot.has_ability(WWRobotConstants.WWRobotAbilities.BODY_MOVE, True):
# it doesn't do any harm to send drive commands to a robot with no wheels,
# but it doesn't help either.
print("%s cannot drive! try a different example." % (robot.name))
return
self._robot = robot
print("starting async threads for %s" % (self._robot.name))
self._async_thread1 = Thread(target=self.action_listener_async)
self._async_thread1.start()
self._async_thread2 = Thread(target=self.twitter_async)
self._async_thread2.start()
def action_listener_async(self):
'''
Performs actions placed on the action queue
:return: None
'''
print("listening")
while True:
action = self._action_queue.get(block=True)
# Reply to the user telling them their action is about to be performed
self._twitter_api.PostUpdate(status="Performing action: " + action["readable"],
in_reply_to_status_id=action["id"],
auto_populate_reply_metadata=True)
print("Performing action: " + action["readable"])
if action["type"] == ActionType.DRIVE:
self.perform_drive(action["direction"], action["value"])
elif action["type"] == ActionType.ROTATE:
self.perform_rotate(action["direction"], action["value"])
def twitter_async(self):
'''
Listens for twitter messages sent to any users in the TWITTER_USERS array. Creates and adds actions to the queue
based on the content of the message
:return: None
'''
try:
# Setup the twitter api
self._twitter_api = twitter.Api(consumer_key=TWITTER_CONSUMER_KEY,
consumer_secret=TWITTER_CONSUMER_SECRET,
access_token_key=TWITTER_ACCESS_TOKEN_KEY,
access_token_secret=TWITTER_ACCESS_TOKEN_SECRET)
print("twitter setup successfully")
for line in self._twitter_api.GetStreamFilter(track=TWITTER_USERS, languages=TWITTER_LANG):
self.parse_message(line["text"], line["id"])
except twitter.TwitterError:
print("Unauthorized Twitter credentials. Verify Twitter keys and tokens are correct")
def parse_message(self, message, tweet_id):
'''
Parses a message and turns it into actions and adds them to the action queue
Each action must follow the order <action type> <direction> <value>
:param message: The message to parse
:param tweet_id: The id of the tweet that send this message. Used to send response tweets
:return: None
'''
message = message.upper()
action = None
direction = None
value = None
readable_action = ""
for word in message.split():
if action == None:
if word in DRIVE_ACTION_WORDS:
action = ActionType.DRIVE
readable_action += word.lower() + " "
elif word in ROTATE_ACTION_WORDS:
action = ActionType.ROTATE
readable_action += word.lower() + " "
elif direction == None:
if word in BACK_DIRECTION_WORDS:
direction = Direction.BACK
readable_action += word.lower() + " "
elif word in FORWARD_DIRECTION_WORDS:
direction = Direction.FORWARD
readable_action += word.lower() + " "
elif word in LEFT_DIRECTION_WORDS:
direction = Direction.LEFT
readable_action += word.lower() + " "
elif word in RIGHT_DIRECTION_WORDS:
direction = Direction.RIGHT
readable_action += word.lower() + " "
elif value == None and is_numeric(word):
value = float(word)
readable_action += word + " "
# We have found an action, direction, and value
if action != None and direction != None and value != None:
if self.are_params_valid(action, direction, value):
self._action_queue.put({"type": action, "direction": direction, "value": value, "id": tweet_id,
"readable": readable_action})
print("Added: {0}, {1}, {2}".format(action, direction, value))
else:
# Command given is not valid
# Send a reply informing the user
self._twitter_api.PostUpdate(status="Invalid action: " + readable_action,
in_reply_to_status_id=tweet_id,
auto_populate_reply_metadata=True)
print("Invalid command: {0}".format(readable_action))
return
# The entire message has been parsed and no message was found
# Inform the sender that their message did not contain a valid action
self._twitter_api.PostUpdate(status="No valid action received, must specify an action, direction, and value",
in_reply_to_status_id=tweet_id,
auto_populate_reply_metadata=True)
def are_params_valid(self, action, direction, value):
'''
Validates the action parameters to make sure it is a valid action
:param action: The type of action
:param direction: The direction of the action
:param value: The value associated with the action
:return: True if valid, False if not
'''
if action != None and direction != None and value != None:
if action == ActionType.DRIVE:
return value >= DRIVE_MIN and value <= DRIVE_MAX
if action == ActionType.ROTATE:
return (direction == Direction.LEFT or direction == Direction.RIGHT) and\
value >= ROTATION_MIN and value <= ROTATION_MAX
return False
def perform_drive(self, direction, distance):
'''
Performs a drive action
:param direction: Direction to drive
:param distance: Distance to drive
:return: None
'''
if direction == Direction.FORWARD:
self._robot.commands.body.do_forward(distance, abs(distance))
elif direction == Direction.BACK:
self._robot.commands.body.do_forward(-distance, abs(distance))
elif direction == Direction.LEFT:
# rotate left and drive forward
self.perform_rotate(Direction.LEFT, 90)
self._robot.commands.body.do_forward(distance, abs(distance))
elif direction == Direction.RIGHT:
# rotate right and drive forward
self.perform_rotate(Direction.RIGHT, 90)
self._robot.cmds.body.do_forward(distance, abs(distance))
def perform_rotate(self, direction, degs):
'''
Performs a rotation action
:param direction: direction to rotate
:param degs: degrees to rotate
:return: None
'''
if direction == Direction.LEFT:
self._robot.commands.body.do_turn(degs, abs(degs))
elif direction == Direction.RIGHT:
self._robot.commands.body.do_turn(-degs, abs(degs))
if __name__ == "__main__":
WonderPy.core.wwMain.start(TwitterBot())
|
37e402f6f64b8d9f7204c938abcf2e41c103b660 | danrayu/pythonrep | /ex_numberreverse.py | 330 | 4.25 | 4 | """
Exercise: Write a program that checks if the reverse of a number is the same number.
It mustn't accept anything except numbers
"""
from InputQualifier import input_check_if_int
number = input_check_if_int(message = "Type in a number:")
if number == number[::-1]:
print("Reversible.")
else:
print("Not reversible.")
|
7c5dabf122a708a3877a13d44a478fcb9e181cbd | kptnkrnch/IntroAI-Pathfinder | /CMPT310-ASN1part1.py | 16,750 | 3.796875 | 4 | ############################################################################
# Project: Pathfinding for shortest path
# Author: Joshua Campbell
# Student Number: 301266191
# Date: October 10, 2016
############################################################################
import time
import sys
# Tile class, used for representing nodes on the grid
class Tile:
def __init__(self, x, y, name=None):
self.x = x # x location on the grid
self.y = y # y location on the grid
self.solid = False # boolean for checking if this tile is a wall or not
self.parent = None # Parent tile for this tile
self.cost = 0 # The current cost to get to the node so far
self.heuristic = 0 # The heuristic cost to a goal point
self.estimate = 0 # The estimated cost to a goal point (cost + heuristic)
self.onPath = False # boolean flag for whether this tile node is part of the path or not
self.name = name # name of the tile (if it has one, ie a landmark)
def setSolid(self, solid):
self.solid = solid
def setEstimate(self, estimate):
self.estimate = estimate
def getEstimate(self):
return self.estimate
# Calculates the estimated cost by adding the current cost with the heuristic
def calculateEstimate(self):
self.estimate = self.cost + self.heuristic
def setCost(self, cost):
self.cost = cost
self.calculateEstimate()
def getCost(self):
return self.cost
def setHeuristic(self, heuristic):
self.heuristic = heuristic
def getHeuristic(self):
return self.heuristic
# Calculates the heuristic as the minimum number of moves needed to get from one point to another.
# This calculation is essentially the x distance plus the y distance between two points.
# For example, (5,5) and (8,9) would be 8-5 = 3 for the x distance and 9-5 = 4 for the y distance.
# Therefore, the heuristic would be 3 + 4 = 7 which would be the minimum number of moves to get to (8,9).
def generateHeuristic(self, goalX, goalY):
self.heuristic = abs(goalX - self.x) + abs(goalY - self.y)
def setParent(self, parent):
self.parent = parent
def getParent(self):
return self.parent
def isSolid(self):
return self.solid
# Used for taking a peek at a new estimate for a node without storing that new estimate
def peekEstimate(self, cost):
return self.heuristic + cost
# shortcut function for calculating and setting the heuristics for all of the tile nodes on the map
def calculateHeuristics(_goalX, _goalY, _searchMap):
for x in range(gridWidth):
for y in range(gridHeight):
tempnode = searchMap[x][y]
tempnode.generateHeuristic(_goalX, _goalY)
searchMap[x][y] = tempnode
# finds the lowest costing node (based on current cost in path and its heuristic) and returns the index of the node
# in the openNodes list.
def findLeastCostNode(_openNodes):
leastCostNode = None
leastCostIndex = 0
currentIndex = 0
for node in _openNodes:
node.calculateEstimate()
if leastCostNode is None:
leastCostNode = node
leastCostIndex = currentIndex
else:
if node.getEstimate() < leastCostNode.getEstimate():
leastCostNode = node
leastCostIndex = currentIndex
currentIndex = currentIndex + 1
return leastCostIndex
# visitNeighbours expands the tiles to the north, east, south, and west of the current node.
# If one of these nodes has not been visited, it is added on to the openNodes list. If it has been visited and if
# it is in either the openNodes or the closedNodes list, the algorithm checks if there if the cost from the current node
# is less than the previous cost. If it is, it is added back into the openNodes list.
def visitNeighbours(_node, _goalX, _goalY, _searchMap, _openNodes, _closedNodes):
global frontierCount
_x = _node.x
_y = _node.y
if _x - 1 >= 0:
temp = _searchMap[_x - 1][_y]
if isGoalNode(temp, _goalX ,_goalY): # If the node is the goal node, set the current node as its parent and return it
temp.setParent(_node)
return temp
# if temp is a traversable node and it is not in the closed or open lists, set its cost and add it to the opennodes list
if temp not in _openNodes and temp not in _closedNodes and not temp.isSolid():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
frontierCount += 1
# else if temp is in the openNodes list, but the cost of getting there from the current node is less than before, update its cost
elif temp in _openNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
# else if temp is in the closedNodes list, but the cost of getting there from the current node is less than before, update
# its cost and add it back into the openNodes list.
elif temp in _closedNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
_closedNodes.remove(temp)
if _x + 1 <= (gridWidth - 1):
temp = _searchMap[_x + 1][_y]
if isGoalNode(temp, _goalX ,_goalY): # If the node is the goal node, set the current node as its parent and return it
temp.setParent(_node)
return temp
# if temp is a traversable node and it is not in the closed or open lists, set its cost and add it to the opennodes list
if temp not in _openNodes and temp not in _closedNodes and not temp.isSolid():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
frontierCount += 1
# else if temp is in the openNodes list, but the cost of getting there from the current node is less than before, update its cost
elif temp in _openNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
# else if temp is in the closedNodes list, but the cost of getting there from the current node is less than before, update
# its cost and add it back into the openNodes list.
elif temp in _closedNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
_closedNodes.remove(temp)
if _y - 1 >= 0:
temp = _searchMap[_x][_y - 1]
if isGoalNode(temp, _goalX ,_goalY): # If the node is the goal node, set the current node as its parent and return it
temp.setParent(_node)
return temp
# if temp is a traversable node and it is not in the closed or open lists, set its cost and add it to the opennodes list
if temp not in _openNodes and temp not in _closedNodes and not temp.isSolid():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
frontierCount += 1
# else if temp is in the openNodes list, but the cost of getting there from the current node is less than before, update its cost
elif temp in _openNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
# else if temp is in the closedNodes list, but the cost of getting there from the current node is less than before, update
# its cost and add it back into the openNodes list.
elif temp in _closedNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
_closedNodes.remove(temp)
if _y + 1 <= (gridHeight - 1):
temp = _searchMap[_x][_y + 1]
if isGoalNode(temp, _goalX ,_goalY): # If the node is the goal node, set the current node as its parent and return it
temp.setParent(_node)
return temp
# if temp is a traversable node and it is not in the closed or open lists, set its cost and add it to the opennodes list
if temp not in _openNodes and temp not in _closedNodes and not temp.isSolid():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
frontierCount += 1
# else if temp is in the openNodes list, but the cost of getting there from the current node is less than before, update its cost
elif temp in _openNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
# else if temp is in the closedNodes list, but the cost of getting there from the current node is less than before, update
# its cost and add it back into the openNodes list.
elif temp in _closedNodes and temp.peekEstimate(_node.getCost() + 1) < temp.getEstimate():
temp.setParent(_node)
temp.setCost(_node.getCost() + 1)
_openNodes.append(temp)
_closedNodes.remove(temp)
return None
# Checks if a Tile node is the goal point
def isGoalNode(_node, _goalX, _goalY):
if _node.x == _goalX and _node.y == _goalY:
return True
else:
return False
# findPath is the main body for the pathfinding algorithm (A*).
# findPath returns the path it found between the start and the goal.
# findPath also labels the nodes on the map as being "onPath" for printing purposes.
def findPath(_startX, _startY, _goalX, _goalY, _searchMap):
openNodes = []
closedNodes = []
openNodes.append(searchMap[_startX][_startY]) # appending the starting node
calculateHeuristics(_goalX, _goalY, _searchMap) # calculates the heuristics for all nodes in the map
path = []
while len(openNodes) > 0:
index = findLeastCostNode(openNodes) # get the index of the lowest cost node in the openNodes list
node = openNodes.pop(index) # remove the lowest costing node from the openNodes list
# Expand the neighbours of the lowest costing node and add them to the openNodes list
goal = visitNeighbours(node, _goalX, _goalY, _searchMap, openNodes, closedNodes)
if goal is not None: # if the goal node is found, we are done
temp = goal
# once the goal node is found, backtrack from that node to its parent and its parents parent, etc
# until we get back to the starting node. Add all of these nodes/parents to the path list.
while temp.getParent() is not None:
path.append(temp)
temp = temp.getParent()
path.append(temp)
break
closedNodes.append(node)
# setting the path node flag for nodes in the map for printing purposes
for node in path:
node.onPath = True
return path
def readMapFile(_fileName):
readSize = False
with open(_fileName) as f:
content = f.readlines()
global gridWidth
global gridHeight
gridHeight = len(content)
currentY = gridHeight - 1
for line in content:
curline = line.split()
if curline:
lineTiles = [int(i) for i in curline]
if not readSize:
readSize = True
gridWidth = len(lineTiles)
searchMap = [[Tile(x, y) for y in range(gridHeight)] for x in range(gridWidth)]
if len(lineTiles) > gridWidth:
return None
currentX = 0
if readSize:
for tile in lineTiles:
if tile == 1:
searchMap[currentX][currentY].setSolid(True)
currentX += 1
currentY -= 1
return searchMap
gridWidth = 18
gridHeight = 18
global frontierCount
frontierCount = 0
searchMap = []
isValidInput = True
if len(sys.argv) == 1:
# Generating an 18x18 map
searchMap = [[Tile(x, y) for y in range(gridHeight)] for x in range(gridWidth)]
# Setting up the walls on the map
searchMap[7][5].setSolid(True)
searchMap[7][6].setSolid(True)
searchMap[7][7].setSolid(True)
searchMap[7][8].setSolid(True)
searchMap[7][9].setSolid(True)
searchMap[10][13].setSolid(True)
searchMap[11][13].setSolid(True)
searchMap[12][13].setSolid(True)
searchMap[13][13].setSolid(True)
searchMap[14][13].setSolid(True)
searchMap[15][13].setSolid(True)
searchMap[15][12].setSolid(True)
# Start point and goal point
startX = 0
startY = 0
goalX = 17
goalY = 17
elif len(sys.argv) == 5:
# Start point and goal point via Command Line arguments
startX = int(sys.argv[1])
startY = int(sys.argv[2])
goalX = int(sys.argv[3])
goalY = int(sys.argv[4])
# Generating an 18x18 map
searchMap = [[Tile(x, y) for y in range(gridHeight)] for x in range(gridWidth)]
# Setting up the walls on the map
searchMap[7][5].setSolid(True)
searchMap[7][6].setSolid(True)
searchMap[7][7].setSolid(True)
searchMap[7][8].setSolid(True)
searchMap[7][9].setSolid(True)
searchMap[10][13].setSolid(True)
searchMap[11][13].setSolid(True)
searchMap[12][13].setSolid(True)
searchMap[13][13].setSolid(True)
searchMap[14][13].setSolid(True)
searchMap[15][13].setSolid(True)
searchMap[15][12].setSolid(True)
if searchMap[startX][startY].isSolid():
print "Error: the starting point cannot be a wall."
isValidInput = False
if searchMap[goalX][goalY].isSolid():
print "Error: the goal point cannot be a wall."
isValidInput = False
if goalX < 0 or goalY < 0 or startX < 0 or startY < 0:
isValidInput = False
if goalX > gridWidth - 1 or startX > gridWidth - 1:
isValidInput = False
if goalY > gridHeight - 1 or startY > gridHeight - 1:
isValidInput = False
elif len(sys.argv) == 6:
# Start point and goal point via Command Line arguments
startX = int(sys.argv[1])
startY = int(sys.argv[2])
goalX = int(sys.argv[3])
goalY = int(sys.argv[4])
# Generating Map from Map File
searchMap = readMapFile(sys.argv[5])
if searchMap is None:
print "Error loading map file!"
isValidInput = False
if searchMap[startX][startY].isSolid():
print "Error: the starting point cannot be a wall."
isValidInput = False
if searchMap[goalX][goalY].isSolid():
print "Error: the goal point cannot be a wall."
isValidInput = False
if goalX < 0 or goalY < 0 or startX < 0 or startY < 0:
isValidInput = False
if goalX > gridWidth - 1 or startX > gridWidth - 1:
isValidInput = False
if goalY > gridHeight - 1 or startY > gridHeight - 1:
isValidInput = False
else:
# Program Usage
isValidInput = False
print "Usage 1: python CMPT310-ASN1part1.py"
print "Usage 3: python CMPT310-ASN1part1.py <startX> <startY> <goalX> <goalY>"
print "Usage 2: python CMPT310-ASN1part1.py <startX> <startY> <goalX> <goalY> <mapFile>"
if isValidInput:
# Finding the shortest path between the start point and the goal point
start_time = time.time()
finalPath = findPath(startX, startY, goalX, goalY, searchMap)
end_time = time.time()
finalPath.reverse()
# Reversing the map so that the printing matches the specified map in the Assignment
searchMap.reverse()
for x in range(gridWidth):
searchMap[x].reverse()
searchMap.reverse()
# Printing the map and the path (+ symbols)
print "Map: (0's are traversable nodes, 1's are nontraversable nodes, +'s are path nodes)"
for y in range(gridHeight):
for x in range(gridWidth):
if searchMap[x][y].isSolid():
print 1, ' ',
elif searchMap[x][y].onPath:
print '+', ' ',
else:
print 0, ' ',
print
print
print "Length of path:", len(finalPath)
print "Total number of nodes expanded:", frontierCount
if len(finalPath) > 0:
print "Path: [",
for node in finalPath:
print "(%d, %d), " % (node.x, node.y),
print "]"
else:
print "Path: no path could be found"
print "Execution Time: %g seconds" % (end_time - start_time)
|
8e529813d7887cdcb77a1164c5fb718104484a1c | alexandraback/datacollection | /solutions_5630113748090880_0/Python/mtbrown/rank_and_file.py | 694 | 3.828125 | 4 | def main():
cases = int(input())
for case in range(1, cases + 1):
n = int(input())
lists = []
for i in range(2*n - 1):
lists.append([int(x) for x in input().split()])
missing = missing_list(lists)
out_str = " ".join([str(x) for x in missing])
print("Case #{0}: {1}".format(case, out_str))
def missing_list(lists):
mega_list = []
missing = []
for l in lists:
for x in l:
mega_list.append(x)
for x in mega_list:
if ((mega_list.count(x) % 2) != 0) and x not in missing:
missing.append(x)
missing.sort()
return missing
if __name__ == "__main__":
main() |
87ffa92e4cab1ce71d9458cc825151f43b0e9e5d | tectronics/physics | /potential.py | 263 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
print "Welcome to potential energy calculation script..."
m = input("Put mass of object:")
g = 10
h = input("Put height of object:")
potential = m*g*h
print "Potential energy of object:%s Newton" %(potential)
|
baf8ae9c3f070dd68d832108a5756a5183acb609 | Baljot12/training | /extend,append,insert.py | 972 | 4.5 | 4 | #append, extend, insert operations on sequence by taking input from user
#list
Cosmeticslist=["LAKME CONDITIONER","HIMALAYA FACEWASH","EYECONIC EYE KAJAL"]
Cosmeticslist.insert(3,"REVLON SHAMPOO")
Items=input("enter a item:")
Cosmeticslist.append(Items)
print(Cosmeticslist)
Cosmeticslist.extend('M') #u can extend only one element in a list
print(Cosmeticslist)
#operations on set (can't run append ,insert, extend on sets)
Cosmeticslist1={"LAKME CONDITIONER","HIMALAYA FACEWASH","EYECONIC EYE KAJAL"}
#Cosmeticslist1.insert(3,"REVLON SHAMPOO")
#Items=input("enter a item:")
#Cosmeticslist1.append(Items)
print(Cosmeticslist1)
#Cosmeticslist1.extend('M')
#operations on tuple
Cosmeticslist2=("LAKME CONDITIONER","HIMALAYA FACEWASH","EYECONIC EYE KAJAL")
Cosmeticslist2.insert(3,"REVLON SHAMPOO")
#Items=input("enter a item:")
Cosmeticslist2.append(Items)
print(Cosmeticslist2)
Cosmeticslist2.extend('M')
print(Cosmeticslist2)
#tuple has no attributes like extend,append,insert |
fbc720957cbdd7bc0315d11c5d9a7fe9cc7b6afb | alluong/code | /leetcode/python/string/zigzag-conversion.py | 1,424 | 4.375 | 4 | '''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
'''
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
t = ""
if numRows == 0 or numRows == 1:
return s
for ii in range(numRows):
for jj in range(0, len(s) - ii, 2 * (numRows - 1)):
if ii % (numRows - 1) == 0 or ii % (2*(numRows - 1)) == 0:
# top and bottom row have 1 element
t += s[jj + ii]
else:
# middle rows have 2 elements
t += s[jj + ii]
# make sure we do not go pass the len of string
if jj + 2 * (numRows - 1) - ii < len(s):
t += s[jj + 2 * (numRows - 1) - ii]
return t
|
48383fbebe99a145033d163515f777d0035700d6 | GSng/Algorithms | /Dijkstra.py | 2,782 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 6 21:36:34 2013
@author: g_singhal
"""
import pdb
graph = {}
with open('/Users/g_singhal/Desktop/dijkstraData.txt','rb') as f:
for line in f:
data = line.split()
parent_node = int(data[0])
data = data[1:]
child_node = []
distance = []
for node in data:
couplet = node.split(',')
child_node.append(int(couplet[0]))
distance.append(int(couplet[1]))
graph[parent_node] = dict(zip(child_node, distance))
def Dijkstra(graph,start,end):
import heapq
explored = set()
distances = {}
path = {}
queue = []
heapq.heappush(queue,[0,'',start])
stop = 0
while len(queue)>0 and stop==0:
distance, parent, node = heapq.heappop(queue)
if node not in explored:
#print 'node explored is '+str(node)
explored |= {node}
distances[node] = distance
path[node] = parent
if node==end:
stop=1
return distance, path
else:
for successor,length in graph[node].iteritems():
if successor not in explored:
new_dist = distance+length
new_entry = [new_dist,node,successor]
if successor not in distances:
distances[successor] = new_dist
path[successor] = node
heapq.heappush(queue,new_entry)
elif new_dist < distances[successor]:
q_index = queue.index([distances[successor],path[successor],successor])
distances[successor] = new_dist
path[successor] = node
queue[q_index] = new_entry
heapq.heapify(queue)
dist = Dijkstra(graph,1,7)
print 'distance to 7 is '+str(dist[0])
dist = Dijkstra(graph,1,37)
print 'distance to 37 is '+str(dist[0])
dist = Dijkstra(graph,1,59)
print 'distance to 59 is '+str(dist[0])
dist = Dijkstra(graph,1,82)
print 'distance to 82 is '+str(dist[0])
dist = Dijkstra(graph,1,99)
print 'distance to 99 is '+str(dist[0])
dist = Dijkstra(graph,1,115)
print 'distance to 115 is '+str(dist[0])
dist = Dijkstra(graph,1,133)
print 'distance to 133 is '+str(dist[0])
dist = Dijkstra(graph,1,165)
print 'distance to 165 is '+str(dist[0])
dist = Dijkstra(graph,1,188)
print 'distance to 188 is '+str(dist[0])
dist = Dijkstra(graph,1,197)
print 'distance to 197 is '+str(dist[0]) |
8d90b84b42df4f60bdae02e44a07f9442fe5444a | DgBrooks3/IA241 | /lec4.py | 563 | 4.34375 | 4 | # Lecture 4 Dict and Tuple
# my_tuple = 'a', 'b', 'c', 'd', 'e'
# print(my_tuple)
# my_second_tuple = ('a', 'b', 'c', 'd', 'e')
# print(my_second_tuple)
# not_a_tuple = 'a'
# print(type(not_a_tuple))
# is_a_tuple = ('a',)
# print(type(is_a_tuple))
# print(my_tuple[:])
my_car = {
'color' : 'red',
'maker' : 'toyota',
'year' : 2015
}
# print(my_car['year'])
# print(my_car.get('year'))
my_car['model'] = 'Corolla'
print(my_car)
my_car['year'] = '2020'
print(my_car)
print(len(my_car))
print('red' in my_car) |
2aba08123733ea782186a655e357df5c3284a5e2 | zeydustaoglu/17.Hafta-Odevler-2 | /Odev2.py | 3,368 | 3.890625 | 4 | import sqlite3 as sql
db = sql.connect('world.db')
print('Database baglandi..')
print("------------------------------------------")
im = db.cursor()
# 1. X ülkesinin başkenti neresidir? (X kullanıcı inputu olacaktır)
str = input("1.Baskentini ogrenmek istediginiz ulkeyi girin: ")
im.execute("""
SELECT City.Name
FROM city City
INNER JOIN country Country
ON City.ID = Country.Capital
WHERE Country.Name = ?
""", (str,))
veriler = im.fetchall()
print("{} baskenti: {}".format(str, veriler[0][0]))
print("------------------------------------------")
# 2. Y bölgesinde konuşulan tüm dilleri listeleyin.
str = input("2.Dillerini listelemek istediginiz ulkeyi girin: ")
im.execute("""
SELECT CL.Language
FROM countrylanguage CL
INNER JOIN country Country
ON CL.countryCode = Country.Code
WHERE Country.Name = ?
""", (str,))
veriler = im.fetchall()
for i in veriler:
print(i[0])
print("------------------------------------------")
# 3. Z dilinin konuşulduğu ulkelerin sayısını bulunuz.
str = input("3.Konusulan toplam ulke sayisini bulmak istediginiz dil: ")
im.execute("""
SELECT COUNT(Country.Name)
FROM country Country
INNER JOIN countrylanguage CL
ON CL.countryCode = Country.Code
WHERE CL.Language = ?
""", (str,))
veriler = im.fetchall()
print(veriler[0][0])
print("------------------------------------------")
# 4.Kullanıcıdan bir A bölgesi(region) ve bir B dili(language) alın. Eğer bu B dili,
# A bölgesindeki ülkelerin birinde resmi dil ise, o ülke(ler)in isim(ler)ini listeleyin.
# Eğer o bölgedeki hiçbir ülkede resmi dil değilse, "B dili A bölgesindeki hiçbir ülkede
# resmi dil değildir." şeklinde bir output verin.
str1 = input("4-a.Bir bolge girin: ")
str2 = input("4-b.Dil girin: ")
im.execute("""
SELECT Country.Name
FROM country Country
INNER JOIN countrylanguage CL
ON CL.countryCode = Country.Code
WHERE CL.Language = ? and Country.Region = ? and CL.isOfficial == "T"
""", (str2, str1))
veriler = im.fetchall()
if len(veriler) == 0:
print('{} dili {} bölgesindeki hiçbir ülkede resmi dil değildir.'.format(str2,str1))
for i in veriler:
print(i[0])
print("------------------------------------------")
# 5. Tüm kıtaları, o kıtalarda konuşulan dillerin sayısı ile birlikte bulunuz.
# (Bazı dillerin bir kıtada birden fazla ülkede konuşulduğunu unutmayın ve
# bunu dikkate alarak bir dili birden fazla kez hesaplamayın.)
im.execute("""
SELECT Country.Continent, CL.language
FROM country Country
INNER JOIN countrylanguage CL
ON CL.countryCode = Country.Code
""")
veriler = im.fetchall()
ulkeler = []
for i in veriler:
a = [i[0], i[1]]
if a not in ulkeler:
ulkeler.append([i[0], i[1]])
ulkeler.sort()
diladet = []
dilulke= []
for i in ulkeler:
if i[0] not in diladet:
diladet.append([i[0]])
for i in diladet:
if [i[0],diladet.count([i[0]])] not in dilulke:
dilulke.append([i[0],diladet.count([i[0]])])
print("5.")
for i in dilulke:
print("{} kitasinda konusulan toplam dil sayisi {}".format(i[0],i[1]))
|
30d717335e6e5844429c2b6858da8f741f245862 | vijaymaddukuri/python_repo | /training/vanHack/algorthim_test/hard/longest_non_overlapping_palindromic_product.py | 2,325 | 4.09375 | 4 | """
We define the following:
A palindrome is a sequence of characters which reads the same forward and backwards.
For example: madam and dad are palindromes, but eva and sam are not.
A subsequence is a group of characters chosen from a list while maintaining their order.
For instance, the subsequences of abc are [a,b,c,ab,ac,bc,abc]
The score of string s is the maximum product of two non-overlapping palindromic subsequences of s that we_ll
refer to as a and b. In other words, score(s) = max(length(a) x length(b)).
There may be multiple ways to choose a and b, but there can't be any overlap between the two subsequences. For example:
Index 0123456
s attract
Palindromic subsequences are [a,t,r,c,t,aa,tt,ata,ara,ttt,trt,tat,tct,atta]. Many of these subsequences overlap,
however (e.g. atta and tct) The maximum score is obtained using the subsequence atta, |atta| = 4 and |c| or |t| = 1, 4 x 1 = 4.
Function Description
Complete the function getScore in the editor below. The function must return an integer denoting the maximum possible score of s.
getScore has the following parameter(s):
s: a string to process
Constraints
1 < |s| <= 3000
s[i] is of ascii[a-z]
Sample Case 0
Sample Input 0
acdapmpomp
Sample Output 0
15
Explanation 0
Given s = "acdapmpomp", we can choose a = "aca" and b= "pmpmp" to get a maximal product of score = 3 x 5 = 15.
"""
def getScore(s):
dp = [[0 for i in range(len(s))] for i in range(len(s))]
def LPS(s):
for i in range(len(s)):
dp[i][i] = 1
for sl in range(2, len(s) + 1):
for i in range(0, len(s) - sl + 1):
j = i + sl - 1
if s[i] == s[j] and sl == 2:
dp[i][j] = 2
elif s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
print(i, j)
print(dp[i][j])
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][len(s) - 1]
longest_subsequence_pal = LPS(s)
print('Longest Palindromic Subsequence -', longest_subsequence_pal)
maximum_product = 0
for i in range(len(dp) - 1):
value = dp[0][i] * dp[i + 1][len(dp) - 1]
maximum_product = max(maximum_product, value)
return maximum_product
print(getScore('acdapmpomp'))
|
2748fc30ce9e813ae21b17ce03f99b01e2fa7a53 | liuweilin17/algorithm | /leetcode/31.py | 2,917 | 3.84375 | 4 | ###########################################
# Let's Have Some Fun
# File Name: 31.py
# Author: Weilin Liu
# Mail: liuweilin17@qq.com
# Created Time: Sun 2 Jun 17:17:50 2019
###########################################
#coding=utf-8
#!/usr/bin/python
#31. Next Permutation
class Solution:
# find the first pair i < j where nums[i]<nums[j]
def nextPermutation1(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
N = len(nums)
if not N: return
#partition
def partition(l, r):
pivot = nums[r]
i = l-1
for j in range(l, r):
if nums[j] <= pivot:
i += 1
tmp = nums[j]
nums[j] = nums[i]
nums[i] = tmp
nums[r] = nums[i+1]
nums[i+1] = pivot
return i+1
# quick sort
def quicksort(l, r):
if l < r:
p = partition(l, r)
quicksort(l, p-1)
quicksort(p+1, r)
for i in range(N-2, -1, -1):
minV = None
for j in range(i+1, N):
if nums[j] > nums[i]:
if minV == None:
minV = j
elif nums[j] < nums[minV]:
minV = j
else: pass
if minV != None:
tmp = nums[i]
nums[i] = nums[minV]
nums[minV] = tmp
quicksort(i+1, N-1)
return
# reverse
nums.sort()
# two optimizaton:
# 1. after finding the pair i<j, nums[i] > nums[j], we could simply reverse nums[i+1:] since there are in reverse order
# !!!
# 2. we do not need to use O(n^2) to find the pair!!! Before i is found, nums[i+1:] are in descending order !!!
def nextPermutation2(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(x,y):
x, y = i+1, N-1
while x < y:
tmp = nums[x]
nums[x] = nums[y]
nums[y] = tmp
x += 1
y -= 1
N = len(nums)
if not N: return
# find the first element which is smaller than previous ones
i = N-2
while i >= 0:
if nums[i] >= nums[i+1]:
i -= 1
else: break
if i == -1:
reverse(0, N-1)
return
j = i+1
while j < N:
if nums[j] > nums[i]:
j += 1
else:
break
# swap i, j-1
tmp = nums[i]
nums[i] = nums[j-1]
nums[j-1] = tmp
# reverse i+1,...,N-1
reverse(i+1, N-1)
|
c17ae1c27c2ad0556b2bebc0f861a69b84afd950 | ohadcohen22/cardgame | /games_cards/test_CardGame.py | 2,407 | 3.984375 | 4 | from unittest import TestCase
from games_cards.CardGame import CardGame
from games_cards.Player import Player
from games_cards.Card import Card
class TestCardGame(TestCase):
def setUp(self):
print("I am setup")
def test_card_num__init__(self):
"""checks card number will be 10 as default"""
cg = CardGame("aa", "bb")
self.assertEqual(cg.num_cards, 10)
def test_new_game_checking(self):
"""checking the function is really gives cards to the players"""
cg = CardGame('ohad', 'polly')
self.assertEqual(len(cg.player1.player_hand), 10)
self.assertEqual(len(cg.player2.player_hand), 10)
def test_new_game_deck_not_full(self):
"""checks the function wont start a new game if the deck is not full"""
cardgame = CardGame('ohad', 'polly')
self.assertEqual(len(cardgame.player1.player_hand), 10)
self.assertEqual(len(cardgame.player2.player_hand), 10)
self.assertEqual(len(cardgame.deck.list_cards), 32)
cardgame.new_game()
self.assertNotEqual(len(cardgame.deck.list_cards), 52)
def test_get_winner_player2_win(self):
"""checks the winner is player 2"""
player1 = Player("ohad")
player2 = Player("polly")
game = CardGame(player1.name, player2.name)
game.player1.player_hand = [Card(8, 3), Card(9, 4), Card(13, 4)]
game.player2.player_hand = [Card(7, 3)]
winner = game.get_winner()
self.assertEqual(player2.name, winner)
def test_get_winner_player1_win(self):
"""checks thw winner is player 1"""
player1 = Player("ohad")
player2 = Player("polly")
game = CardGame(player1.name, player2.name)
game.player2.player_hand = [Card(8, 3), Card(9, 4), Card(13, 4)]
game.player1.player_hand = [Card(7, 3)]
winner = game.get_winner()
self.assertEqual(player1.name, winner)
def test_get_winner_draw(self):
"""checks if the result is draw"""
player1 = Player("ohad")
player2 = Player("polly")
game = CardGame(player1.name, player2.name)
game.player2.player_hand = [Card(8, 3), Card(9, 4), Card(13, 4)]
game.player1.player_hand = [Card(7, 3), Card(10, 4), Card(12, 4)]
winner = game.get_winner()
self.assertEqual(None, winner)
def tearDown(self):
print('I am teardown')
|
0bc4f45083c1f13f410cc47807c82a171d2c0e5c | joestalker1/leetcode | /src/main/scala/WayNumberToGetHeap.py | 644 | 3.765625 | 4 | from math import log
def get_factorials(n):
factorials = {0: 1}
for i in range(1, n + 1):
factorials[i] = i * factorials[i - 1]
return factorials
def choose(factorials, n, k):
return factorials[n] // factorials[n - k] // factorials[k]
def ways(n, f):
if n <= 2:
return 1
height = int(log(n)) + 1
bottom = n - (2 ** height - 1)
left = 2 ** (height - 1) - 1 + min(2 ** (height - 1), bottom)
right = n - left - 1
return choose(f, n - 1, left) * ways(left, f) * ways(right, f)
def num_heaps(n):
factorials = get_factorials(n)
return ways(n, factorials)
print(num_heaps(10)) |
46f0f66ef79ca961f0bfa00e1c1d96d4dcb4f1a8 | zhangshv123/superjump | /shuhan/facebook/shuhan/mid/LC75-Sort Colors.py | 507 | 3.875 | 4 | #!/usr/bin/python
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero, second = 0,len(nums)-1
for i in range(0,second+1):
while nums[i] == 2 and i<second:
nums[i], nums[second] = nums[second], nums[i]
second -= 1
while nums[i] == 0 and i > zero:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1
return nums
s = Solution()
print s.sortColors([1, 0, 1, 2,1,1,1,1])
|
3a39708d8717ea2f4e0a4ad641d334cdf325fb99 | SORARAwo4649/Learning_EffectivePython | /Section1/Item10.py | 1,775 | 4.28125 | 4 | """
代入式で繰り返しを防ぐ
walrus(セイウチ)演算子
a := b 「aウォルラスb」
"""
# ジュースに使うフルーツの籠の中身を表現する
fresh_fruit = {
'apple': 10,
'banana': 8,
'lemon': 5,
}
# レモネードを作るのにレモンを使う
def make_lemonade(count):
fresh_fruit['lemon'] = count - 1
if fresh_fruit['lemon'] <= 0:
fresh_fruit.pop('lemon')
print('レモネード完成!!')
# サイダーを作るのにはアップルが4個必要らしい
def make_cider(count):
fresh_fruit['apple'] = count - 4
if fresh_fruit['apple'] <= 0:
fresh_fruit.pop('apple')
print('サイダー完成!!')
# バナナスムージーを作るのにバナナが2本必要
# スライスバナナを作る
def slice_bananas(count):
fresh_fruit['banana'] -= 2
fresh_fruit['slice_banana'] += 1
class OutOfBananas(Exception):
pass
# バナナスムージーを作る
def make_smoothies(count):
fresh_fruit['slice_banana'] -= 1
if fresh_fruit['slice_banana'] <= 0:
fresh_fruit.pop('slice_banana')
print('バナナスムージー完成!!')
def out_of_stock():
print('在庫切れ')
# getの第2引数は第一引数のキーが存在しなかったときの返り値
# レモネードの注文
if count := fresh_fruit.get('lemon', 0):
make_lemonade(count)
else:
out_of_stock()
# サイダーの注文
if (count := fresh_fruit.get('apple', 0)) >= 4:
make_cider(count)
# バナナスムージーの注文
# バナナの在庫確認
if (count := fresh_fruit.get('banana', 0)) >= 2:
# スライスバナナの在庫確認
fresh_fruit['slice_banana'] = 0
# スライスバナナの作成
slice_bananas(count)
|
4640240084685fafcf5b3353dd8cd3e90c44240a | jiaxiaochu/spider | /00-Knowledge-review/03-协程/02-判断对象是否是可迭代对象.py | 1,187 | 3.890625 | 4 | from collections import Iterable # 可迭代类型
from collections import Iterator # 迭代器类型
# 判断对象是否是 类型 的实例对象 返回值为真或者假
# isinstance(对象, 类型)
print(isinstance(100, int)) # True 判断一个数据是否是整型类型
print(isinstance(100, str)) # False 判断一个数据是否是字符串类型
# 判断对象是否是可迭代类型
print(isinstance([1, 2, 3, 4], Iterable)) # True
# 判断对象是否是迭代器类型
data_iter = iter([1, 2, 3, 4]) # 取出可迭代对象中的迭代器
data2_iter = iter(data_iter) # 迭代器是可迭代类型 通过iter(迭代器)取出迭代器还是原来的迭代器
print(id(data_iter), id(data2_iter))
print(isinstance(data_iter, Iterator)) # True
print(isinstance([1, 2, 3, 4], Iterator)) # False 可迭代对象不是迭代器
print(isinstance(data_iter, Iterable)) # True Python规定: 迭代器必须是可迭代类型对象
# 因为迭代器是可迭代对象 所以能够使用for循环进行遍历
# for i in data_iter:
# print(i)
while True:
try:
i = next(data_iter)
except StopIteration:
break
else:
print(i)
|
ac80504e777c3de9ddcc8e8b89de0b2378417f9f | CompetitiveCode/hackerrank-python | /Practice/Math/Power - Mod Power.py | 329 | 4.4375 | 4 | #Answer to Power - Mod Power
a=int(input())
b=int(input())
m=int(input())
print(pow(a,b))
print(pow(a,b,m))
"""
Powers or exponents in Python can be calculated using the built-in power function. Call the power function a^b as shown below:
>>> pow(a,b)
>>> a**b
It's also possible to calculate a^b mod m.
>>> pow(a,b,m)
""" |
4b59a2dacb92e0ff317d1ffef105ac3ff2d2ac5b | rhoenkelevra/python_simple_applications | /class-notes/fukushu/解答/hukushu0720/hukushu0720.py | 637 | 4.09375 | 4 | # ① 「calculation.py」を読み込む
import calc
# ② 利用者から数値を2つ受取る
num1 = input("ひとつ目の数値:")
num2 = input("ふたつ目の数値:")
# ③ 数値変換を行う
num1 = int(num1)
num2 = int(num2)
# ④ 4つの関数を発動し戻り値を受取る
ans1 = calc.add(num1, num2)
ans2 = calc.sub(num1, num2)
ans3 = calc.mul(num1, num2)
ans4 = calc.div(num1, num2)
# ⑤ 「◯算の結果は:△」の形で関数の数、出力する
print(f"加算の結果:{ans1}")
print(f"減算の結果:{ans2}")
print(f"乗算の結果:{ans3}")
print(f"除算の結果:{ans4}")
|
7dbf04ea8791b3e539c792d63f3018f671a0264e | Joshua-Kloepfer20/WorkshopStuySoftDev | /06_py-csv/06.py | 883 | 3.875 | 4 | #The Best Team-01
#SoftDev
#K06-printing from csv file and choosing random job
#2021-9-28
#We open up the csv file and convert to a dictionary with the keys as the job and the value as the percentage
#we then put the dictionary into a function which picks a random int from 0 to 1000
#the function adds each percentage until it reaches one greater than the random int and pickts that one to print
import csv
import random
finalDict = {}
def randomJob(reader):
x = random.randint(0, 1000)
y = 0
for i in reader:
y += reader[i] * 10
if (y > x):
print(i)
break
with open('occupations.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
finalDict[row['Job Class']] = float(row['Percentage'])
randomJob(finalDict)
|
ba2dc5c2d665448683f402fd84026579beafca8e | GgunHo/- | /almostIncreasingSequence.py | 635 | 3.515625 | 4 | def almostIncreasingSequence(sequence):
a = 0
b = 0
for i in range(len(sequence)-1):
if sequence[i] >= sequence[i+1] :
a += 1
for j in range(len(sequence)-2):
if sequence[j] >= sequence[j+2]:
b += 1
return (a <= 1 | b<=1)
'''리스트내에서 숫자 하나를 제외하면 증가수열이 되는가?
처음 for문에서 바로 옆자리와 비교하여 작은 수이면 a 에 +1
다음 for문에서 옆옆자리와 비교하여 작은 수 이면 b에 +1
최종적으로 a혹은 b가 1 이하인가'''
|
0182b36c9d6ff21780c50c8c47bbcf97758776a6 | supermikol/coursera | /Algorithm Toolbox/Week 2/fibonacci_last_digit/fibonacci_last_digit.py | 392 | 3.921875 | 4 | # Uses python3
import sys
def get_fibonacci_last_digit(n):
if n == 0:
return 0
fib_array = [0]*(n+1)
fib_array[1] = 1
for i in range(2,n+1):
fib_array[i] = (fib_array[i-1] + fib_array[i-2]) % 10
return fib_array[n]
# write your code here
# return 0
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(get_fibonacci_last_digit(n))
|
fdff77dce837fd1464c05f2e2811df24eb62b16b | Jiayichenn/GamesTheory | /10to1/game.py | 1,815 | 4.0625 | 4 | import random
import recursion
def check_win(current_position):
if current_position == 0:
return True
else:
return False
def check_valid_move(current_position, move):
move = int(move)
if move not in [1, 2]:
return False
if current_position - move < 0:
return False
return True
def start():
print("1 for single mode, 2 for double mode")
mode = int(input())
if mode not in [1, 2]:
mode = 1
order = [0, 1]
random.shuffle(order)
current_position = 10
turns = 0
while check_win(current_position) is False:
print("Current position is %d" % current_position)
if order[turns] == 0:
if mode == 1:
print("Player please enter move")
else:
print("Player1 please enter move")
move = int(input())
while check_valid_move(current_position, move) is False:
print("Please enter correct move")
if order[turns] == 1:
if mode == 2:
print("Player2 please enter move")
move = int(input())
while check_valid_move(current_position, move) is False:
print("Please enter correct move")
else:
moves = recursion.best_choice(current_position)
move = moves[0]
print("Computer move %d" % move)
current_position = current_position - move
turns = (turns + 1) % 2
turns = (turns - 1) % 2
if order[turns] == 0:
if mode == 1:
print("Player win")
else:
print("Player1 win")
else:
if mode == 1:
print("Computer win")
else:
print("Player2 win")
if __name__ == "__main__":
start()
|
bb2a3535e4c7bbbed38d470b1184b8bd10bc1209 | fraunhofer-iais/dlplatform | /DLplatform/parameters/kerasNNParameters.py | 6,784 | 3.5625 | 4 | from DLplatform.parameters import Parameters
import numpy as np
class KerasNNParameters(Parameters):
'''
Specific implementation of Parameters class for KerasNN learner
Here we know that parameters are list of numpy arrays. All the methods
for addition, multiplication by scalar, flattening and finding distance
are contained in this class.
'''
def __init__(self, weights : list):
'''
Initialize with setting the weights values
Parameters
----------
weights - List of weights values extracted from the network with Keras method get_weights
Returns
-------
None
'''
self.weights = weights
self.shapes = []
for arr in self.weights:
self.shapes.append(arr.shape)
def set(self, weights: list):
'''
Set the weights values
If needed to update weights inside of an existing parameters object
Parameters
----------
weights - List of weights values extracted from the network with Keras method get_weights
Returns
-------
None
Exception
---------
ValueError
when weights are not a list or elements of the weights list are not numpy arrays
'''
if not isinstance(weights, list):
raise ValueError("Weights for KerasNNParameters should be given as list of numpy arrays. Instead, the type given is " + str(type(weights)))
for arr in weights:
if not isinstance(arr, np.ndarray):
raise ValueError("Weights for KerasNNParameters should be given as list of numpy arrays. Instead, one element of list is of type " + str(type(arr)))
self.weights = weights
self.shapes = []
for arr in self.weights:
self.shapes.append(arr.shape)
# to use it inline
return self
def get(self) -> list:
'''
Get the weights values
Returns
-------
list of numpy arrays with weights values
'''
return self.weights
def add(self, other):
'''
Add other parameters to the current ones
Expects that it is the same structure of the network
Parameters
----------
other - Parameters of the other network
Returns
-------
None
Exception
---------
ValueError
in case if other is not an instance of KerasNNParameters
in case when the length of the list of weights is different
Failure
in case if any of numpy arrays in the weights list have different length
'''
if not isinstance(other, KerasNNParameters):
error_text = "The argument other is not of type" + str(KerasNNParameters) + "it is of type " + str(type(other))
self.error(error_text)
raise ValueError(error_text)
otherW = other.get()
if len(self.weights) != len(otherW):
raise ValueError("Error in addition: list of weights have different length. This: "+str(len(self.weights))+", other: "+str(len(otherW))+".")
for i in range(len(otherW)):
self.weights[i] = np.add(self.weights[i], otherW[i])
def scalarMultiply(self, scalar: float):
'''
Multiply weight values by the scalar
Returns
-------
None
Exception
---------
ValueError
in case when parameter scalar is not float
'''
if not isinstance(scalar, float):
raise ValueError("Scalar should be float but is " + str(type(scalar)) + ".")
for i in range(len(self.weights)):
self.weights[i] *= scalar
def distance(self, other) -> float:
'''
Calculate euclidian distance between two parameters set
Flattens all the weights and gets simple norm of difference
Returns
-------
distance between set of weights of the object and other parameters
Exception
---------
ValueError
in case the other is not KerasNNParameters
in case when length of the list of weights is different
Failure
in case when flattened vecrtors are different by length
'''
if not isinstance(other, KerasNNParameters):
error_text = "The argument other is not of type" + str(KerasNNParameters) + "it is of type " + str(type(other))
self.error(error_text)
raise ValueError(error_text)
otherW = other.get()
if len(self.weights) != len(otherW):
raise ValueError("Error in addition: list of weights have different length. This: "+str(len(self.weights))+", other: "+str(len(otherW))+".")
w1 = self.flatten()
w2 = other.flatten() #instead of otherW, because otherW is of type np.array instead of paramaters
dist = np.linalg.norm(w1-w2)
return dist
def flatten(self) -> np.ndarray:
'''
Get the flattened version of weights
Returns
-------
numpy array of all the layers weights flattenned and concatenated
'''
flat_w = []
for wi in self.weights:
flat_w += np.ravel(wi).tolist()
return np.asarray(flat_w)
def getCopy(self):
'''
Creating a copy of paramaters with the same weight values as in the current object
Returns
-------
KerasNNParameters object with weights values from the current object
'''
newWeights = []
for arr in self.weights:
newWeights.append(arr.copy())
newParams = KerasNNParameters(newWeights)
return newParams
def toVector(self)->np.array:
'''
Implementations of this method returns the current model parameters as a 1D numpy array.
Parameters
----------
Returns
-------
'''
return self.flatten()
def fromVector(self, v:np.array):
'''
Implementations of this method sets the current model parameters to the values given in the 1D numpy array v.
Parameters
----------
Returns
-------
'''
currPos = 0
newWeights = []
for s in self.shapes: #shapes contains the shapes of all weight matrices in the model
n = np.prod(s) #the number of elements n the curent weight matrix
arr = v[currPos:currPos+n].reshape(s)
newWeights.append(arr.copy())
currPos = n
self.set(newWeights)
|
61cb96c18341e50047f4ac6937d222a4c1e4aa2f | bsraya/ds-and-algo-python | /is_array_sorted.py | 329 | 3.921875 | 4 | def isArraySorted(array):
if len(array) == 1:
return True
else:
return array[0] <= array[1] and isSorted(array[1:])
def isSorted(array):
if array == sorted(array):
return True
else:
return False
A = [9, 6, 3, 1]
B = [1, 2, 3, 4]
print(isArraySorted(A))
print(isArraySorted(B))
|
c8d02af76f3c6f113643b81b45ef211715de8615 | ranitdey/customer-invitation-application | /src/lib/utils/sorting.py | 477 | 3.59375 | 4 | import logging
class Sorting:
@staticmethod
def sort_customers(records, ascending: bool):
"""
Sorts the given List based on user_id attribute of Customer object.
:param records: List of Customer objects
:param ascending: Will the sorting happen on ascending order or descending order
:return:
"""
logging.warning("Sorting Customer objets")
records.sort(key=lambda x: x.user_id, reverse=not ascending)
|
a3319ad9c3dc8218c85bebf8c5aa1c7e070bf729 | rwieckowski/project-euler-python | /euler293.py | 834 | 3.6875 | 4 | """
An even positive integer N will be called admissible if it is a power
of 2 or its distinct prime factors are consecutive primes
The first twelve admissible numbers are 24681216182430323648
If N is admissible the smallest integer M gt 1 such that NM is prime
will be called the pseudoFortunate number for N
For example N630 is admissible since it is even and its distinct prime
factors are the consecutive primes 235 and 7
The next prime number after 631 is 641 hence the pseudoFortunate
number for 630 is M11
It can also be seen that the pseudoFortunate number for 16 is 3
Find the sum of all distinct pseudoFortunate numbers for admissible
numbers N less than 10<sup>9</sup>
"""
def euler293():
"""
>>> euler293()
'to-do'
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod() |
d16168bbb521a6ed2ffd39200e0120bf0dfbaa50 | comorina/Ducat_class_code | /p149.py | 120 | 3.59375 | 4 | x=10
y=20
def add():
global x,y
x=5
y=6
print(x+y)
def mul():
print(x*y)
add()
mul()
|
0d21a0ba454c53bce2a9fce4cc6bbd8519460c80 | effyhuihui/leetcode | /Depth_First_Search/restoreIPAddress.py | 1,999 | 3.8125 | 4 | __author__ = 'effy'
# -*- coding: utf-8 -*-
'''
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
一个有效的IP地址由4个数字组成,每个数字在0-255之间。对于其中的2位数或3位数,不能以0开头
所以对于以s[i]开头的数字有3种可能:
1. s[i]
2. s[i : i+1],s[i] !=0时
3. s[i : i+2],s[i] != 0,且s[i : i+2] <= 255
'''
class Solution:
# @param {string} s
# @return {string[]}
def restoreIpAddresses(self, s):
res = []
def dfs(path, remain):
if remain == '':
if len(path) == 4:
res.append('.'.join(path))
else:
if len(path) < 4:
for i in range(1,min(4,len(remain)+1)):
## ensure even if the first char is 0, it will at least
## have one round of recursion
if int(remain[:i]) <= 255:
dfs(path+[remain[:i]],remain[i:])
if int(remain[0]) == 0:
break
dfs([],s)
return res
class Solution_secondround:
# @param {string} s
# @return {string[]}
def restoreIpAddresses(self, s):
res = []
l = len(s)
def dfs(index,path):
if len(path) == 4:
if index == l:
res.append('.'.join(path))
elif index<l:
for i in range(min(3,l-index+1)):
part = s[index:index+i+1]
if i == 0:
dfs(index+1, path+[part])
else:
if s[index] != '0' and int(part) <= 255:
dfs(index+i+1, path+[part])
dfs(0,[])
return res
x = Solution()
print x.restoreIpAddresses("0000")
|
e922b4c2adf4c8933df4651fd286ad9598217b2a | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_02/Fabio02_Parte_a/f2_a_q24_raizes.py | 638 | 3.875 | 4 | def main():
a = int(input('Digite o valor de "a": '))
b = int(input('Digite o valor de "b": '))
c = int(input('Digite o valor de "c": '))
delta = calcular_delta(a, b, c)
raizes(a, b, delta)
def calcular_delta(a, b, c):
d = b**2 - 4 * a * c
return d
def raizes(a, b, delta):
if delta > 0:
x1 = (-b + delta**(1/2))/(2 * a)
x2 = (-b - delta**(1/2))/(2 * a)
print(f'As raízes da função são {x1} e {x2}.')
elif delta == 0:
x = -b/(2 * a)
print(f'A raiz da função é {x}.')
else:
print('A função não possui raízes reais.')
main()
|
3639384fa01cf033069e23f1c58de27f5639accb | gabriellaec/desoft-analise-exercicios | /backup/user_069/ch28_2019_08_26_13_17_00_060871.py | 186 | 3.671875 | 4 | v = float(input('Qual a velocidade? ')
if 80>v:
print('Não foi multado')
elif v>80:
multa == (v-80)*5
print('A multa foi de {0:.2f}'.format(multa)) |
3d7dd04fc1c75d930e4618eaa234175f2d64c775 | ninaadjoshi93/artificial_intelligence_projects | /assignment_1/problem2/assign.py | 13,093 | 4.09375 | 4 | #!/usr/bin/env python
# put your group assignment problem here!
# This is problem 2 - where you need to assign members to team in such a way that it would lower the time taken by
# the grader to grade the assignment.
# Have discussed on a high level with saurabh agrawal but no code or design was shared among us.
'''
Abstraction:
Here for each iteration, based on the input configuration which is possible grouping of users in a team
i.e A state, we are finding the total cost for this current state along with cost of each person when kept alone.
For example: if n students give the survey
The initial configuration is: [[nth user][nth - 1 user][nth - 2 user]....[]]
So for 4 students intial configuration will be : [[user1][user2][user3][user4]]
This is an input to the cost function and we find the total cost for the state and cost of each user.
Based on result, the user with max cost, we try to place that user with other users in such a way that the overall
cost might be reduced and a team of size n or 3 might be created.
Placing the removed user with each other team, we create a list of all possible states and pick the one which has the
least cost.
Once the user is placed in another team, we assign that configuration as the best one obtained till now and try to place
another user in the above achieved configuration in a way the total cost gets reduced.
We keep on trying to do the same thing till every user has been taken into consideration once. i.e May be assigned in
a particular team or might be kept alone.
Initial State: A team configuration where in each user belongs to exactly one team. So here the initial teams equal to
the number of students who have given the survey
State Space: Possible team configurations from the current configurations
Goal State: Every user belongs to a team only once and is not present in more than one team along with the cost for the
team to be as low as possible.
successor function: Each user removed based on the cost function, the possible arrangement of the user with respect to
other teams
Cost: For each configuration, we find the total grading time based on input k, m and n values based on the time for
time size, desired members, undesired members for each user preference.
'''
import warnings
import sys
import copy
# This method loads the data from the file and creates a dictionary of keys which are usernames
# and list of survey answers given by each student where the 1st element is the team preference size followed by
# desired members followed by undesired member
# If the file is not found, then it throws and Exception and prints the appropriate message
def load_data(file):
try:
file = open(file,"r")
dict = {}
for line in file:
data = line.split();
dict[data[0]] = data[1:]
return dict
except IOError:
print "File not found. Please provide valid file name"
exit(0)
#This method creates a list of all the usernames from the dictionary of survey results
def create_username(dict):
username_list = []
for username in dict:
username_list.append(username)
return username_list
# This method creates an initial configuration of the teams where in each member is assigned in team of size 1 and total
# number of groups equal the number of student to start with.
def create_initial_teams(dict):
username_list = []
for username in dict:
username_list.append([username])
return username_list
# This method remove the element which has the maximum score i.e the maximum time from the input dictionary.
# The dictionary has keys as to time and values as list of usernames which take that much amount of time.
# This sorts the keys and removes the last element which is a username of the student
# Reference : https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python
def remove_unhappy_user(dict):
key_list = dict.keys()
key_list.sort()
time = key_list.pop()
received_username_list = dict[time]
for user in received_username_list:
return user
# This method calculates the total time taken to grade the assignment based on the groups created and k m and n values
# The inputs are dictionary of survey answers, the groups configuration as List of List where each list is one team
# username list which has the usernames which have not be considered for grouping
def calculate_time(dict,teams,username,k,m,n):
dict_of_time_to_student = {}
total_time = 0
team_size_count = 0
time_for_wanted_students = 0
time_for_unwanted_student = 0
number_of_groups = len(teams)
# the number of teams equal the number of groups, so multiplying ito k times
time_wasted_for_checking = k*number_of_groups
# looping in all the teams
for team in teams:
# number of students assigned in one team is team_size
team_size = len(team)
#looping on each student in the team to finds how much time one student takes
for student in team:
student_preference = int(dict[student][0])
team_preference_count = 0
# student preference doesn't match with its assigned team size, then add 1 to time
if student_preference != 0 and student_preference != team_size:
team_preference_count = 1
team_size_count+=team_preference_count
#Student' s desired team members
student_wants_to_team_list = dict[student][1].split(",")
# Reference: https://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists
# finding the number of students common in the student's preference vs student's assigned team
common_list_for_needed = list(set(team).intersection(student_wants_to_team_list))
length_of_desired_students = len(common_list_for_needed)
# if the student gave no desired team size
length_of_student_wanted_list = 0 if(student_wants_to_team_list[0] == '_') \
else len(student_wants_to_team_list)
# number of students did not be a part of the student's desired team
number_of_students_did_not_get = length_of_student_wanted_list - length_of_desired_students
time_wasted_desired_student = number_of_students_did_not_get*n
time_for_wanted_students+=time_wasted_desired_student
# Student's undesired team members
student_does_not_want_in_team = dict[student][2].split(",")
lengthOfStudentNotWantedList = 0 if (student_does_not_want_in_team[0] == '_') \
else len(student_does_not_want_in_team)
# finding the number of students common in the student's undesired list vs student's assigned team
common_list_for_not_needed = list(set(team).intersection(student_does_not_want_in_team))
# number of undesired students which became part of student's desired team
number_of_student_not_wanted = len(common_list_for_not_needed)
time_wasted_for_undesired_student = number_of_student_not_wanted*m
time_for_unwanted_student+= time_wasted_for_undesired_student
# Calculating time wasted for each user based on its preference, desired members and undesired members
time_for_each_student = team_preference_count + time_wasted_desired_student + \
time_wasted_for_undesired_student
# creating a dictionary of key value pairs where key is the time taken by the students and values is the
# list of users which take the same time
for rem_student_list in username:
student_name = rem_student_list
if student_name == student:
dict_of_time_to_student.setdefault(time_for_each_student, [])
dict_of_time_to_student[time_for_each_student].append(student)
total_time = time_wasted_for_checking + team_size_count + time_for_wanted_students + time_for_unwanted_student
# returning a dictionary of time to student with the total cost
return dict_of_time_to_student, total_time
# This method creates the configuration by placing the removed user with each other combinations except with itself and
# generates a list of different team configurations with respect to the removed user
# input to the function: name of the user to be placed
# input to the function: configuration
# for example : consider 4 students giving the survey : djcran , kapadia, fan6 and chen464
# input configuration was [djcran][kapadia,fan6][chen464] and user is chen464
# this method will create new configurations as
# first conf: [djcran, chen464][kapadia,fan6]
# second conf: [djcran][kapadia,fan6,chen464]
# and appends them to the final list
def form_team_combination(removed_user, list_of_teams):
new_list = []
copy_of_list_of_team = copy.deepcopy(list_of_teams)
for list_number in range(len(copy_of_list_of_team)):
temp = []
if removed_user not in copy_of_list_of_team[list_number]:
temp.append(copy.deepcopy(copy_of_list_of_team[list_number]))
for j in range(len(copy_of_list_of_team)):
if j != list_number and removed_user not in copy_of_list_of_team[j]:
temp.append(copy_of_list_of_team[j])
if len(temp[0]) < 3:
temp[0].append(removed_user)
else:
temp.append([removed_user])
new_list.append(temp)
return new_list
# this method removes the username from the available usernames based on the username which was assigned a team
# input: username - name of the student
# input_team - the configuration
# username_list - the list of usernames
def remove_element_from_list(username, input_team, username_list):
copy_of_user_list = copy.deepcopy(username_list)
for team in input_team:
if username in team:
for each_user in team:
for user in username_list:
if user == each_user:
copy_of_user_list.remove(user)
return copy_of_user_list
# prints the final selected configuration as one line per team followed by total time on the last time
def print_output(final_team_conf, time):
return "\n".join([" ".join([user for user in team]) for team in final_team_conf]) +"\n"+ str(time)
# main function
if __name__=="__main__":
warnings.filterwarnings('ignore')
# if len of argument is not 5 then incorrect arguments provided
if len(sys.argv) != 5:
print "Incorrect argument provided"
else:
# reading the inputs from command-line
fileName = sys.argv[1]
res = load_data(fileName)
k = int(sys.argv[2])
m = int(sys.argv[3])
n = int(sys.argv[4])
# assigning intial cost as the maximum cost
max_cost = sys.maxint
# creating username list
list_of_username = create_username(res)
# creating initial team configuration where each username is in one team
initial_team_configuration = create_initial_teams(res)
#looping until the username list doesn't become 0
while len(list_of_username) > 0:
# returns the dictionary of time to student names, and total time for this configuration
dict_of_cost_of_each_user, totalCost = calculate_time(res,initial_team_configuration,list_of_username,k,m,n)
# this method removes the most unhappy user based on the map and tries to fit him in one team
removed_user = remove_unhappy_user(dict_of_cost_of_each_user)
# compares the newly generated cost with the previous best cost
max_cost = min(max_cost,totalCost)
# creates a possible states of different team configurations based on the removed user i.e the most unhappy
new_formed_list = form_team_combination(removed_user, initial_team_configuration)
# loops in all possible team configurations and selected the one with least cost
selected_team = []
for each_team_combination in new_formed_list:
# calculate total cost and time to student dictionary
dict_of_cost_of_each_user, totalCost = calculate_time(res, each_team_combination, list_of_username, k, m, n)
# if total cost is less than previous best cost
if totalCost < max_cost:
max_cost = totalCost
selected_team = each_team_combination
initial_team_configuration = selected_team
# remove the user from the user list which was assigned a team
list_of_username = remove_element_from_list(removed_user, selected_team, list_of_username)
# final team configuration
final_team_conf = initial_team_configuration
# print the output
print print_output(final_team_conf,max_cost) |
59ed0f1d68e962386d4a95034395dbadbd4c3dbc | Machina123/Polygon | /polygons.py | 7,615 | 3.6875 | 4 | import math
from abc import ABC, abstractmethod
from params import Length, Colour, Ratio, Angle, MathHelpers
from gui import GUI
import constants
class ConvexPolygon(ABC):
fill_colour = Colour(name="Fill colour")
outline_colour = Colour(name="Outline colour")
@abstractmethod
def __init__(self):
self.fill_colour = "white"
self.outline_colour = "black"
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
@abstractmethod
def draw(self, scale=1):
pass
def set_fill_colour(self, colour):
self.fill_colour = colour
def set_outline_colour(self, colour):
self.outline_colour = colour
class Triangle(ConvexPolygon):
len_base = Length(name="Length of base")
len_height = Length(name="Height of triangle")
ratio_h_div = Ratio(name="Ratio of base intersection with height")
def __init__(self, len_base, len_height, ratio_h_div):
super().__init__()
self.len_base = len_base
self.len_height = len_height
self.ratio_h_div = ratio_h_div
def area(self):
return self.len_base * self.len_height * 0.5
def perimeter(self):
side_b = math.sqrt(((self.len_base * self.ratio_h_div) ** 2) + (self.len_height ** 2))
side_c = math.sqrt(((self.len_base * (1 - self.ratio_h_div)) ** 2) + (self.len_height ** 2))
return self.len_base + side_b + side_c
def draw(self, scale=1):
scaled_base = self.len_base * scale
scaled_height = self.len_height * scale
coords = [(0, 0), (scaled_base, 0), (self.ratio_h_div * scaled_base, scaled_height)]
GUI.draw_polygon(self, coords, scale)
pass
class ConvexQuadrilateral(ConvexPolygon):
len_diag1 = Length(name="Length of first diagonal")
len_diag2 = Length(name="Length of second diagonal")
ratio_intersect_diag1 = Ratio(name="Ratio of diagonals intersection (for 1st diag.)")
ratio_intersect_diag2 = Ratio(name="Ratio of diagonals intersection (for 2nd diag.)")
angle_btwn_diagonals = Angle(name="Angle between diagonals")
def __init__(self, len_diag1, len_diag2, ratio_intersect_diag1, ratio_intersect_diag2, angle_btwn_diagonals):
super().__init__()
self.len_diag1 = len_diag1
self.len_diag2 = len_diag2
self.ratio_intersect_diag1 = ratio_intersect_diag1
self.ratio_intersect_diag2 = ratio_intersect_diag2
self.angle_btwn_diagonals = angle_btwn_diagonals
def area(self):
return 0.5 * self.len_diag1 * self.len_diag2 * math.sin(self.angle_btwn_diagonals)
def perimeter(self):
side_a = MathHelpers.cosine_law(self.len_diag1 * self.ratio_intersect_diag1,
self.len_diag2 * self.ratio_intersect_diag2, self.angle_btwn_diagonals)
side_b = MathHelpers.cosine_law(self.len_diag1 * (1 - self.ratio_intersect_diag1),
self.len_diag2 * self.ratio_intersect_diag2,
math.pi - self.angle_btwn_diagonals)
side_c = MathHelpers.cosine_law(self.len_diag1 * self.ratio_intersect_diag1,
self.len_diag2 * (1 - self.ratio_intersect_diag2), self.angle_btwn_diagonals)
side_d = MathHelpers.cosine_law(self.len_diag1 * (1 - self.ratio_intersect_diag1),
self.len_diag2 * (1 - self.ratio_intersect_diag2),
math.pi - self.angle_btwn_diagonals)
return side_a + side_b + side_c + side_d
def draw(self, scale=1):
scaled_diag1 = self.len_diag1 * scale
scaled_diag2 = self.len_diag2 * scale
points = list()
point_a = (0,0)
point_b = GUI.get_rotated_point(0, scaled_diag2 * self.ratio_intersect_diag2,
(math.pi/2) - self.angle_btwn_diagonals)
point_c = (scaled_diag1, 0)
point_d = GUI.get_rotated_point(0, (-1)*(scaled_diag2 * (1-self.ratio_intersect_diag2)),
(math.pi/2) - self.angle_btwn_diagonals)
points.append(point_a)
points.append((point_b[0] + self.ratio_intersect_diag1 * scaled_diag1, point_b[1]))
points.append(point_c)
points.append((point_d[0] + self.ratio_intersect_diag1 * scaled_diag1, point_d[1]))
GUI.draw_polygon(self, points, scale)
class RegularPentagon(ConvexPolygon):
side = Length(name="Side of regular pentagon")
def __init__(self, side):
super().__init__()
self.side = side
def area(self):
return 0.25 * 5 * self.side * self.side * (1 / math.tan(0.2 * math.pi))
def perimeter(self):
return 5 * self.side
def draw(self, scale=1):
scaled_side = self.side * scale
circumcircle_radius = scaled_side * (1/math.sqrt(3 - constants.GOLDEN_RATIO))
points = list()
for i in range(5):
points.append(GUI.get_rotated_point(circumcircle_radius, 0, i * 0.4 * math.pi))
GUI.draw_polygon(self, points, scale)
class RegularHexagon(ConvexPolygon):
side = Length(name="Side of regular hexagon")
def __init__(self, side):
super().__init__()
self.side = side
def area(self):
return 0.5 * 3 * self.side * self.side * math.sqrt(3)
def perimeter(self):
return 6 * self.side
def draw(self, scale=1):
scaled_side = self.side * scale
points = list()
for i in range(6):
points.append(GUI.get_rotated_point(scaled_side, 0, i * (math.pi / 3)))
GUI.draw_polygon(self, points, scale)
class RegularOctagon(ConvexPolygon):
side = Length(name="Side of regular octagon")
def __init__(self, side):
super().__init__()
self.side = side
def area(self):
return 2 * (1 + math.sqrt(2)) * self.side * self.side
def perimeter(self):
return 8 * self.side
def draw(self, scale=1):
scaled_side = self.side * scale
circumcircle_radius = scaled_side * math.sqrt((2+math.sqrt(2))/2)
points = list()
for i in range(8):
points.append(GUI.get_rotated_point(circumcircle_radius, 0, i * 0.25 * math.pi))
GUI.draw_polygon(self, points, scale)
class IsoscelesTriangle(Triangle):
def __init__(self, len_base, len_height):
super().__init__(len_base, len_height, 0.5)
class EquilateralTriangle(Triangle):
def __init__(self, len_side):
super().__init__(len_side, (len_side * math.sqrt(3)) / 2, 0.5)
class Parallelogram(ConvexQuadrilateral):
side_a = Length(name="Longer side of parallelogram")
side_b = Length(name="Shorter side of parallelogram")
angle_btwn_sides = Angle(name="Angle between sides")
def __init__(self, side_a, side_b, angle_btwn_sides):
diag1 = math.sqrt(side_a**2 + 2*side_a*side_b*math.cos(angle_btwn_sides) + side_b**2)
diag2 = math.sqrt(side_a**2 - 2*side_a*side_b*math.cos(angle_btwn_sides) + side_b**2)
angle_diag = math.acos(((diag1/2)**2 + (diag2/2)**2 - side_b**2)/(2*(diag1/2)*(diag2/2)))
super().__init__(diag1, diag2, 0.5, 0.5, angle_diag)
class Kite(ConvexQuadrilateral):
def __init__(self, len_diag1, len_diag2, diag_ratio):
super().__init__(len_diag1, len_diag2, diag_ratio, 0.5, math.pi/2)
class Rhombus(Parallelogram):
def __init__(self, side, angle):
super().__init__(side, side, angle)
class Square(Rhombus):
def __init__(self, side):
super().__init__(side, math.pi/2) |
2e92b22bb19ec60a3912a2db1b74099cd448095e | tanmaymudholkar/project_euler | /1-49/nine.py | 545 | 3.8125 | 4 | #!/usr/bin/env python
import numpy
import math
set_of_squares=numpy.array([],dtype=int)
for i in range(1,1001):
set_of_squares=numpy.append(set_of_squares,i*i)
def is_part_of_triplet(a,b):
sumsq=a**2+b**2
if (sumsq in set_of_squares):
c=int(math.sqrt(sumsq))
return c
else:
return -1
for a in range(1,1000):
for b in range(a+1,1001):
c=is_part_of_triplet(a,b)
if (c>0 and a+b+c==1000):
print "(",a,",",b,",",c,")"
print a*b*c
quit()
|
921214260646729c0dfeae80400111976195acc9 | zhlthunder/python-study | /python 之路/section1_基础及数据结构/基本数据类型_数据运算.py | 761 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#author:zhl
# >>> a=10
# >>> b=20
# >>> a+b
# 30
# >>> a-b
# -10
# >>> a*b
# 200
# >>> a/b
# 0.5
# >>>
# >>> a=5
# >>> b=2
# >>> a%b
# 1
# >>>
# @@求次方
# >>> 2**2
# 4
# >>>
# @@求整除的商
# >>> 9//2
# 4
# >>>
# @@等于和不等于
# >>> 2==2
# True
# >>> 2!=1
# True
# >>>
# >>> 2==1 and 3==3
# False
# >>> 2==1 or 3==3
# True
# >>>
##使用not 可以直接对一个条件取反
# a=1
# if a > 2:
# print("ok")
#
# if not a > 2:
# print("ok")
# @@成员运算符, in 和 not in
# a=[1,2,33]
# if 3 in a:
# print("3333")
# if 3 not in a:
# print("44444")
# @@身份运算符 is
# a=[11,22,44]
# print(type(a) is list)
# @@二进制运算略,需要时查询一下就可以了
|
bcd9e58f6db709b8051c7522d1a46ffcfb9b368b | zzxmona/pythontrain | /小飞/Lesson3/Lesson3.py | 2,236 | 3.828125 | 4 | # Section0 开场
print("-"*30 + "Begin Section 0 开场" + "-"*30)
print("这是Python的第三次课程,主要讲Pandas第三方库,内容主要包括:")
print("1.Series\n2.DataFrame")
print("-"*30 + "End Section 0 开场" + "-"*30)
print('\n')
#首先需要安装和引入pandas
import pandas as pd
# Series
print("-"*30 + "Begin Section 1 Series" + "-"*30)
# Series是一种类似于一维数组的对象,由一组数据和一组与之相关联的索引组成
# 默认的索引从0开始
print("传入列表,默认索引:")
S1 = pd.Series(['a','b','c','d'])
print(S1)
# 传入索引
print("传入列表,自定义索引:")
S2 = pd.Series(['a','b','c','d'],index = [1,2,3,4])
print(S2)
# 传入字典,key为索引,value为数据
print("传入字典:")
S3 = pd.Series({1:'a',2:'b',3:'c',4:'d'})
print(S3)
# index获得索引
print("index 获得索引:")
print(S1.index)
print(S2.index)
# values获得值
print("values 获得值:")
print(S1.values)
print(S2.values)
print("-"*30 + "End Section 1 Series" + "-"*30)
print("\n")
# DataFrame
print("-"*30 + "Begin Section 2 DataFrame" + "-"*30)
# DataFrame是由一组数据与一对索引(行索引和列索引)组成的表哥型数据结构
# 默认的行索引和列索引都是从0开始
print("传入列表,默认行索引和列索引:")
df1 = pd.DataFrame(['a','b','c','d'])
print(df1)
print("传入一个嵌套列表:")
df2 = pd.DataFrame([['a','A'],['b','B'],['c','C'],['d','D']])
print(df2)
print("传入一个嵌套列表,里面是元组:")
df2 = pd.DataFrame([('a','A'),('b','B'),('c','C'),('d','D')])
print(df2)
print("指定行列索引:")
df3 = pd.DataFrame([['a','A'],['b','B'],['c','C'],['d','D']],columns = ["小写","大写"],index = ["一","二","三","四"])
print(df3)
print("传入字典:")
df4 = pd.DataFrame({"小写":["a","b","c","d"],"大写":["A","B","C","D"]},index = ["一","二","三","四"])
print(df4)
# columns 获取DataFrame的列
print("获取DataFrame的列:")
print(df2.columns)
print(df3.columns)
# index 获取DataFrame的行
print("获取DataFrame的行:")
print(df2.index)
print(df3.index)
# 获取 DataFrame的值 后续再讲
print("-"*30 + "End Section 2 DataFrame" + "-"*30)
print('\n') |
71e085f9f38985f7e270470ef4f7c66a7abad2de | huyuyu/lpthw | /ex25_usetest.py | 886 | 3.96875 | 4 | # import ex25 # 引入自定义类
from ex25 import * # 在下文中使用ex25中相关方法时,无需在点名ex25.?,可直接对函数进行使用
sentence = "All good things come to those who wait."
words = ex25.break_words(sentence)
print("words break_words : ", words)
sorted_words = ex25.sort_words(words)
print("sorted_words :", sorted_words)
ex25.print_first_word(words)
ex25.print_last_word(words)
print("words pop first and last : ", words)
ex25.print_first_word(sorted_words)
ex25.print_last_word(sorted_words)
print("sorted_words pop first and last : ", sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print("first to words, second to sort :" , sorted_words)
ex25.print_first_and_last(sentence)
ex25.print_first_and_last_sorted(sentence)
# Study Drills
# 在终端进入python,import ex25 后,help(ex25) 可以查看到关于类的详细情况 |
4d836567918a2bbbce29801713b804b701159451 | khalidumar098/CPS-3320 | /Hangman/hangman.py | 1,001 | 3.984375 | 4 | # Hangman game!
# Assume the answer is "hangman"
A = ['h','a','n','g','m','a','n']
L = ['_','_','_','_','_','_','_']
play = True
turns = 6
while play == True and turns > 0:
# Ask the user to guess a letter
letter = str(input("Guess a letter: "))
#if letter does not match, give an error bad guess
if letter not in A:
turns -= 1
print("Bad guess!")
print("You have", + turns, 'more turns!')
if turns == 0:
print("You lose the game!")
# Check to see if that letter is in the Answer
i = 0
for currentletter in A:
# If the letter the user guessed is found in the answer,
# set the underscore in the user's answer to that letter
if letter == currentletter:
L[i] = letter
i = i + 1
# Display what the player has thus far (L) with a space
# separating each letter
print(' '.join(str(n) for n in L))
# Test to see if the word has been successfully completed,
# and if so, end the loop
if A == L:
play = False
print("GREAT JOB!") |
6714de3102a94bd24b725fbf2c7799d051def391 | LeetCodeMio/LeetCodeProblems | /AcRate/187. 761. Special Binary String .py | 706 | 3.75 | 4 | # The number of 0's is equal to the number of 1's.
# 0和1的数量相等
# Every prefix of the binary string has at least as many 1's as 0's.
# 任何前缀中 1的数量 >= 0的数量
# 分治 括号山
# 对括号山进行递归处理
# 在递归体中对已经递归处理好的子括号山按字典序降序排列
class Solution :
def makeLargestSpecial(self, S) :
def f(s) :
if len(s) == 2 : return s
ret = []
level = 0
start = 1
for i in range(1, len(s) - 1) :
level += 1 if s[i] == '1' else -1
if level == 0 :
ret.append(f(s[start : i+1]))
start = i+1
return '1' + ''.join(sorted(ret, reverse = True)) + '0'
return f('1' + S + '0')[1:-1] |
ecb11613361bdd800d469ef0c612a7ed128fba0d | udoy382/Module | /re_1.py | 2,763 | 3.78125 | 4 | # Code With Harry / Regular Expressions
import re
mystr = '''Hello world, I am a Saifur +8801782-668254 .Rahman Udoy, i aiiii want to learn cybersecurity.
and i am from bangladesh , i am a python programmer. 01782-299436, 1.1.1, 2.2.2, 333, 45, 436
haha hehe huhu 2929, 5454 helo bangladesh India 66-66 hola'''
# all functions = findall, search, split, sub, finditer
# search any carecture in string
'''
# print(r"\n")
patt = re.compile(r'learn')
matches = patt.finditer(mystr)
for match in matches:
print(match)
print(mystr[50:55])
'''
# search [ . ] or any rarecture in string [ . ] meens all
'''
patt = re.compile(r'.Rahman')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# search which caructor first to start in this string [ ^ ] this meen which first carecture in this string
'''
patt = re.compile(r'^Hello')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# search which caructor end in this string [ $ ] this meen which end carecture in this string
'''
patt = re.compile(r'hola$')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# [ ai* ] meens a or all i and [ a*i* ] meens all [ a ] and all [ i ]
'''
patt = re.compile(r'ai*')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# see only ai
'''
patt = re.compile(r'ai+')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# see exject ai in this string
'''
patt = re.compile(r'ai{2}')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# see exject ai with makeing group, if im search 2 ai so im add 2 in [ {} ] this second bracket
'''
patt = re.compile(r'(ai){1}')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# show ai or show t [ | ] this meens [ or ]
'''
patt = re.compile(r'ai{1}|t')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# Spcial Sequences
# if Hello first word in this string os show without not [ \A ] meens which first word in this string
'''
patt = re.compile(r'\AHello')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# return all start word like cyber
'''
patt = re.compile(r'\bcyber')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# return all ending word like security
'''
patt = re.compile(r'security\b')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# search number or anything with desh [ - ] in string
'''
patt = re.compile(r'\d{5}-\d{6}')
matches = patt.finditer(mystr)
for match in matches:
print(match)
'''
# Exercise code...
patt = re.compile(r'\d{7}-\d{6}')
matches = patt.finditer(mystr)
for match in matches:
print(match) |
d2625e29c3f3a079a93788bc8c26358f1f444c47 | idnavid/pyknograms | /code/tools/teo/energy_operator.py | 807 | 3.65625 | 4 | #! /usr/bin/python
import numpy as np
def teager(x,first_diff=False):
"""
DESA-1 implementation
If first_diff is On (i.e. True), it means that the function
must also calculate the TEO of the first difference signal.
"""
y0 = np.multiply(x[1:-1],x[1:-1])-np.multiply(x[2:],x[0:-2])
# Since the since of y0 is two samples fewer than the original signal:
y0 = np.append(y0,np.array([0,0]))
if first_diff:
x_diff = x[1:]-x[:-1]
y1 = np.multiply(x_diff[1:-1],x_diff[1:-1])-np.multiply(x_diff[2:],x_diff[0:-2])
# The size of y1 is 3 samples fewer than x, 1 sample for x_diff and 2 samples for calculating the operator.
y1 = np.append(y1,np.array([0,0,0]))
return y0,y1
else:
return y0,np.array([])
|
c2420d67119022ffc1ecb734aa97f524b5b0fa7a | Anup-Toggi/python | /recurrsion/mirrored-right-triangle_number.py | 273 | 3.640625 | 4 | def f(n,i):
if n==0:
return
def g(t):
if t==0:
return
g(t-1)
print(t,end='')
f(n-1,i+1)
print(' '*i,sep='',end='')
g(n)
print()
n=int(input("enter a number: "))
i=0
f(n,i)
'''
output-
enter a number: 5
1
12
123
1234
12345
'''
|
88fb903bf4d9dbe3fa9547c23a7d283bb9240d14 | erickgnavar/exercism | /python/word-count/word_count.py | 254 | 3.5625 | 4 | from collections import Counter
def word_count(phrase):
if isinstance(phrase, bytes):
phrase = phrase.decode('utf-8')
s = ''.join([c if c.isalnum() or c.isspace() else ' ' for c in phrase])
return dict(Counter(s.lower().split()))
|
3f04525cb6b45211e7a71d58c4ec24d0a288dcc2 | audy/cd-hit-that | /src/dna.py | 1,519 | 3.515625 | 4 | '''
dnaobj.py
An object representing a FASTA or FASTQ record.
Austin Glenn Davis-Richardson
austingdr@gmail.com
Triplett Lab, University of Florida
'''
import string
_complement = string.maketrans('GATCRYgatcry','CTAGYRctagyr')
class Dna:
''' An object representing either a FASTA or FASTQ record '''
def __init__(self, header, sequence, quality = False):
self.header = header[1:]
self.sequence = sequence
self.quality = quality
if quality:
self.type = 'fastq'
else:
self.type = 'fasta'
def __str__(self):
''' returns a FASTA/Q formatted string '''
if not self.quality:
return ('>%s\n%s\n') % (self.header, self.seq)
else:
return('@%s\n%s\n+%s\n%s\n') % \
(self.header, self.seq, self.header, self.quality)
def __repr__(self):
return '<dnaobj.%s instance: %s>' % (self.type, self.header)
@property
def complement(self):
''' returns complement of sequence '''
return self.sequence.translate(_complement)
@property
def revcomp(self):
''' returns reverse complement of sequence '''
return self.complement()[::-1]
@property
def seq(self):
''' returns DNA sequence '''
return '\n'.join(self.sequence)
@property
def qual(self):
''' returns quality '''
return self.quality
@property
def nucqual(self):
''' returns ('sequence', 'quality') '''
return self.sequence, self.quality
|
073b2de86a95e19a47f1e2fae865b3b500eb2f5f | sudiptog81/ducscode | /YearII/SemesterIII/ProgrammingInPython/Practicals/strings/main.py | 2,368 | 4.28125 | 4 | '''
Write a menu driven program to perform the following on strings:
(a) Find the length of string.
(b) Return maximum of three strings.
(c) Accept a string and replace all vowels with "#"
(d) Find number of words in the given string.
(e) Check whether the string is a palindrome or not.
Written by Sudipto Ghosh for the University of Delhi
'''
def findLength():
c = 0
s = input('Enter a String: ')
for i in s:
c += 1
print('Length of String:', c)
def maxOfStrings():
maximum = ''
s1 = input('Enter String 1: ')
s2 = input('Enter String 2: ')
s3 = input('Enter String 3: ')
if s1 >= s2 and s1 >= s3:
maximum = s1
elif s2 >= s1 and s2 >= s3:
maximum = s2
else:
maximum = s3
print('Maximum of Three Strings:', maximum)
def replaceVowels():
s = input('Enter a String: ')
for i in s:
if i in 'aAeEiIoOuU':
s = s.replace(i, '#')
print('Modified String:', s)
def numberOfWords():
s = input('Enter a String: ')
c = 0
for i in s:
if i == ' ':
c += 1
print('Number of Words:', c + 1)
def isPalindrome():
f = True
s = input('Enter a String: ')
for i in range(0, len(s) // 2, 1):
if s[i] != s[len(s) - i - 1]:
f = False
print('String is not a Palindrome')
break
if f == True:
print('String is a Palindrome')
def main():
s = ''
s1 = ''
s2 = ''
s3 = ''
flag = 0
while True:
print('''
MENU
===================================================
(1) Find the length of string.
(2) Return maximum of three strings.
(3) Accept a string and replace all vowels with '#'
(4) Find number of words in the given string.
(5) Check whether the string is a palindrome or not.
(0) Exit
''')
c = int(input('Enter Choice: '))
if c == 1:
findLength()
elif c == 2:
maxOfStrings()
elif c == 3:
replaceVowels()
elif c == 4:
numberOfWords()
elif c == 5:
isPalindrome()
elif c == 0:
break
input('Press any key to continue...')
if __name__ == '__main__':
main()
|
393724a9ae95dbfddb5471150763c0804f09dd4f | AAH20/100-redteam-projects | /Projects/0_TCP_server/client.py | 656 | 3.828125 | 4 | import socket
# Declaring and initializing local ip address and port to be used
localIP, localPort = "127.0.0.1", 65432
#creating a TCP/IP socket
TCPclientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCPclientSocket.connect((localIP, localPort))
clientMsg = input("Type your message for the server here: ")
data = bytes(clientMsg, "utf-8")
# send message to the server using TCP socket
print("Sending message to {0} port {1}".format(localIP, localPort))
TCPclientSocket.sendall(data)
#receiving reply from the server
dataFromServer = str(TCPclientSocket.recv(1024))
print("Message received from the server: ", str(dataFromServer))
|
95162eeb031cdb47a735199940b8f1bf30053278 | fengbaoheng/leetcode | /python/225.implement-stack-using-queues.py | 1,707 | 4.28125 | 4 | #
# @lc app=leetcode.cn id=225 lang=python3
#
# [225] 用队列实现栈
#
# https://leetcode-cn.com/problems/implement-stack-using-queues/description/
#
# algorithms
# Easy (55.93%)
# Total Accepted: 6.9K
# Total Submissions: 12.3K
# Testcase Example: '["MyStack","push","push","top","pop","empty"]\n[[],[1],[2],[],[],[]]'
#
# 使用队列实现栈的下列操作:
#
#
# push(x) -- 元素 x 入栈
# pop() -- 移除栈顶元素
# top() -- 获取栈顶元素
# empty() -- 返回栈是否为空
#
#
# 注意:
#
#
# 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty
# 这些操作是合法的。
# 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
# 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
#
#
#
class MyStack:
def __init__(self):
# list只能使用队列操作即入队:append()与出队:pop(0)
self.queue = []
def push(self, x: int) -> None:
self.queue.append(x)
for i in range(len(self.queue) - 1):
item = self.queue.pop(0)
self.queue.append(item)
def pop(self) -> int:
return self.queue.pop(0)
def top(self) -> int:
item = self.pop()
self.push(item)
return item
def empty(self) -> bool:
return len(self.queue) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
|
f99e5918b851c50635e47fdd8c6bfac062d17659 | dfialho/adventofcode-puzzles | /day03/day03_pt2.py | 3,006 | 4.21875 | 4 | from math import sqrt, ceil
def level(n: int) -> int:
"""
Returns the level for the given position.
The first square contains only 1 - the level 1
The second square contains value 2 to 9 - the level 3 (level 3)
The third square contains value 10 to 25 - the level 5
The fourth square contains value 26 to 49 - the level 7
"""
ra = sqrt(n)
r = int(ra)
if r % 2 == 0:
r += 1
elif ra > r:
r += 2
return r
def backward_square(n: int, i: int) -> int:
""" Computes the backward square """
# Can be simplified to: backward_i = (r(n) - 1) * (r(n) - 2 + i)
backward_i = (level(n) - 1) * (level(n) - 2) + (level(n) - 1) * i
if i == 3:
backward_i += 1
return backward_i
def corner_square(n: int, i: int) -> int:
if i == 0:
return pow((level(n) - 2), 2) + 1
else:
return backward_square(n, i - 1) + 1
def forward_square(n: int, i: int) -> int:
return corner_square(n, i) + 1
def side_index(n: int) -> int:
for i in range(4):
if n - backward_square(n, i) <= 0:
return i
return 3
def is_backward_square(n: int, i: int) -> bool:
return n == backward_square(n, i)
def is_corner_square(n: int, i: int) -> bool:
return n == corner_square(n, i)
def is_forward_square(n: int, i: int) -> bool:
return n == forward_square(n, i)
def diff(n: int, i: int) -> int:
return 1 + (level(n) - 2) // 2 * 8 + 2 * i
def backward_value(grid: list, n: int, i: int) -> int:
return grid[n - 1] + grid[n - diff(n, i)] + grid[n - diff(n, i) - 1]
def corner_value(grid: list, n: int, i: int) -> int:
return grid[n - 1] + grid[n - diff(n, i) + 1]
def forward_value(grid: list, n: int, i: int) -> int:
return grid[n - 1] + grid[n - 2] + grid[n - diff(n, i)] + grid[n - diff(n, i) + 1]
def middle_value(grid: list, n: int, i: int) -> int:
return grid[n - 1] + grid[n - diff(n, i) - 1] + grid[n - diff(n, i)] + grid[n - diff(n, i) + 1]
def backward_and_forward_value(grid: list, n: int, i: int) -> int:
return grid[n - 1] + grid[n - 2] + grid[n - diff(n, i)]
def value_function(n: int, i: int):
if is_corner_square(n, i):
return corner_value
elif is_forward_square(n, i) and is_backward_square(n, i):
return backward_and_forward_value
elif is_forward_square(n, i):
return forward_value
elif is_backward_square(n, i):
return backward_value
else:
return middle_value
def process(bound: int) -> int:
if bound == 1:
return 1
n = 3 # 'n' always holds the position in the spiral
grid = [None, 1, 1]
while True:
side_i = side_index(n)
square = value_function(n, side_i)
square_value = square(grid, n, side_i)
if square_value > bound:
return square_value
grid.append(square_value)
n += 1
def main():
print("Solution part 2:", process(368078))
if __name__ == '__main__':
main()
|
fa163a1e10005cd201a923725398008b08c56db2 | Sanmathi05/program | /basscatri.py | 91 | 3.6875 | 4 | no1,no2,no3=map(int,input().split())
if(no1!=no2!=no3):
print("yes")
else:
print("no")
|
14a0a983d60787710735fb1f52f2d7dd4e419fb6 | TeamAIoT/python-tutorial | /4.Python_조건문/실습코드/pr04_04.py | 149 | 3.953125 | 4 | n1=int(input())
n2=int(input())
if (n1+n2)>=10:
print("sum >= 10")
elif (n1+n2)>5:
print("5 < sum < 10")
else:
print("sum <= 5") |
16fbbbf3675930e9476b250631d1a013e9beb7aa | isbox/leet_code | /9.palindrome-number.py | 1,316 | 3.96875 | 4 | # -*- coding:utf-8 -*-
# @lc app=leetcode.cn id=9 lang=python3
#
# [9] 回文数
#
# https://leetcode-cn.com/problems/palindrome-number/description/
#
# algorithms
# Easy (55.88%)
# Total Accepted: 66.7K
# Total Submissions: 119.3K
# Testcase Example: '121'
#
# 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
#
# 示例 1:
#
# 输入: 121
# 输出: true
#
#
# 示例 2:
#
# 输入: -121
# 输出: false
# 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
#
#
# 示例 3:
#
# 输入: 10
# 输出: false
# 解释: 从右向左读, 为 01 。因此它不是一个回文数。
#
#
# 进阶:
#
# 你能不将整数转为字符串来解决这个问题吗?
#
#
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
elif x < 10:
return True
result = []
while(x > 0):
remainder = x % 10
result.append(remainder)
x = x // 10
for res in range(len(result) // 2):
if result[res] != result.pop():
return False
return True
|
cd603db612c1a66cfeda4c288340f1e88c775c95 | pyre/pyre | /tests/gsl.pkg/vector_min.py | 516 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2023 all rights reserved
#
"""
Find the minimum value in a vector
"""
def test():
# package access
import gsl
# make a vector and initialize it
v = gsl.vector(shape=100)
# prime
for index in range(v.shape): v[index] = 2*index+1
# find the min
small = v.min()
# check it
assert small == 1
# all done
return v
# main
if __name__ == "__main__":
test()
# end of file
|
c480e19abd214b4bb929d669ada4f85ee349b7c2 | pujahabibi/codingInterview | /Array_Strings/URLify.py | 284 | 3.90625 | 4 | """
write a method to replace all space in string with %20
"""
def URLifiy(input_str):
url = ""
for i in range(len(input_str)):
if input_str[i] == ' ':
url += "%20"
else:
url = url + input_str[i]
return url
print(URLifiy("Puja Ahmad Habibi")) |
07d8375c1e2f435c9693a83a127f59a643f0d693 | sheucke/Pythontutorial | /turtleGraphics.py | 1,645 | 3.921875 | 4 | import turtle
import random
from turtle import Turtle, Screen
colors = ['red', 'green', 'blue', 'yellow',
'pink', 'orange', 'purple', 'black', 'grey']
tim = turtle.Turtle()
tim.color('red')
tim.pensize(5)
tim.shape('turtle')
tim.forward(100)
tim.left(90)
tim.penup()
tim.forward(100)
tim.right(90)
tim.pendown()
tim.color('green')
tim.forward(100)
# set pen width
tim.width(5)
# Fill in shape with color
tim.begin_fill()
tim.circle(50)
tim.end_fill()
# square
for x in range(4):
tim.forward(100)
tim.right(90)
# random circles
for x in range(5):
randColor = random.randrange(0, len(colors))
tim.color(colors[randColor], colors[random.randrange(0, len(colors))])
rand1 = random.randrange(-300, 300)
rand2 = random.randrange(-300, 300)
tim.penup()
tim.setpos((rand1, rand2))
tim.pendown()
tim.begin_fill()
tim.circle(random.randrange(0, 80))
tim.end_fill()
jim = turtle.Turtle()
jim.speed(0)
jim.width(5)
def up():
jim.setheading(90)
jim.forward(100)
def down():
jim.setheading(270)
jim.forward(100)
def left():
jim.setheading(180)
jim.forward(100)
def right():
jim.setheading(0)
jim.forward(100)
def clickleft(x, y):
jim.color(random.choice(colors))
def clickright(x, y):
jim.color(random.choice(colors))
jim.stamp()
turtle.listen()
turtle.onscreenclick(clickleft, 1) # 1 for left mouse button
turtle.onscreenclick(clickright, 3) # 3 for right mouse button
# move with arrowkeys
turtle.onkey(up, 'Up')
turtle.onkey(down, 'Down')
turtle.onkey(left, 'Left')
turtle.onkey(right, 'Right')
turtle.mainloop()
# mouse input
|
a04b923266daa478c4c42dc4949b5cb0de8ba0ae | IJS1016/Algorithm | /Python/BOJ/brute_force/1620.py | 429 | 3.703125 | 4 | import sys
def scanf() :
return sys.stdin.readline().rstrip()
num, question = scanf().split(" ")
ordered_list = []
pocketmon_dict = {}
for i in range(int(num)) :
pocketmon = scanf()
ordered_list.append(pocketmon)
pocketmon_dict[pocketmon] = i + 1
for _ in range(int(question)) :
q = scanf()
if q.isnumeric() :
print(ordered_list[int(q)-1])
else :
print(pocketmon_dict[q]) |
d54e748fc73e35f96cd4d52a90293015ee4eb396 | gabocic/python | /ML/trash/pyProCT-1.4.3/pyproct/clustering/cluster.py | 7,891 | 4.03125 | 4 | """
Created on 12/03/2012
@author: victor
"""
import sys
import random
def cluster_from_tuple(mytuple):
"""
Creates a cluster from a tupple formed by a first element being the prototype and
a second element being the list of all elements.
"""
prototype = mytuple[0]
all_elements = list(mytuple[1])
all_elements.extend([prototype])
return Cluster(prototype, all_elements)
def get_cluster_sizes(clusters):
"""
Calculates all the sizes of a clusters list and returns it in a tuple in which
the first element is the total number of elements, and the second a list containing
the size of each cluster (maintaining the ordering).
"""
total_elements = 0
cluster_sizes = []
for c in clusters:
size = c.get_size()
total_elements = total_elements + size
cluster_sizes.append(size)
return total_elements,cluster_sizes
def gen_clusters_from_class_list(group_list,skip_list=[]):
"""
Generates the clusters that describe a group list. A group list for a N elements clustering
is defined as the list of N elements with the number of cluster to which each cluster
belongs. Example: for 4 elements [1,2,3,4] a possible group list would be: [2,1,2,1] which
means that element 0 and 2 belong to cluster 2 and the others to cluster 2. As it's not possible
to define a centroid or medioid. ATENTION: the first element of the cluster will be defined as the
centroid/medoid.
"""
dic_clusters = {}
for i in range(len(group_list)):
if not group_list[i] in skip_list:
if group_list[i] in dic_clusters.keys():
dic_clusters[group_list[i]].append(i)
else:
dic_clusters[group_list[i]] = [i]
clusters = []
for k in dic_clusters.keys():
clusters.append(Cluster(dic_clusters[k][0],dic_clusters[k]))
return clusters
class Cluster(object):
"""
A cluster object is defined a group of elements which have one or more characteristics in common
and one element which is the most representative element of the cluster.
"""
most_representative_element = None
all_elements = []
def __init__(self, prototype , elements):
"""
TODOC
"""
self.set_elements(elements)
self.id = ""
try:
self.set_prototype(prototype)
except TypeError:
raise
def set_prototype(self,this_one):
"""
Adds a representative element which must already be inside the
internal elements list.
"""
if this_one == None:
self.prototype = None
else:
if this_one in self.all_elements:
self.prototype = this_one
else:
raise TypeError("[Error in Cluster::set_prototype] the prototype is not in the elements list.")
def set_elements(self,elements):
self.all_elements = elements
def get_size(self):
"""
Returns the size of the cluster (which is indeed the size of its elements list)
"""
return len(self.all_elements)
def __eq__(self, other):
"""
Checks whether two clusters are equal or not. Returns True or False depending
on it :P
"""
if(self.get_size() != other.get_size()):
return False
else:
elements = sorted(self.all_elements)
other_elements = sorted(other.all_elements)
for i in range(len(elements)):
if elements[i] != other_elements[i]:
return False
return True
def __str__(self):
return "["+str(self.prototype)+str(self.all_elements)+"]"
def __getitem__(self, index):
return self.all_elements[index]
def calculate_biased_medoid(self,condensed_distance_matrix,elements_into_account):
"""
Calculates the medoid (element with minimal distance to all other objects) of the
elements of the cluster which are in elements_into_account.
"""
all_elems_set = set(self.all_elements)
accountable_set = set(elements_into_account)
# Check that elements_into_account is a subset of all_elements
elem_inters = all_elems_set.intersection(accountable_set)
if len(elem_inters) != len(elements_into_account):
print "[ERROR Cluster::calculate_biased_medoid] 'elements_into_account' is not a subset of the elements of this cluster."
exit()
if len(elements_into_account) == 0:
print "[ERROR Cluster::calculate_biased_medoid] This cluster is empty."
return -1
min_dist_pair = (sys.maxint, -1)
for ei in elements_into_account:
# Calculate distances for this vs all the others
# Note that for comparing, the mean is not required,as
# all have the same amount of elements
summed_distance = 0
for ej in elements_into_account:
summed_distance = summed_distance + condensed_distance_matrix[ei,ej]
min_dist_pair = min(min_dist_pair,(summed_distance,ei))
medoid_element = min_dist_pair[1]
return medoid_element
def calculate_medoid(self,condensed_distance_matrix):
"""
Calculates the medoid for all_elements of the cluster and updates the prototype.
"""
return self.calculate_biased_medoid(condensed_distance_matrix, self.all_elements)
def get_random_sample(self, n, rand_seed = None):
"""
Returns a random sample of the elements.
@param n: Number of random elements to get.
@param rand_seed: Seed for the random package. Used for testing (repeteability)
@return: A random sample of the cluster elements.
"""
if not rand_seed is None:
random.seed(rand_seed)
temporary_list = list(self.all_elements)
random.shuffle(temporary_list)
return temporary_list[0:n]
def to_dic(self):
"""
Converts this cluster into a dictionary (to be used with json serializers).
"""
json_dic = {}
elements = sorted([int(self.all_elements[i]) for i in range(len(self.all_elements))])
elements.append(-1) #capping
str_elements = ""
start = elements[0]
for i in range(1,len(elements)):
if elements[i-1] != elements[i]-1 :
if elements[i-1] == start:
str_elements += str(start)+", "
start = elements[i]
else:
str_elements += str(start)+":"+str(elements[i-1])+", "
start = elements[i]
json_dic["elements"] =str_elements[:-2]
if self.prototype is not None:
json_dic["prototype"] = int(self.prototype)
if self.id != "":
json_dic["id"] = self.id
return json_dic
@classmethod
def from_dic(cls, cluster_dic):
"""
Creates a cluster from a cluster dictionary describing it (as reverse operation of
'to_dic').
@param cluster_dic: The cluster in dictionary form (output of 'to_dic')
"""
if "prototype" in cluster_dic:
proto = cluster_dic["prototype"]
else:
proto = None
if "id" in cluster_dic:
cid = cluster_dic["id"]
else:
cid = None
values_string_parts = cluster_dic["elements"].split(",");
elements = []
for value_part in values_string_parts:
if ":" in value_part:
[ini,end] = value_part.split(":")
elements.extend(range(int(ini),int(end)+1))
else:
elements.append(int(value_part))
cluster = Cluster(proto, elements)
cluster.id = cid
return cluster
|
2e64749ad7adcd36a37a7a8c0387b122fa16eac7 | byeungoo/algorithmStudy | /week7/greedy6/hamdoe_greedy_6.py | 444 | 3.515625 | 4 | def solution(routes):
answer = 0
routes.sort()
bf_end = -30001
for route in routes:
if route[0] > bf_end:
# 포함되지 않는 경우
answer += 1
bf_end = route[1]
else:
# 포함되는 경우
bf_end = min(bf_end, route[1])
return answer
if __name__ == "__main__":
routes = [[-20,15], [-14,-5], [-18,-13], [-5,-3]]
print(solution(routes)) |
9f1a1541415fa1e4aa628c41e22278499e27de87 | abhi0203/Data-Structure-And-Algorithms | /DS_AlgoBook/Queue/QueueHotPotato.py | 785 | 4.03125 | 4 | # This is the problem to represent a queue.
# Here we simulate passing a potato amoing kids and whoever has the potato looses.
# This is done using a queue since the potato traverse instriaght order.
# Here the queue is simulated as circular queue.
import random
class Queue:
def __init__(self):
self.items=[]
def enqueue(self, value):
self.items.insert(0, value)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def isEmpty(self):
return self.items==[]
def hotPotato(names):
q= Queue()
for name in names:
q.enqueue(name)
while q.size()> 1:
num= random.randint(5,15)
for _ in range(num):
q.enqueue(q.dequeue())
q.dequeue()
return q.dequeue()
print(hotPotato(['Abhiram', 'Neha', 'Sara', 'Alka','Sudhir']))
|
9160a22678b4ef6550adc6f3f18b22fa7cdfc295 | ChaeDLR/Bullfrog | /game_files/sprites/enemy.py | 1,600 | 3.5625 | 4 | import pygame
import os
import random
from pygame.sprite import Sprite
class Enemy(Sprite):
""" enemy class """
def __init__(self, screen_w_h: tuple, row_number: int):
""" screen_w: (screen_width: int)
row_number: ()
"""
super().__init__()
self._load_enemy_image()
self.screen_width, self.screen_height = screen_w_h
self.rect = self.image.get_rect()
self.enemy_direction = random.choice((-1, 1))
self.enemy_speed = random.randint(3, 9)
self._set_enemy_spawn(row_number)
def set_enemy_speed(self, speed_modifier: int):
self.enemy_speed = random.randint(
3 + speed_modifier, 9 + speed_modifier
)
def _set_enemy_spawn(self, row: int):
self.x = float(self.rect.x + (
random.randint(5, self.screen_width-40)))
self.rect.x = self.x
self.rect.y = (self.screen_height/7)*row
def _load_enemy_image(self):
path = os.path.dirname(__file__)
self.image = pygame.image.load(
os.path.join(path, 'sprite_images/enemy_ship.png'))
def change_direction(self):
self.enemy_direction = self.enemy_direction * -1
def check_edges(self):
""" make sure player is in screen bounds """
if self.rect.right >= self.screen_width:
self.enemy_direction = -1
elif self.rect.left <= 0:
self.enemy_direction = 1
def update(self):
""" update the enemy position """
self.x += self.enemy_speed * self.enemy_direction
self.rect.x = self.x
|
864578337f4999c5f0b77bc06ca73dea90d8c824 | JohnG-123/litterbox | /Pija/LearnPythontheHardWay/File6.py | 398 | 3.703125 | 4 | from sys import argv
script, first, second, third, fourth = argv
print "This script is called:", script
print "Name a fruit:", first
#print "Your name:", second
print "Your favorite ice-cream flavor:", third
print "Your pet's name:", fourth
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
print "You are %r years old and your height is %r." % (age, height), second |
a78b509bc08cad6bf0c4bd5f4d2eec7a0fe99f07 | mrfosse/holbertonschool-higher_level_programming | /0x02-python-import_modules/3-infinite_add.py | 225 | 3.515625 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
num = len(sys.argv) - 1
i = 1
total = 0;
while i <= num:
total = total + int(sys.argv[i])
i = i + 1
print("{:d}".format(total))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.