blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
54ed4f477b5f52468ea5cdd1a9c4b8c6e7251981 | Broozer29/Utrecht_HBO_ICT | /Lists & numbers.py | 468 | 3.578125 | 4 | def main():
invoer = "5-9-7-1-7-8-3-2-4-8-7-9"
list = invoer.split("-")
list.sort()
nieuweList = []
totaal = 0
for i in list:
totaal += int(i)
nieuweList.append(int(i))
print("Gesoorteerde list: ", nieuweList)
print("Het minimum getal is: ", min(list), "Het maximum getal is: ", max(list))
print("Aantal getallen: ", len(list), "Som van de getallen: ", totaal)
print("Gemiddelde: ", totaal / len(list))
main()
|
4fac8eda3ce50f8b41beb9be5508de400b2589ac | pfkevinma/stanCode_Projects | /stanCode_Projects/my_drawing/draw_line.py | 1,622 | 3.765625 | 4 | """
File: draw_line.py
Name: Pei-Feng (Kevin) Ma
-------------------------
This program creates lines on an instance of GWindow class.
There is a circle indicating the user’s first click. A line appears
at the condition where the circle disappears as the user clicks
on the canvas for the second time.
"""
from campy.graphics.gobjects import GOval, GLine
from campy.graphics.gwindow import GWindow
from campy.gui.events.mouse import onmouseclicked
# Constants
SIZE = 5 # This is the diameter of the ball
# Global variables
window = GWindow(width=500, height=500, title='CLick and Draw') # This is the canvas.
# create 2 global variables to record the location of the dot.
first_dot_x = 0 # create a x global variables to record the x location of the dot.
first_dot_y = 0 # create a y global variables to record the y location of the dot.
def main():
"""
"""
onmouseclicked(draw_line)
def draw_line(event):
"""
use a if/else statement to determine putting the dot or draw a line on window.
:param event: every click on window.
"""
global first_dot_x, first_dot_y
if first_dot_x == 0 and first_dot_y == 0:
dot = GOval(SIZE, SIZE)
window.add(dot, event.x - SIZE / 2, event.y - SIZE / 2)
first_dot_x = event.x
first_dot_y = event.y
else:
window.remove(window.get_object_at(first_dot_x, first_dot_y))
line = GLine(first_dot_x, first_dot_y, event.x, event.y)
window.add(line)
first_dot_x = 0
first_dot_y = 0
if __name__ == "__main__":
main()
|
ade97e11cd2b8ce2321384c78a24128fd2961278 | mamemilk/acrc | /プログラミングコンテストチャレンジブック_秋葉,他/src/2-1-2_03_arc037_b.py | 1,846 | 3.578125 | 4 | # https://atcoder.jp/contests/arc037/tasks/arc037_b
# 閉路判定
# - DFS
# 訪問済みの頂点を再度訪問したときに閉路存在.
#
# - UnionFind
# a,bの辺を張るときに,すでに同じグループなら閉路が存在.
#
N, M = map(int, input().split())
UV = []
for m in range(M):
u, v = map(int, input().split())
UV.append((u,v))
class UnionFind:
def __init__(self, n):
self.n = n
self.parent_size =[- 1]* n
self.heiro = [False] * n
def merge(self, a, b):
x, y = self. leader(a), self. leader(b)
if x == y:
self.heiro[x] = True
return True
if abs(self.parent_size[x]) < abs( self.parent_size[y]):
x, y = y, x
self.parent_size[x] += self. parent_size[y]
self.parent_size[y]= x
return False
def same(self, a, b):
return self. leader( a) == self. leader( b)
def leader(self, a):
if self.parent_size[ a]< 0:
return a
self.parent_size[ a]= self. leader(self. parent_size[ a])
return self. parent_size[ a]
def size( self, a):
return abs(self.parent_size[ self.leader( a)])
def groups( self):
result =[[] for _ in range( self. n)]
for i in range( self. n):
result[ self. leader( i)]. append( i)
return [r for r in result if r != []]
def open_groups( self):
result =[[] for _ in range( self. n)]
for i in range( self. n):
if self.heiro[self.leader(i)]:
pass
else:
result[self.leader(i)].append(i)
return [r for r in result if r != []]
Uni = UnionFind(N)
for u,v in UV:
Uni.merge(u-1,v-1)
print(len(Uni.open_groups()))
|
70037e2a99bcff22dd6337e7a06323500da5e216 | mpyrev/checkio | /open-labyrinth.py | 6,827 | 3.65625 | 4 | from heapq import heappush, heappop
START = (1, 1)
FINISH = (10, 10)
def get_manhattan_score(coords):
return (FINISH[0]-coords[0]) + (FINISH[1]-coords[1])
def make_move(coords, move):
return coords[0]+move[0], coords[1]+move[1]
class SearchNode:
coords = None
move_number = None
previous = None
visited = None
def __init__(self, coords, move_number, previous, visited):
self.coords = coords
self.move_number = move_number
self.previous = previous
self.visited = visited
def get_priority(self):
return self.move_number + get_manhattan_score(self.coords)
def is_goal(self):
return self.coords == FINISH
def __lt__(self, other):
return self.get_priority() < other.get_priority()
def __repr__(self):
v = [str(self.coords), str(self.move_number)]
if self.previous is not None:
v.append('SearchNode({}, {}, ...)'.format(self.previous.coords, self.previous.move_number))
return 'SearchNode({})->{}'.format(', '.join(v), self.get_priority())
def get_steps(self):
l = []
node = self
while node is not None:
l.insert(0, node.coords)
node = node.previous
return l
def get_moves(self):
moves = []
steps = self.get_steps()
for x, y in zip(steps[:-1], steps[1:]):
moves.append((y[0]-x[0], y[1]-x[1]))
return moves
def moves_to_str(moves):
mapping = {(1,0): 'S', (0,1): 'E', (-1,0): 'N', (0,-1): 'W'}
return ''.join([mapping[m] for m in moves])
def checkio(maze_map):
queue = []
heappush(queue, SearchNode(START, 0, None, {START}))
result_node = None
while queue:
node = heappop(queue)
if node.is_goal():
result_node = node
break
for move in [[1,0], [0,1], [-1,0], [0,-1]]:
coords = make_move(node.coords, move)
# Make sure we are not coming back
if maze_map[coords[0]][coords[1]] == 0:
if coords in node.visited:
continue
node.visited.add(coords)
heappush(queue, SearchNode(coords, node.move_number+1, node, node.visited))
return moves_to_str(result_node.get_moves())
if __name__ == '__main__':
# This code using only for self-checking and not necessary for auto-testing
def check_route(func, labyrinth):
MOVE = {"S": (1, 0), "N": (-1, 0), "W": (0, -1), "E": (0, 1)}
# copy maze
route = func([row[:] for row in labyrinth])
pos = (1, 1)
goal = (10, 10)
for i, d in enumerate(route):
move = MOVE.get(d, None)
if not move:
print("Wrong symbol in route")
return False
pos = pos[0] + move[0], pos[1] + move[1]
if pos == goal:
return True
if labyrinth[pos[0]][pos[1]] == 1:
print("Player in the pit")
return False
print("Player did not reach exit")
return False
# These assert are using only for self-testing as examples.
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "First maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Empty maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Up and down maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Dotted maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "Need left maze"
assert check_route(checkio, [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]), "The big dead end."
print("The local tests are done.")
|
05f5a123e3b47cffb018e67c748c9f2d31a2c440 | spymobilfon/PythonHomeWork | /Lessons_1/questions_and_answers.py | 2,004 | 4.03125 | 4 | # Clear the value of variables
correct_answer = 0
not_correct_answer = 0
# Set the value options for YES and NO
value_yes = ["yes", "true", "да", "верно", "правда"]
value_no = ["no", "false", "нет", "не верно", "ложь"]
# Block of the questions and answers
answer_1 = input("Какой это язык программирования?\nОтвет: ")
if answer_1.lower() == "python":
print("Правильный ответ!")
correct_answer += 1
else:
print("Не правильный ответ :(")
not_correct_answer += 1
answer_2 = input("5 больше 10?\nОтвет: ")
if answer_2.lower() in value_no:
print("Правильный ответ!")
correct_answer += 1
else:
print("Не правильный ответ :(")
not_correct_answer += 1
answer_3 = input("10 больше 5?\nОтвет: ")
if answer_3.lower() in value_yes:
print("Правильный ответ!")
correct_answer += 1
else:
print("Не правильный ответ :(")
not_correct_answer += 1
answer_4 = input("4 делится на 2?\nОтвет: ")
if answer_4.lower() in value_yes:
print("Правильный ответ!")
correct_answer += 1
else:
print("Не правильный ответ :(")
not_correct_answer += 1
answer_5 = input("Сколько будет 5 умножить на 2?\nОтвет: ")
try:
answer_5_integer = int(answer_5)
except ValueError:
print("Не правильный ответ :(")
not_correct_answer += 1
else:
if answer_5_integer == 10:
print("Правильный ответ!")
correct_answer += 1
else:
print("Не правильный ответ :(")
not_correct_answer += 1
# Print result
print("Общее количество вопросов {}.\nПравильных ответов {}.\nНе правильных ответов {}.".format(correct_answer + not_correct_answer, correct_answer, not_correct_answer)) |
3c0cc7b30c511a3b4e1f52bc7c70cdf58d30d10a | grigart97/Basics_of_Python | /.idea/Task-2.py | 1,225 | 3.734375 | 4 | from abc import ABC, abstractmethod
class Clothes (ABC):
def __init__(self, size):
self.size = size
@abstractmethod
def tissue_consumption(self):
pass
class Coat(Clothes):
max_size = 66
min_size = 40
@property
def tissue_consumption(self):
if self.size < self.min_size:
nat_size = self.min_size
elif self.size > self.max_size:
nat_size = self.max_size
else:
nat_size = self.size + 1 if self.size % 2 == 1 else self.size
print(f'Для пальто размером {self.size} необходимо {nat_size / 6.5 + 0.5:.3f} метров ткани')
class Suit(Clothes):
max_size = 210
min_size = 120
@property
def tissue_consumption(self):
if self.size < self.min_size:
nat_size = self.min_size
elif self.size > self.max_size:
nat_size = self.max_size
else:
nat_size = self.size + 1 if self.size % 2 == 1 else self.size
print(f'Для костюма размером {self.size} необходимо {nat_size * 2 + 0.3:.1f} метров ткани')
a = Suit(100)
b = Coat(35)
a.tissue_consumption
b.tissue_consumption
|
677d705bf43bb091474e86891c15601c4fcf6e85 | esigei/Lab_4 | /Image.py | 2,045 | 3.515625 | 4 | # Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import numpy as np
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
# Reading my images, transforming and reshaping to fit into the model.
traingenerate = ImageDataGenerator(rescale = 1./255)
testgenerate = ImageDataGenerator(rescale = 1./255)
training = traingenerate.flow_from_directory('mytraining',target_size = (64, 64),batch_size = 32,class_mode = 'binary')
test = testgenerate.flow_from_directory('mytesting',target_size = (64, 64),batch_size = 32,class_mode = 'binary')
# Reading my test image and reshaping it
testimage = image.load_img('dog.jpg', target_size = (64, 64))
testimage = image.img_to_array(testimage)
testimage = np.expand_dims(testimage, axis = 0)
# Creating a Sequential model
model = Sequential()
# adding 2 Dimensional convolutional neural nets layers
model.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2))) # pool a max value in a 2x2 matrix
model.add(Conv2D(32, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Flatten())
# Adding fully connected layers, first with rectifier activation and the next sigmoid
model.add(Dense(units = 128, activation = 'relu'))
model.add(Dense(units = 1, activation = 'sigmoid'))
# Minimize loss measure the model accuracy
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting model on training
model.fit_generator(training,steps_per_epoch=100,epochs=2,validation_data=test,validation_steps=10)
# making prediction on wether the input image is a dog or cat
predict_image = model.predict(testimage)
if predict_image[0][0] == 1:
prediction = 'dog'
print("Image is for dog")
else:
prediction = 'cat'
print("Image is for cat") |
d66ee814bba5b7b79a6be36fa6bf1e08e48d6e39 | qamine-test/codewars | /kyu_5/fibonacci_streaming/test_all_fibonacci_numbers.py | 2,350 | 3.515625 | 4 | # Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# ALGORITHMS
import allure
import itertools
import unittest
from utils.log_func import print_log
from kyu_5.fibonacci_streaming.all_fibonacci_numbers import all_fibonacci_numbers
@allure.epic('5 kyu')
@allure.parent_suite('Novice')
@allure.suite("Algorithms")
@allure.sub_suite("Unit Tests")
@allure.feature("Lists")
@allure.story('Fibonacci Streaming')
@allure.tag('ALGORITHMS')
@allure.link(url='https://www.codewars.com/kata/55695bc4f75bbaea5100016b/train/python',
name='Source/Kata')
class AllFibonacciNumbersTestCase(unittest.TestCase):
"""
Testing all_fibonacci_numbers function
"""
def test_all_fibonacci_numbers(self):
"""
Testing all_fibonacci_numbers function
You're going to provide a needy programmer a
utility method that generates an infinite sized,
sequential IntStream (in Python generator)
which contains all the numbers in a fibonacci
sequence.
A fibonacci sequence starts with two 1s.
Every element afterwards is the sum of
the two previous elements.
:return:
"""
allure.dynamic.title("Testing all_fibonacci_numbers function")
allure.dynamic.severity(allure.severity_level.NORMAL)
allure.dynamic.description_html('<h3>Codewars badge:</h3>'
'<img src="https://www.codewars.com/users/myFirstCode'
'/badges/large">'
'<h3>Test Description:</h3>'
"<p></p>")
with allure.step("Run all_fibonacci_numbers function"
" and verify the result"):
expected = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, 610, 987, 1597, 2584, 4181, 6765,
10946, 17711, 28657, 46368, 75025, 121393,
196418, 317811, 514229, 832040]
result = list(itertools.islice(all_fibonacci_numbers(),
30))
print_log(result=result,
expected=expected)
self.assertEqual(expected,
result)
|
37eb040eee324df5bc657743c7b12143fa168263 | manishdwibedy/Natural-Language-Processing | /Homework 4/ngrams.py | 1,895 | 3.75 | 4 | import codecs
class NGrams(object):
def __init__(self, n, filename):
self.filename = filename
self.n = n
def readFile(self):
'''
Reading the file
:return: Sets the value in the line parameter
'''
lines = []
with codecs.open(self.filename,'r',encoding='utf8') as f:
lines = f.readlines()
self.lines = lines
def computeNGramsFile(self):
# Reading the file
self.readFile()
self.ngrams = []
# For each of the lines
for line in self.lines:
line_ngrams = {}
# computing the list of words
words = line.strip().split()
# If the words are less than 4, only one N-gram is possible
if len(words) < self.n:
# The only n-gram
ngram = ' '.join(words).strip()
if ngram in line_ngrams:
line_ngrams[ngram] += 1
else:
line_ngrams[ngram] = 1
# Otherwise len(words) - 3 number of 4-grams are possible
else:
end_index = len(words) - self.n
for index in range(0, end_index + 1):
n_words = words[index:index+self.n]
ngram = ' '.join(n_words).strip()
if ngram in line_ngrams:
line_ngrams[ngram] += 1
else:
line_ngrams[ngram] = 1
self.ngrams.append(line_ngrams)
def getNGrams(self):
'''
Returing the n-grams as a dict
:return: a dict of n-grams with their counts
'''
self.computeNGramsFile()
return self.ngrams
if __name__ == '__main__':
file_location = 'data/book_data/reference-1.txt'
ngrams = NGrams(1, file_location).getNGrams()
print ngrams |
9ed6b78ac508fbdebde06d506e9df517a32953ed | EmjayAhn/DailyAlgorithm | /18_programmers/programmers_35.py | 448 | 3.921875 | 4 | # https://school.programmers.co.kr/learn/courses/30/lessons/120893
# programmmers, 코딩테스트 입문
import string
def solution(my_string):
answer = ''
for s in my_string:
if s in string.ascii_lowercase:
answer += s.upper()
else:
answer += s.lower()
return answer
if __name__ == '__main__':
test_set = ['cccCCC', 'abCdEfghIJ']
for test in test_set:
print(solution(test)) |
e1f6237109ddeee306208634fc3c565efdad4450 | cwahbong/roller | /roller/dice/_immutable_die.py | 1,438 | 3.640625 | 4 | """ class ImmutableDie.
"""
from roller.dice._die import Die
class ImmutableDie(Die):
""" A die that has immutable attributes.
"""
def __init__(self, distribution, expected_hint=None):
def _normalized_dist_dict(dist_dict):
""" Make the sum of probability be 1 in a distribution by
multiplying a constant.
"""
total_weight = sum(dist_dict.values())
return dict((k, v / total_weight) for k, v in dist_dict.items())
super().__init__()
self._distribution = _normalized_dist_dict(dict(distribution))
if expected_hint is None:
self._expected = sum(k * v for k, v in self._distribution.items())
else:
self._expected = expected_hint
@property
def expected(self):
return self._expected
def prob(self, side):
return self._distribution[side]
def results(self):
return self._distribution.keys()
def regular_die(sides):
""" Shortcut for getting a regular die. For example, d(4) for a
d4, d(6) for a d6, and etc.
"""
return ImmutableDie(
((side, 1 / sides) for side in range(1, sides + 1)),
expected_hint=(sides + 1) / 2
)
def const_die(const):
""" Shortcut for getting a const die. For example, c(3) for a die that
always rolls 3.
"""
return ImmutableDie(
((const, 1), ),
expected_hint=const
)
|
eb82b1cc4dcd2bea324a73553f17ba395038c353 | quanewang/public | /window.py | 4,163 | 4.4375 | 4 |
"""
Given an integer array of size n, find the maximum of the minimums
of every window size in the array. Note that window size varies from 1 to n.
Example:
Input:
10 20 30 50 10 70 30
10 20 30
Output:
70 30 20 10 10 10 10
30 20 10
Explaination:
Input: arr[] = {10, 20, 30, 50, 10, 70, 30}
Output: 70, 30, 20, 10, 10, 10, 10
First element in output indicates maximum of minimums of all
windows of size 1.
Minimums of windows of size 1 are {10}, {20}, {30}, {50}, {10},
{70} and {30}. Maximum of these minimums is 70
Second element in output indicates maximum of minimums of all
windows of size 2.
Minimums of windows of size 2 are {10}, {20}, {30}, {10}, {10},
and {30}. Maximum of these minimums is 30
Third element in output indicates maximum of minimums of all
windows of size 3.
Minimums of windows of size 3 are {10}, {20}, {10}, {10} and {10}.
Maximum of these minimums is 20
Similarly other elements of output are computed.
"""
def window(a):
if not a:
return []
n=len(a)
for i in range(1, n):
mval = a[0]
for j in range(n-i):
a[j] = min(a[j], a[j+1])
mval = max(mval, a[j+1])
a[n-i]=mval
a.reverse()
return a
print window([10, 20, 30, 50, 10, 70, 30])
"""
Sliding window min max
Posted on June 1, 2014
Given an array of integer A[] and the size of sliding window w.
Assume that the window of size w starting from left keeps sliding
by moving the window one element to right each time. Find the stream
of sliding minimums in optimal way. A sliding minimum is
the minimum element of current window.
Lets start with an example for our convenience.
sliding window Min Max
--------------- ----- -----
[1 2 -1] -3 4 2 5 3 -1 2
1 [2 -1 -3] 4 2 5 3 -3 2
1 2 [-1 -3 4] 2 6 3 -3 4
1 2 -1 [-3 4 2] 5 3 -3 4
1 2 -1 -3 [4 2 5] 3 2 5
1 2 -1 -3 4 [2 5 3] 2 5
"""
import heapq
class MHeap:
MIN, MAX = 1, -1
def __init__(self, key):
self.heap=[]
self.key=key
def push(self, x):
heapq.heappush(self.heap, x*self.key)
def peek(self):
return self.heap[0]*self.key
def remove(self, x):
self.heap.remove(x*self.key)
heapq.heapify(self.heap)
def slide(a, w):
if not a or not w:
return []
n=len(a)
min_max=[()]*n
min_heap, max_heap = MHeap(MHeap.MIN), MHeap(MHeap.MAX)
i,j = 0, 0
while i<n:
for k in range(j, min(i+w, n)):
min_heap.push(a[k])
max_heap.push(a[k])
j=k
min_max[i]=(min_heap.peek(), max_heap.peek())
min_heap.remove(a[i])
max_heap.remove(a[i])
i+=1
j+=1
return min_max
print slide([1, 2, -1, -3, 4, 2, 5, 3 ], 3)
"""
For Example: A = [2,1,3,4,6,3,8,9,10,12,56], w=4
partition the array in blocks of size w=4. The last block may have less then w.
2, 1, 3, 4 | 6, 3, 8, 9 | 10, 12, 56|
Traverse the list from start to end and calculate min_so_far.
Reset min to 0 after each block (of w elements).
left_min[] = 2, 1, 1, 1 | 6, 3, 3, 3 | 10, 10, 10
Similarly calculate min_in_future by traversing from end to start.
right_min[] = 1, 1, 3, 4 | 3, 3, 8, 9 | 10, 12, 56
now, min at each position i in current window,
sliding_min(i) = min {right_min[i], left_min[i+w-1]}
sliding_min = 1, 1, 3, 3, 3, 3, 8,
"""
def slide1(a, w):
n=len(a)
l, r = [0]*n, [0]*n
curr=None
for i in range(n):
if i%w==0:
curr = a[i]
l[i]=a[i]
else:
curr = min(curr, a[i])
l[i] = curr
for i in range(n-1, -1, -1):
if i % w == w-1 or i==n-1:
curr = a[i]
r[i] = a[i]
else:
curr = min(curr, a[i])
r[i] = curr
result = [0]*n
for i in range(n):
result[i]=min(r[i], l[min(i+w-1, n-1)])
return result
print slide1([1, 2, -1, -3, 4, 2, 5, 3 ], 3)
|
de2bbc4359a0d0c13c231820f40bab9253bb45d0 | mrejonas/MRC_Flagship | /ExceltoREDCapInstrument.py | 1,856 | 3.859375 | 4 | #!/usr/bin/python
import sys
import re
# Description:
# Take a CSV file generated by Excel with fields in columns
# and transpose column fields to rows. Used these fields to
# then create a basic REDCap instrument to be imported
# PseudoCode/ Steps
# -Add REDCap header
# -Remove trailing or extra spaces from field
# -Capitalise first letter of each word in Field Name
# -Transpose columns into rows
# -Convert field names to variable
# -Add bare minimum field values:
# --> Variable, Form name, Field type and Field Label
# Usage: python scriptname infile.csv "form_name" > outfile.csv
REDCap_header = 'Variable / Field Name,Form Name,Section Header,\
Field Type,Field Label,"Choices,Calculations, OR Slider Labels",\
Field Note,Text Validation Type OR Show Slider Number,Text \
Validation Min,Text Validation Max,Identifier?,Branching Logic \
(Showfield only if...),Required Field?,Custom Alignment,Question \
Number (surveys only),Matrix Group Name,Matrix Ranking?,Field Annotation'
# Print our REDCap instrument header
print REDCap_header
filename = sys.argv[1]
formname = sys.argv[2]
with open(filename) as f:
for line in f:
fieldlist = line.split(",")
for field in fieldlist:
#Strip all extra spaces from string
# Leading and trailing spaces
field = field.strip()
# Multiple spaces replaced with a single space
field = re.sub(' +', ' ', field)
#Capitalise all words in field names
field = field.title()
#Fieldnames to variable names; replace space with underscore
variablename = field.replace(" ", "_")
# Print out the bare minimum field values
#print variablename,',',formname,',,text,',field,",,,,,,,,,,,,,"
sys.stdout.write("%s,%s,,text,%s,,,,,,,,,,,,,\n" % (variablename, formname, field))
|
c0e6396c167ad80f53a54fe322c053aba6b6e5e3 | poojaKarande13/ProgramingPractice | /python/intToRoman.py | 1,962 | 3.921875 | 4 | '''
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
'''
def mapping(t, string, num):
map = {
1: ['I','II','III','IV','V','VI','VII','VIII','IX','X'],
2: ['X','XX','XXX','XL', 'L', 'LX','LXX','LXXX','LC','C'],
3: ['C','CC','CCC','CD','D','DC','DCC','DCCC','DM','M'],
4: ['M', 'MM', 'MMM']
}
string.append(map[t][num-1])
return string
def intToRoman(num):
"""
:type num: int
:rtype: str
"""
string = []
while num > 0:
if num >= 1000: #thousands
mapping(4, string, int(num/1000))
num = num % 1000
elif num >= 100: # hundreds
mapping(3, string, int(num/100))
num = num % 100
elif num >= 10: # tens
mapping(2, string, int(num/10))
num = num % 10
else: # units
mapping(1, string, int(num))
num = 0
return "".join(string)
print(intToRoman(2000))
|
11061a915910abeaf0c05cbf77c6aae51d90bf12 | GenyGit/python-simple-code | /venv/NOK.py | 330 | 3.828125 | 4 | #нахождение наименьшего общего кратного через нахождение наибольшего общего делителя
a = int(input())
b = int(input())
if a > b :
n = a
m = b
else:
n = b
m = a
while n % m != 0 :
ost = n % m
n = m
m = ost
print(a * b // m) |
4ca60261e1129dbce2004a9204f3eac33aa7f10b | philwade/Euler | /euler4.py | 636 | 4.09375 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def isPalindrome(n):
n = str(n)
if len(n) == 1 or n == '':
return True
if n[0] == n[-1]:
return isPalindrome(n[1:-1])
else:
return False
top = 0
for n in range(999, 99, -1):
for m in range(999, 99, -1):
if isPalindrome(n * m):
tmp = n * m
if tmp > top:
print n, m
print n * m
top = tmp
print top
|
780aa0ff92d671b61119f7100c2d4223cf5f7222 | Jane11111/Leetcode2021 | /106_2.py | 827 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021-05-12 15:15
# @Author : zxl
# @FileName: 106_2.py
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder , postorder ) -> TreeNode:
if len(inorder)==0:
return None
if len(inorder) == 1:
p = TreeNode(inorder[0])
return p
root = TreeNode(postorder[-1])
i = 0
while i<len(inorder) and inorder[i] != postorder[-1]:
i+=1
left = self.buildTree(inorder[:i],postorder[:i])
right = self.buildTree(inorder[i+1:],postorder[i:-1])
root.left = left
root.right = right
return root
|
b9d8614f035490050b52a5b75944ac4083c0484e | codacy-badger/pythonApps | /countNumberEachVowel.py | 234 | 3.53125 | 4 |
vowel = 'aiueo'
setString = 'Hello, get back to the future'
setString = setString.casefold()
count = {}.fromkeys(vowel, 0)
for charCount in setString:
if charCount in count:
count[charCount] += 1
print(count)
|
0b033ea21feebbd60d853f003d6a8db1eee80769 | 666syh/python_cookbook | /python_cookbook/1_data_structure_and_algorithm/1.8_字典的运算.py | 615 | 3.953125 | 4 | """
问题
怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)?
"""
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# 使用 zip() 函数先将键和值反转过来
min_price = min(zip(prices.values(), prices.keys()))
print(min_price)
# (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
print(max_price)
# (612.78, 'AAPL')
price_sorted = sorted(zip(prices.values(), prices.keys()))
print(price_sorted)
# [(10.75, 'FB'), (37.2, 'HPQ'), (45.23, 'ACME'), (205.55, 'IBM'),
# (612.78, 'AAPL')]
|
dd254a29df8181d5808fb35ec54c52a727941b30 | tommytobi/DataStructures | /Binary Tree/test_binaryTree.py | 2,064 | 3.734375 | 4 | from binaryTree import BinaryTree
tr = BinaryTree([5,9,7,4,6,1,2,8])
print(tr)
print('find 2', tr.search(2))
print('find 22', tr.search(22))
print('testing deletion')
print('delete 2')
tr.delete(2)
print(tr)
tr = BinaryTree([5,9,7,4,6,1,2,8])
print('delete 1')
tr.delete(1)
print(tr)
tr = BinaryTree([5,9,7,4,6,1,2,8])
print('delete 7')
tr.delete(7)
print(tr)
tr = BinaryTree([5,9,7,4,6,1,2,8])
print('delete 5')
tr.delete(5)
print(tr)
tr = BinaryTree([5,9,7,4,6,1,2,8])
tr = BinaryTree([5,9,7,4,6,1,2,8])
# in order predecessor test
tNode = tr.search(5)
pNode = tr.subtreePredecessor(tNode)
print('in order predecessor of 5:', pNode.data if pNode else None)
tNode = tr.search(4)
pNode = tr.subtreePredecessor(tNode)
print('in order predecessor o 4:', pNode.data if pNode else None)
tNode = tr.search(7)
pNode = tr.subtreePredecessor(tNode)
print('in order predecessor of 7:', pNode.data if pNode else None)
tNode = tr.search(9)
pNode = tr.subtreePredecessor(tNode)
print('in order predecessor of 9:', pNode.data if pNode else None)
tNode = tr.search(2)
pNode = tr.subtreePredecessor(tNode)
print('in order predecessor of 2:', pNode.data if pNode else None)
tNode = tr.search(1)
pNode = tr.subtreePredecessor(tNode)
print('in order predecessor of 1:', pNode.data if pNode else None)
print('--------------------------------------')
tNode = tr.search(5)
pNode = tr.subtreeSuccessor(tNode)
print('in order successor of 5:', pNode.data if pNode else None)
tNode = tr.search(4)
pNode = tr.subtreeSuccessor(tNode)
print('in order successor of 4:', pNode.data if pNode else None)
tNode = tr.search(7)
pNode = tr.subtreeSuccessor(tNode)
print('in order successor of 7:', pNode.data if pNode else None)
tNode = tr.search(9)
pNode = tr.subtreeSuccessor(tNode)
print('in order successor of 9:', pNode.data if pNode else None)
tNode = tr.search(2)
pNode = tr.subtreeSuccessor(tNode)
print('in order successor of 2:', pNode.data if pNode else None)
tNode = tr.search(1)
pNode = tr.subtreeSuccessor(tNode)
print('in order successor of 1:', pNode.data if pNode else None)
|
56593a6968819041901b793928689098be6549ea | suriyakamal007/python | /leap.py | 98 | 3.71875 | 4 | num=int(input())
if ((num%400==0)or(num%4==0 and num%100!=0)):
print('yes')
else:
print('no')
|
b575310940f81b968bd1662c9d9936579f93f701 | dallasmcgroarty/python | /General_Programming/OOP/grumpy_dict.py | 665 | 4.40625 | 4 | # overriding dictionary object in python
# using magic methods we can override how a dictionary functions
# this can also be applied to other objects as well
class grumpyDict(dict):
def __repr__(self):
print("None of Your Business")
return super().__repr__()
def __missing__(self, key):
print(f"You Want {key}? Well It Aint Here!")
def __setitem__(self, key, value):
print("You want to change the dictionary?")
print("Okay fine!")
super().__setitem__(key, value)
data = grumpyDict({"first":"Tom", "animal": "cat"})
print(data)
data['city'] = 'Tokyo'
print(data)
data['city'] = 'SF'
print(data) |
c5ab9e9bcd5b4f4996035e8468fa4a9509ee42b9 | RuRey0310/Competitive_Programming | /ABC151~200/ABC153/d.py | 103 | 3.53125 | 4 | h = int(input())
ans = 0
cnt = 1
while h >= 1:
ans += cnt
h = h // 2
cnt *= 2
print(ans)
|
d7a79c2a81f29c89f14c98b81614fc923adf8caf | almighty-superstar/Python-Projects | /Guessing Game.py | 741 | 3.984375 | 4 | tries=0
secret_word="giraffe"
guess=0
while guess!=secret_word:
guess=input("Choose and animal in all lowercase letters:")
tries=tries+1
if tries==1:
print("The animal is yellow")
if tries==2:
print("The animal is yellow and has spots")
if tries==3:
print("The animal is yellow,has spots, and has a long neck")
if guess==secret_word:
print("You win!")
""" print("You are incorrect,please try again")
tries=tries+1
if tries==1:
print("The animal is yellow")
if tries==2:
print("The animal is yellow and has spots")
if tries==3:
print("The animal is yellow, has spots, and has a long neck")
"""
|
ccbe4c9f93a977aad4e7222034444b2a92087dd8 | dapazjunior/ifpi-ads-algoritmos2020 | /Fabio_06/f6_q02_separar_frase.py | 327 | 3.921875 | 4 | def main():
frase = input('Digite a frase:\n>> ')
print_palavras(frase)
def print_palavras(string):
palavra = ''
for c in string:
if c == ' ':
print(palavra)
palavra = ''
else:
palavra += c
print(palavra)
main() |
0b5482df0b5459c427589c6c35dbb4a195a529a0 | Abdel-IBM-IA/Formation | /Pycharm/LesFonctions/Echange de variables.py | 1,666 | 4.1875 | 4 | from copy import copy
def swap(var1, var2):
""" Permet d'échanger les valeurs de 2 variables passées en arguments
Les deux variables doivent être de même type"""
print("type(var1) : " + str(type(var1)))
if type(var1) == type(var2):
if type(var1) == int or type(var1) == float or type(var1) == str:
return copy(var2), copy(var1)
if type(var1) == list:
temp = var1[:]
var1 = var2[:]
var1.append('1')
var2 = temp[:]
return var1, var2
if type(var1) == dict:
args = {"arg1": var1, "arg2": var2}
return args("arg2"), args("arg1")
else:
NotImplemented
return (copy(var2), copy(var1))
nb1 = 4
nb2 = 6
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1, nb2 = swap(nb1, nb2)
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1 = 5.1
nb2 = 19.0
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1, nb2 = swap(nb1, nb2)
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1 = 5.0
nb2 = 3
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
swap(nb1, nb2)
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1 = {5, 3, 8}
nb2 = {1, 2, 3}
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
swap(nb1, nb2)
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1 = [5, 3, 8]
nb2 = [1, 2, 3]
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
swap(nb1, nb2)
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
nb1 = 1
nb2 = None
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
swap(nb1, nb2)
print("var1 : " + str(nb1))
print("var2 : " + str(nb2))
|
e4e56de38507cc4a4029977d568997f66ea120f6 | guei061528/Leetcode_Training | /FindandReplacePattern.py | 1,206 | 4 | 4 | # You have a list of words and a pattern, and you want to know which words in words matches the pattern.
#
# A word matches the pattern if there exists a permutation of letters p so that after replacing
# every letter x in the pattern with p(x), we get the desired word.
#
# (Recall that a permutation of letters is a bijection from letters to letters: every letter maps
# to another letter, and no two letters map to the same letter.)
#
# Return a list of the words in words that match the given pattern.
#
# You may return the answer in any order.
# def findAndReplacePattern(words, pattern):
words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"]
pattern = "abb"
pattern = list(pattern)
res = []
for word in words:
if len(set(word)) == len(set(pattern)): # 排除一對多的情况
flag = True
mydict = {}
for a, b in zip(word, pattern):
if a not in mydict:
mydict[a] = b
else:
if mydict[a] != b: # 排除多對一的情况
flag = False
break
if flag:
res.append(word)
print(res)
# 了解字典 dictionary 和 zip 用法
# 用排除法的概念來實作 |
e5f47aa24187cf025022dde11581770a7074b0e2 | AlexandraSenkova/pyth_senkova-github | /Урок4_7.py | 1,144 | 3.671875 | 4 | """7. Реализовать генератор с помощью функции с ключевым словом
yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор.
Функция должна вызываться следующим образом:
for el in fact(n).
Функция отвечает за получение факториала числа,
а в цикле необходимо выводить только первые n чисел,
начиная с 1! и до n!.
Подсказка: факториал числа n — произведение чисел от 1 до n.
Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24."""
from functools import reduce
from itertools import count
def fact(n):
res_fact = 1
for i in count(1):
if i <= n:
res_fact = res_fact * i
# reduce(lambda x, y: x*y, range(1, i+1))
yield res_fact
else:
break
for el in fact(int(input('Введите число: '))):
print(el)
|
011bd8b6efff03b48da666814972a1f087f5ea3c | HenriFeinaj/Simple_Python_Programs | /Even_or_Odd_Finder.py | 238 | 4.5 | 4 | #EVEN/ODD FINDER
#Input of an interger by the user.
number = int(input("Enter only an integer: "))
#Find if the number is even or odd.
if number % 2 == 1:
print(number, " ===> odd")
else:
print(number, " ===> even")
|
b56d81745e80ce1fad8c5042f4152ed390d2d402 | codebankss/CorePython | /count.py | 128 | 3.6875 | 4 | n = input()
l = len(n)
count = 0
for x in range(l):
if (n[x] == 'a'):
count +=1
print('a is repeated', count, 'times')
|
3601212637672430d86ffd83e4055307c0ff1beb | AdrianWR/MachineLearningBootcamp | /day00/ex01/matrix.py | 3,535 | 3.5 | 4 | #!/usr/bin/python3
from vector import Vector
class InputError(Exception):
def __init__(self, message="User input error."):
self.message = message
class Matrix:
def __init__(self, data, shape=None):
if isinstance(data, list):
if len(set([len(i) for i in data])) > 1:
raise InputError("Unequal matrix dimensions.")
self.data = data
elif isinstance(data, tuple):
if len(data) != 2:
raise InputError("Invalid matrix shape.")
self.data = [[0 for i in range(data[0])] for i in range(data[1])]
else:
raise InputError("Invalid matrix data.")
@property
def shape(self):
return (len(self.data), len(self.data[0]))
def __neg__(self):
return self * -1
def __add__(self, m2):
m1 = self
if not isinstance(m1, Matrix) or not isinstance(m2, Matrix):
raise InputError("Invalid operands for matrix sum.")
elif m1.shape != m2.shape:
raise InputError("Cannot add matrices with different shapes.")
else:
result = []
for k in range(m1.shape[1]):
result.append([i + j for i, j in zip(m1.data[k], m2.data[k])])
return Matrix(result)
def __radd__(self, m2):
return self + m2
def __sub__(self, m2):
return self + -m2
def __rsub__(self, m2):
return -self + m2
def __mul__(self, m2):
if isinstance(m2, (int, float)):
result = []
for k in range(self.shape[1]):
result.append([i * m2 for i in self.data[k]])
return Matrix(result)
elif isinstance(m2, Vector):
if self.shape[0] != m2.size:
raise InputError("Cannot multiply matrix for n-sized vector.")
result = []
for k in range(self.shape[1]):
result.append(Vector(self.data[k]) * m2)
return result
elif isinstance(m2, Matrix):
if self.shape != m2.shape:
raise InputError("Cannot multiply unequal shapes matrices.")
result = []
for k in range(self.shape[1]):
row = []
for l in range(self.shape[0]):
col = Vector([i[l] for i in m2.data])
row.append(Vector(self.data[k]) * col)
result.append(row)
return Matrix(result)
else:
raise InputError("Can't multiply matrix by this data type.")
def __rmul__(self, scalar):
if isinstance(scalar, (int, float)):
return self * scalar
else:
raise InputError("Can't multiply this type by matrix.")
def __truediv__(self, scalar):
if isinstance(scalar, (int, float)):
return self * (scalar ** -1)
else:
raise InputError("Can't divide matrix by this type.")
def __rtruediv__(self, scalar):
raise InputError("Operation undefined.")
def __str__(self):
result = "["
for i in range(self.shape[0]):
result += str(self.data[i])
if i != self.shape[0] - 1:
result += '\n '
result += "]"
return (result)
def __repr__(self):
result = "Matrix(["
for i in range(self.shape[0]):
result += str(self.data[i])
if i != self.shape[0] - 1:
result += '\n '
result += "])"
return (result)
|
a3cf509db22682ccf52e1e102af94bc85cd98c05 | lyicecream1012/leetcode | /7_ReverseInteger/Solution_1.py | 554 | 3.6875 | 4 | # Solution 1
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
y = 0-x
string = str(y)
str_new = '-'
else:
string = str(x)
str_new = ''
list_x = list(string)
list_new = list(reversed(list_x))
result = int(str_new + ''.join(list_new))
if result > 2**31-1 or result < -2**31:
print "The reversed integer overflows."
return 0
return result
|
76576ae0e4a26843ff9f9e33700c1ec0d218fe32 | zhongtan/automl-scripts | /merge_csv.py | 663 | 3.65625 | 4 | # This script combines all the given input csv files and merges them into one single csv file.
import os
def merge_csv(merge_dir, filenames, outfile):
files = [os.path.join(merge_dir, file) for file in filenames]
fout = open(os.path.join(merge_dir, outfile), "a")
for file in files:
for line in open(file):
fout.write(line)
print("written: {}".format(line))
fout.close()
if __name__ == "__main__":
root = '' # TODO: specify your project's toplevel directory here
merge_dir = root + 'csv/merge_csv_files/'
shoes_files = [] # TODO: specify which CSV files you want to merge
merge_csv(merge_dir, shoes_files, "shoes_merged.csv") |
07921e72ef11d5f0c5b529fba01d6a69200d87cd | dwqq/algorithm_python | /动态规划/最大子序和.py | 540 | 3.625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# -------------------------------
# @Author: dwqq
# @Date : 2021/1/26 10:21
# @File : 最大子序和.py
# @IDE : PyCharm
# -------------------------------
def maxSubArray(nums):
"""最大子序和"""
n = len(nums)
dp = [float('-inf') for _ in range(n)]
if n == 0:
return 0
dp[0] = nums[0]
for i in range(1, n):
dp[i] = max(nums[i], nums[i] + dp[i-1])
return dp
if __name__ == '__main__':
print(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])) |
4e696a222736c71de3beca4471134e58ad781793 | nacros/My-files | /snakenladder.py | 1,188 | 3.90625 | 4 | #!/usr/bin/python3
import random
count=0
r=0
while count<=100:
roll=input("press r to roll the dice")
if roll=="r":
r=random.randint(1,6)
count=count+r
print("your random num is",r)
if count==8:
count=37
print("wow u climbed to ladder",count)
elif count==13:
count=34
print("wow u climed the ladder",count)
elif count==40:
count=68
print("wow u climed the ladder",count)
elif count==52:
count=81
print("wow u climed the ladder",count)
elif count==76:
count=97
print ("wow u climbed ladder",count)
elif count==11:
count=2
print("oops u r bitten by snake",count)
elif count==25:
count=4
print("oops u r bitten by snake",count)
elif count==38:
count=9
print("oops u r bitten by snake",count)
elif count==65:
count=46
print("oops u got bitten by snake"count)
elif count==89:
count=70
print("oops u got bitten by snake",count)
elif count==97:
count=76
print ("oops u got bitten by snake",count)
else:
print("you are on count",count)
|
96cdf9bfceabf52c4005bda0dfba33919c1b59c4 | alextar/drone_trips | /test.py | 2,038 | 3.96875 | 4 | from copy import deepcopy
from typing import List
from typing import Dict
def shipment(items: List[Dict], drone: Dict, trip: int = 1, initial: bool = True) -> None:
if initial:
# sort items by weight from heavier to lighter
# do this only for the first function call (initial=True)
items.sort(key=lambda x: x.get('weight'), reverse=True)
print(drone.get('name'))
capacity = drone.get('capacity')
loading_weight = 0
selected_items = []
def drone_loaded() -> None:
"""
Print selected items
Check if we still have items in list and initiate next trip
:return:
"""
print(f'location {", ".join(selected_items)}')
if len(items):
shipment(items, drone, trip=trip + 1, initial=False)
print(f'trip #{trip}')
# copy items to keep original collection without changes
item_iterator = iter(deepcopy(items))
while True:
try:
item = next(item_iterator)
item_weight = item.get('weight')
# check if it's possible to add next item
if item_weight + loading_weight <= capacity:
loading_weight += item_weight
# add item to selected items
selected_items.append(item.get('name'))
# remove item from available items list
items.remove(item)
# check if item weight less then drone capacity
elif item_weight > capacity:
# if item weight > capacity remove it from the list
items.remove(item)
if loading_weight == capacity:
raise StopIteration()
except StopIteration as e:
# print current trip and initiate next
drone_loaded()
break
test_items = [{'name': 'test1', 'weight': 23},
{'name': 'test2', 'weight': 15},
{'name': 'test3', 'weight': 17}]
test_drone = {'name': 'drone 1', 'capacity': 40}
shipment(test_items, test_drone)
|
8e6689e8250315bb45d04748665cbb4be1fa965f | saloni27301/SIG-python | /module4/even.py | 185 | 3.796875 | 4 | print("SALONI\n 1803010120")
start=int(input("enter start digit:"))
end=int(input("Enter end digit:"))
for i in range(start,end+1):
if(i%2==0):
continue
print(i,end=" ") |
f58b39741f93ad26df4cdfcdd6a97fc866585f39 | mamorukudo0927/pracPython | /src/basicCode/classAndMethod.py | 1,604 | 4.09375 | 4 | # コメント。 #から初めて1行が認識される。
# 変数宣言。型はない。初期化するなら任意の値も
a = 'Hello world'
print(a) # Hello world
a = 1
print(a) # 1
# 関数宣言。 def 関数名 (引数) :で定義。
def addNumber(num1, num2) :
return num1 + num2
# 呼び出しは名称と引数を合わせるだけ
print(addNumber(1 ,2)) # 3
# class宣言もできる。
"""
DocString。ダブルクォートで囲った範囲に適応される。
このクラスは共通処理を提供しています。
"""
class BasicUtil :
# コンストラクタ。インスタンス生成時に呼び出される。
def __init__(self , num) :
self.num = num
# デストラクタ。インスタンス破棄時に呼び出される。
def __del__(self) :
self.num = 0
print('インスタンスを破棄しました。')
# 引数のうち1つめはselfという名称を指定する。
def concatStr(self, target, param) :
return self.num + target + param
def concatNum(self, target, param) :
return target + param
# クラス内メソッドはインスタンス生成を行って呼び出す。
util = BasicUtil(10)
print(util.concatNum(20,30))
# インスタンスの破棄
del util
# クラスの継承も可能
class utilTest(BasicUtil) :
def __init__(self, num) :
self.num = num
# スーパークラスのメソッド呼び出し。
@classmethod
def concatNumTest(cls) :
print(super().concatNum(15, 10, 20))
test = utilTest(15)
print(test.concatNumTest())
|
a66b6364543e1003838416479979b19ace203f54 | python20180319howmework/homework | /yaojikai/20180328/h5.py | 427 | 3.640625 | 4 |
'''
5,定义一个函数,判断用户输入的成绩所属于的等级
1) 90~100:A
2) 80~89 :B
3) 70~79:C
4) 60~69:D
5) 0~59:E
'''
def yjkpd(num):
if 90 < num <= 100:
print("A")
elif 80 < num <= 90:
print("B")
elif 70 < num <= 80:
print("C")
elif 59 < num <= 70:
print("D")
elif 0 <= num <= 59:
print("E")
else:
print("请输入正确的成绩!")
n = int(input("请输入成绩:"))
yjkpd(n)
|
fca5ede91a5e89b51a670b1b0b7aef97bce69469 | oknowles/euler | /problem_12.py | 931 | 3.96875 | 4 | def prime_factors(n):
prime_factors = []
while (n % 2 == 0):
prime_factors.append(2)
n //= 2
p = 3
while (n > 1):
if (n % p == 0):
prime_factors.append(p)
n //= p
else:
p += 2
return prime_factors
# makes use of a trick to count the exponents of all prime factors and multiply their incremented values together
def num_factors(n):
p_factors = prime_factors(n)
prev_p = p_factors[0]
count = 0
total_factors = 1
for p in p_factors:
if p == prev_p:
count += 1
else:
total_factors *= (count+1)
prev_p = p
count = 1
return total_factors*(count+1)
t = 5000
t_num = sum(range(t+1))
while (num_factors(t_num) < 500):
print(t)
t += 1
t_num += t
print('result: triangle number [' + str(t_num) + '] with [' + str(num_factors(t_num)) + '] factors')
|
e88f137e28b516d6fa0036bfb1b9dedb90f064ef | zy15662UNUK/Homework | /Remove Duplicates from Sorted Array.py | 1,388 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 8 23:04:46 2017
@author: James
"""
"""
:type nums: List[int]
:rtype: int
nums is a sorted array
"""
def removeDuplicates(self, nums):
temp = nums[:]
if len(nums)<2:
return len(nums)
else:
for i in temp:
count=1
for j in nums:
if i == j:
if count>1:
nums.remove(i)
else:
count=count+1
return len(nums)
"""
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if not A:
return 0
newTail = 0
for i in range(1, len(A)):
if A[i] != A[newTail]:
newTail += 1
A[newTail] = A[i]
return newTail + 1
"""
"""
since this list is sorted
only check whether its neoghbor is the same
1. if not the same, newtail proceed first by +1 to the initial i
position, then i proceed by i+1
2. once is the same as next one, new tail stops, and i keeps going
till meet a different one
then by newtail proceed first by +1
and switch the different one to the neighbour
|
a3e558a98833af4495e60663240a3971089a93cd | abuyinn/practice-python | /16/e16.py | 750 | 4.09375 | 4 | #!/usr/bin/env python3
import string
import random
easy_chars = string.digits + string.ascii_letters
all_chars = string.digits + string.ascii_letters + string.punctuation
def generate_passwd(_strong):
length = _strong*_strong*2
if strong<2:
passwd = [random.choice(string.ascii_lowercase) for _ in range(length)]
elif strong==2:
passwd = [random.choice(string.ascii_letters) for _ in range(length)]
elif strong ==3:
passwd = [random.choice(easy_chars) for _ in range(length)]
else:
passwd = [random.choice(all_chars) for _ in range(length)]
return "".join(passwd)
strong = int(input("How strong the password should be? [1-4]: "))
print(generate_passwd(strong))
|
b38b8756d6197d194e035c8212e548498cd60f59 | balajisomasale/Chatbot-using-Python | /05 Python Data Stuctures/04 Dictionaries: Challenges/02 Even Keys.py | 591 | 4.375 | 4 | '''
Create a function called sum_even_keys that takes a dictionary named my_dictionary, with all integer keys and values, as a parameter. This function should return the sum of the values of all even keys.
'''
# Write your sum_even_keys function here:
def sum_even_keys(my_dictionary):
total=0
for key in my_dictionary.keys():
if key %2 == 0:
total+=my_dictionary[key]
return total
# Uncomment these function calls to test your function:
print(sum_even_keys({1:5, 2:2, 3:3}))
# should print 2
print(sum_even_keys({10:1, 100:2, 1000:3}))
# should print 6
|
3bb16089ace35132e54f762250e75ada4732d974 | piupom/Python | /sortedrate.py | 797 | 3.828125 | 4 | # python sortedrate.py sortedrate.txt
from sys import argv
rates = {"FIM":6.0}
with open (argv[1]) as infile:
for line in infile:
ps = line.split("\t")
code, name, rate, inrate = ps[0], ps[1], float(ps[2]), float(ps[3])
rates[code] = rate
print(rates.keys())
print(rates.values())
#sanakirjan (set) läpikäynti
for code in sorted(rates):
print(code, rates[code])
code = input("give a currency code:")
try:
print(" Rate is ",rates[code]) # sanakirjan avaimeen viitataan olemassa olevalla arvolle. muuten se pitää tarkistaa
except KeyError:
print("No information for",code)
#vaihtoehtoisesti voidaan suoraan katsoa,että onko arvo avainten joukossa
if code in rates:
print(" Rate is ",rates[code])
else:
print("No information for",code)
#yhtenä rivinä
rates={i: j for i in |
b756c89a12a774eca670e510d672a499ce0156fc | vtopgh/python-tour | /functions/tasks/task9.py | 271 | 3.515625 | 4 | def show_jets(jets):
for jet in jets:
print(jet)
def make_great(jets):
for jet in range(len(jets)):
jets[jet] += ' is great!'
return jets
jets = ['f-18', 'f-86', 'me-163']
show_jets(jets)
new_jets = make_great(jets[:])
show_jets(new_jets)
|
6a0384119909e00113b1de2561a0f96ad5f07da1 | kchase9/ai50-projects-2020-x-tictactoe | /tictactoe.py | 3,890 | 4.03125 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
x_count = 0
o_count = 0
for i in range(3):
for j in range(3):
if board[i][j] == X:
x_count += 1
elif board[i][j] == O:
o_count += 1
if x_count > o_count:
return O
else:
return X
def actions(board): # move = row(i), column(j)
"""
Returns set of all possible actions (i, j) available on the board.
"""
moves = set()
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
moves.add((i, j))
return moves
def result(board, action): # do not alter original board
"""
Returns the board that results from making move (i, j) on the board.
"""
board_copy = copy.deepcopy(board)
if board_copy[action[0]][action[1]] == EMPTY:
board_copy[action[0]][action[1]] = player(board)
return board_copy
else:
raise Exception("Location unavailable")
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
xcount = 0
ocount = 0
for row in board:
xcount = row.count(X)
ocount = row.count(O)
if xcount == 3:
return X
elif ocount == 3:
return O
# check columns
for j in range(3):
if board[0][j] == board[1][j] == board[2][j] == X:
return X
if board[0][j] == board[1][j] == board[2][j] == O:
return O
# check diagonals
# only two possible combos for a diagonal win
if board[0][0] == board[1][1] == board[2][2] == X:
return X
elif board[0][2] == board[1][1] == board[2][0] == X:
return X
if board[0][0] == board[1][1] == board[2][2] == O:
return O
elif board[0][2] == board[1][1] == board[2][0] == O:
return O
# No winner
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
check = 0
if winner(board) == X or winner(board) == O:
return True
for i in range(3):
for j in range(3):
if board[i][j] != EMPTY:
check += 1
if check == 9:
return True
return False
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == X:
return 1
elif winner(board) == O:
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
team = player(board)
if terminal(board):
return None
if team == X:
a = -math.inf
best_move = None
for action in actions(board):
factor = min_value(result(board, action))
if factor > a:
a = factor
best_move = action
return best_move
else:
b = math.inf
best_move = None
for action in actions(board):
maxmove = max_value(result(board, action))
if maxmove < b:
b = maxmove
best_move = action
return best_move
def max_value(board):
n = -math.inf
if terminal(board):
return utility(board)
for action in actions(board):
n = max(n, min_value(result(board, action)))
return n
def min_value(board):
n = math.inf
if terminal(board):
return utility(board)
for action in actions(board):
n = min(n, max_value(result(board, action)))
return n |
d6557e983a95b5c417138e9bf4a3d11a3683fc8b | hmc-koala-f17/CTCI-Edition-6-Solutions-in-Python | /graph_trees/bst_sequence.py | 1,200 | 3.890625 | 4 | # BST Sequences: A binary search tree was created by traversing through an array from left to right
# and inserting each element. Given a binary search tree with distinct elements, print all possible
# arrays that could have led to this tree.
from tree import Tree
def permute (prefix, lst_l, lst_r):
if lst_l == None or lst_r == None:
return lst_l if lst_l is not None else lst_r
permutations = []
for l1 in lst_l:
for l2 in lst_r:
permutations.append([prefix] + l1 + l2)
permutations.append([prefix] + l2 + l1)
return permutations
def bst_sequence(root):
if root is not None:
if root.lchild == None and root.rchild == None:
return [[root.data]]
l_subtree = bst_sequence(root.lchild)
r_subtree = bst_sequence(root.rchild)
permutation = permute(root.data,l_subtree,r_subtree)
return permutation
else:
return None
def main():
t = Tree()
n1 = t.make_node(1)
n2 = t.make_node(2)
n3 = t.make_node(3)
n4 = t.make_node(4)
n5 = t.make_node(5)
n6 = t.make_node(6)
n7 = t.make_node(7)
n1.lchild = n2
n1.rchild = n3
n2.lchild = n4
n2.rchild = n5
n3.lchild = n6
n3.rchild = n7
[print(l) for l in bst_sequence(t.root)]
if __name__ == "__main__":
main()
|
774b5f4bc32721880d557d4d0f7468c9f2232a9c | laureanopiotti/algoritmosI | /ejercicios/fwdalgoritmosparcialito4/10 30 17 Practica - Recursion.py | 1,884 | 4.0625 | 4 | """
TP 3
* --> desencola, imprime y encola
'\\' --> caracter barra
Fibo(0)=1
Fibo(1)=1
Fibo(n)=Figo(n-1)+Figo(n-2)
"""
def suma(l):
if not l:
return 0
print (l)
return l[0]+suma(l[1:])
# Otra manera
def suma(l):
if len(l)==0:
return 0
return l[0]+suma(l[1:])
def fibonacci(n):
if n == 0:
return 1
if n == 1:
return 1
return fibonacci(n-1)#HASTA NO DEVOLVER SU VALOR, NO TOCA LA SIGUIENTE
+fibonacci(n-2)#Una vez terminado el anterior, llama a esta funcion (Ver stack)
def fibonacci(n):
if n == 0:
return 1
if n == 1:
return 1
return fibonacci(n-1)+fibonacci(n-2)#Una vez terminado el anterior, llama a esta funcion (Ver stack)
def fibonacci(n):
if n == 0:
return 1
if n == 1:
return 1
n_2=0
n_1=1
for i in range(2,n):
fibn= n_1+n_2
n_2=n_1
n_1=fibn
return fibn
# log2(n)
"""Ejercicio 15.2.
Escribir una función que simule el siguiente experimento: Se tiene una rata en
una jaula con 3 caminos, entre los cuales elige al azar (cada uno tiene la misma probabilidad), si
elige el 1 luego de 3 minutos vuelve a la jaula, si elige el 2 luego de 5 minutos vuelve a la jaula,
en el caso de elegir el 3 luego de 7 minutos sale de la jaula. La rata no aprende, siempre elige
entre los 3 caminos con la misma probabilidad, pero quiere su libertad, por lo que recorrerá los
caminos hasta salir de la jaula.
La función debe devolver el tiempo que tarda la rata en salir de la jaula."""
import random
def experimento():
'''...'''
camino=random.randint(1,3)
if camino == 3:
return 7
if camino == 2:
return 5+experimento()
return 3+experimento()
def BusquedaBinaria(l,n):
'''.....'''
if not l:
return False
if l[len(l)//2]==n:
return True
if l[len(l)//2]<n:
return BusquedaBinaria(l[len(l)//2:],n)
return BusquedaBinaria(l[:len//2],n)
|
58c212a99a48f944b714c6b9406e81716172a1c4 | stevied9366/Simple-Work-Calculator | /Work_Calculator.py | 840 | 3.90625 | 4 | # Calculator that calculates total based on QUANTITY of coins/bills etc.
pennies = input("Number of Pennies: ")
num1 = int(pennies) * float(.01)
print(num1)
nickels = input("Number of Nickels: ")
num2 = int(nickels) * float(.05)
print(num2)
dimes = input("Number of Dimes: ")
num3 = int(dimes) * float(.1)
print(num3)
quarters = input("Number of Quarters: ")
num4 = int(quarters) * float(.25)
print(num4)
singles = input("Number of Singles: ")
num5 = int(singles)
print(num5)
fives = input("Number of Fives: ")
num6 = int(fives) * 5
print(num6)
tens = input("Number of Tens: ")
num7 = int(tens) * 10
print(num7)
twenties = input("Number of Twenties: ")
num8 = int(twenties) * 20
print(num8)
print(float(num1) + float(num2) + float(num3) + float(num4) + float(num5) + float(num6) + float(num7) + float(num8))
|
a6afd7599b3dc4cee005b05511230ddd470c40a3 | JanaRasras/2D-Game-using-arcade-library | /P03.py | 3,394 | 3.875 | 4 | '''
Build Your Own 2D Platformer Game using Arcade Library
P03: Add keyboard control
Jana Rasras
Nov.2019
'''
## libraries
import arcade
## constants
WIDTH = 1000
HEIGHT = 650
TITLE = 'A game'
BLUE =[100,149,237]
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
COIN_SCALING = 0.5
PLAYER_MOVEMENT_SPEED = 5
## classes
class JGame(arcade.Window):
def __init__(self):
super().__init__(WIDTH, HEIGHT, TITLE)
arcade.set_background_color(BLUE)
# Our physics engine
self.physics_engine = None
def setup(self):
# for scrolling
self.view_bottom = 0
self.view_left = 0
# Keep track of the score
self.score = 0
self.player_list = arcade.SpriteList()
self.wall_list = arcade.SpriteList()
self.coin_list = arcade.SpriteList()
self.player_sprite = arcade.Sprite('images/player_1/player_stand.png',CHARACTER_SCALING)
self.player_sprite.center_x = 64
self.player_sprite.center_y = 120
# self.player_sprite.position = [64, 120]
self.player_list.append(self.player_sprite)
for x in range(0,1250,64):
wall = arcade.Sprite('images/tiles/grassMid.png',TILE_SCALING)
wall.center_x = x
wall.center_y = 32
self.wall_list.append(wall)
coordinate_list = [[512, 96],
[256, 96],
[768, 96]]
for coordinate in coordinate_list:
wall = arcade.Sprite('images/tiles/boxCrate_double.png', TILE_SCALING)
wall.position = coordinate
self.wall_list.append(wall)
self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite, self.wall_list, GRAVITY)
def on_draw(self):
''' Render the screen'''
arcade.start_render()
self.wall_list.draw()
self.coin_list.draw()
self.player_list.draw()
# Draw score and scroll it
score_text = f"Score: {self.score}"
arcade.draw_text(score_text, 10 + self.view_left, 10 + self.view_bottom, [255, 255, 255], 18)
def on_key_press(self, key, modifiers):
'''
'''
if key == arcade.key.UP:
if self.physics_engine.can_jump():
self.player_sprite.change_y = PLAYER_JUMP_SPEED
arcade.play_sound(self.jump_sound)
elif key == arcade.key.DOWN:
self.player_sprite.change_y = - PLAYER_MOVEMENT_SPEED
elif key == arcade.key.LEFT:
self.player_sprite.change_x = - PLAYER_MOVEMENT_SPEED
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED
def on_key_release(self, key, modifiers):
''' '''
if key == arcade.key.LEFT:
self.player_sprite.change_x = 0
elif key == arcade.key.RIGHT:
self.player_sprite.change_x = 0
def on_update(self, delta_time):
""" Movement and game logic (Call update on all sprites)"""
self.physics_engine.update()
## functions
def main():
'''
Create an Empty game
'''
window = JGame()
window.setup()
arcade.run()
## The End ..
if __name__ =='__main__':
main() |
209485aa5487dbbf42f31825944f502bd7b71cbf | rwaidaAlmehanni/python_course | /get_started/dictionary/problem37.py | 206 | 4.28125 | 4 | # Write a function valuesort to sort values of a dictionary based on the key.
def valuesort(f):
arr=[]
x=f.keys()
x.sort()
for i in x:
arr.append(f[i])
print arr
valuesort({'x': 1, 'y': 2, 'a': 3}) |
cc395661950473f79a34f7967c11b5770fe8b13a | MonaTem/algorithms-practice | /SubArray_Cum_Sum.py | 462 | 3.921875 | 4 | # Python program to find the start and end index of a subarray
# that equals a sum passed in
# function to check for subArray that equals the sum
def subArray(a, X):
# Create empty hash set
s = set()
sum = 0
for i in range(0,len(a)):
sum = sum + a[i]
if sum == X:
print (0, i)
if sum in s
print sum+1, i
s.add(arr[i])
# driver program to check the above function
A = [1,4,45,-6,10,8]
X = 16
subArray(a, X)
|
5ec24cea48ce106fe50599a29a723bae548d9b5b | atu-ce/Error-Management | /handling.py | 1,417 | 4.1875 | 4 | # error handling => hata yönetimi
# Yöntem 1 -> Detaylı gösterim, belirtilen hatalar için özel mesaj.
try:
x = int(input("x: "))
y = int(input("y: "))
print(x / y)
except ZeroDivisionError:
print("y değeri için 0 girilemez.")
except ValueError:
print("x ve y değerleri için sayısal değer girmelisiniz.")
# Yöntem 2 -> Belirtilen hatalar için aynı mesaj ama istersek hatanın ne olduğunu öğrenebiliriz.
try:
x = int(input("x: "))
y = int(input("y: "))
print(x / y)
except (ZeroDivisionError, ValueError) as er:
print("Yanlış değer girdiniz.")
print(er)
# Yöntem 3 -> Tüm hatalar için aynı mesaj ama hatayı öğrenemeyiz.
try:
x = int(input("x: "))
y = int(input("y: "))
print(x / y)
except:
print("Yanlış değer girdiniz.")
# Yöntem 4 -> Tüm hatalar için aynı mesaj ve hatayı öğrenebiliriz.
try:
x = int(input("x: "))
y = int(input("y: "))
print(x / y)
except Exception as ex:
print("Yanlış değer girdiniz.")
print(ex)
# Doğru bilgi girilene kadar çalışan, doğru bilgi girilince biten kod dizini:
while True:
try:
x = int(input("x: "))
y = int(input("y: "))
print(x / y)
except:
print("Yanlış değer girdiniz.")
else:
break
finally:
print("try - except sonlandı.")
|
2dbb7b7e371c0e19a52fb5089169d4ce392d9315 | appan-roy/Seleniun-Python | /LearnPython/Pattern/Pattern23.py | 416 | 3.6875 | 4 | """
1
2 2 2
3 3 3 3 3
4 4 4 4
5 5 5
6 6
7
"""
for i in range(1, 4, 1):
for j in range(i, 3, 1):
print("\t\t", end="")
for k in range(1, 2*i, 1):
print(str(i)+"\t\t", end="")
print()
for x in range(4, 8, 1):
for y in range(x, 3, -1):
print("\t", end="")
for z in range(1, 9-x, 1):
print(str(x)+"\t\t", end="")
print() |
983905009d611aa5df69e476320e5405728cf778 | casterbn/my_program | /python_/list_test.py | 203 | 3.59375 | 4 | #!/usr/bin/python
list = ["dai",123,10.02]
list_1 = ["chenghe"]
list[2] = "hehe"
print list[0]
print list
print list[0:1]
print list * 2
print list + list_1
print "********************"
print list[1:2]
|
965dd0529742981315d7def9188da23bad1374e4 | houziershi/PythonStudy | /demo/my_demo.py | 791 | 3.859375 | 4 | #! usr/bin/env python3
# -*- coding:utf-8 -*-
def variable_arg(a, b, *l):
"""可变参数"""
return a + b + sum(l)
def key_word_arg(name, age, **key):
"""关键字参数"""
print(name, age, 'other ===', key)
def named_keyword_arg_1(name, age, *, city, job):
"""命名关键字参数形式1"""
print(name, age, city, job)
def named_keyword_arg_2(name, age, *args, city, job):
""""命名关键字参数形式2: 可变参数"""
print(name, age, "other=", args, city, job)
if __name__ == '__main__':
print(variable_arg(10, 12, *[1, 2, 8]))
key_word_arg('guokun', '66666', city='beijing')
named_keyword_arg_1('guokun', 12, city='beijing', job='Internet')
named_keyword_arg_2('guokun', 12, *[1, 2, 3], city='beijing', job='Internet')
|
afe16866cf0836690c40be6ef1fe947bd1288eea | salterb/ktane | /simple_wires.py | 3,312 | 3.953125 | 4 | """Simple Wires
The Simple Wires module consists of 3-6 horizontal wires with various
possible colours.
"""
from utils import get_input
from colours import bold
def _is_valid_simple_wires(wires):
"""Helper function to determine if the wire arrangement specified
is valid.
"""
if len(wires) < 3 or len(wires) > 6:
return False
for char in wires:
if char not in ('K', 'B', 'Y', 'R', 'W'):
return False
return True
class SimpleWires:
"""Class to represent the SimpleWires module. Solving requires
inputting the list of wire colours, and then cutting a wire
based on a web of conditions based on the number and colours of
the wires, and the bomb's serial number
"""
def __init__(self, bomb):
# Do-while to get the wire sequence
while True:
wire_sequence = get_input("Input the wire sequence. Use one letter per wire. "
"Use 'K' for black: ")
if _is_valid_simple_wires(wire_sequence):
self.wires = wire_sequence
break
print("Invalid wire sequence")
self.bomb = bomb
def __repr__(self):
return self.wires
def _solve_3_wires(self):
if "R" not in self.wires:
print(f'\nCut the {bold("SECOND")} wire\n')
elif self.wires[-1] == "W":
print(f'\nCut the {bold("LAST")} wire')
elif self.wires.count("B") > 1:
print(f'\nCut the {bold("LAST BLUE")} wire\n')
else:
print(f'\nCut the {bold("LAST")} wire\n')
def _solve_4_wires(self):
if self.wires.count("R") > 1 and int(self.bomb.serial[-1]) % 2 == 1:
print(f'\nCut the {bold("LAST RED")} wire\n')
elif self.wires[-1] == "Y" and "R" not in self.wires:
print(f'\nCut the {bold("FIRST")} wire\n')
elif self.wires.count("B") == 1:
print(f'\nCut the {bold("FIRST")} wire\n')
elif self.wires.count("Y") > 1:
print(f'\nCut the {bold("LAST")} wire\n')
else:
print(f'\nCut the {bold("SECOND")} wire\n')
def _solve_5_wires(self):
if self.wires[-1] == "K" and int(self.bomb.serial[-1]) % 2 == 1:
print(f'\nCut the {bold("FOURTH")} wire\n')
elif self.wires.count("R") == 1 and self.wires.count('Y') > 1:
print(f'\nCut the {bold("FIRST")} wire\n')
elif "K" not in self.wires:
print(f'\nCut the {bold("SECOND")} wire\n')
else:
print(f'\nCut the {bold("FIRST")} wire\n')
def _solve_6_wires(self):
if "Y" not in self.wires and int(self.bomb.serial[-1]) % 2 == 1:
print(f'\nCut the {bold("THIRD")} wire\n')
elif self.wires.count("Y") == 1 and self.wires.count("W") > 1:
print(f'\nCut the {bold("FOURTH")} wire\n')
elif "R" not in self.wires:
print(f'\nCut the {bold("LAST")} wire\n')
else:
print(f'\nCut the {bold("FOURTH")} wire\n')
def solve(self):
"""Solve the simple wires module on the bomb. The user inputs the
sequence of wires, and the function tells the user which one to
cut.
"""
solver = getattr(self, f"_solve_{len(self.wires)}_wires")
solver()
|
ac7509aa1b31a80ba8720b1ea168b686c65f705f | agandhasiri/Python-OOP | /program 2 DNA/dna.py | 1,375 | 4.25 | 4 | DNA=input("Enter a DNA sequence: ")
pattern=input("Enter the pattern: ")
reversed_pattern=pattern[::-1]
a=DNA.find(pattern) # Finding start index of pattern
c=len(pattern) # Finding length of pattern
b=DNA.find(reversed_pattern,a+c) # Finding start index of reversed pattern after complete pattern
middle=DNA[a+c:b] # Finding Middle
reversed_middle=middle[::-1] # Reversing middle
mutated_dna=DNA[:a]+pattern+reversed_middle+reversed_pattern+DNA[b+c:]
# Adding prefix,pattern,reversed middle,reversed pattern,suffix
# pattern can be added to the prefix as a+c
print("Prefix:",DNA[:a]) # prefix is from 0 to start index of pattern
print("Marker:",pattern)
print("Middle:",middle )
print("Reversed Middle:",reversed_middle)
print("Reversed Marker:",reversed_pattern)
print("Suffix:",DNA[b+c:]) # suffix is from reversed (pattern + pattern length)till end
print("Result:",mutated_dna)
|
9b2dc2edb737fda6c72adfd3d39a3442296b2aca | prabhat997/demo | /hackerrank/practise here.py | 489 | 3.875 | 4 | import random
n=(random.randint(1,10))
guess_count = 0
guess_limit=4
print('you have 5 chances:')
while (guess_limit<=4):
guess_number=int(input('guess the number:\n'))
guess_limit -= 1
if guess_number > n:
print('insert lower number')
elif guess_number < n:
print('insert higher number')
elif guess_limit == 0:
print('out')
else:
print('correct')
break
print(f'you have {guess_limit} chances')
|
8b0487dc802ab14c39ec86426adb85b34abd0772 | Goooaaal/ali_freshman_compatiton | /model_lr_and_gdbt_and_xgboost/data_preanalysis/dict_csv.py | 1,549 | 3.859375 | 4 | import csv
####
# convert csv file to dict
####
# convert csv file to dict(key-value pairs each column)
def csv2dict(csv_file, key, value):
new_dict = {}
with open(csv_file, 'r')as f:
reader = csv.reader(f, delimiter=',')
# fieldnames = next(reader)
# reader = csv.DictReader(f, fieldnames=fieldnames, delimiter=',')
for row in reader:
new_dict[row[key]] = row[value]
return new_dict
# convert csv file to dict(key-value pairs each row)
def row_csv2dict(csv_file=""):
new_dict = {}
with open(csv_file)as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
new_dict[row[0]] = row[1]
return new_dict
####
# convert dict to csv file
####
# convert dict to csv file(key-value pairs each column)
def dict2csv(raw_dict={}, csv_file=""):
with open(csv_file, 'w') as f:
w = csv.writer(f)
# write all keys on one row and all values on the next
w.writerow(raw_dict.keys())
w.writerow(raw_dict.values())
# convert dict to csv file(key-value 1-1 pairs each row)
def row_dict2csv(raw_dict={}, csv_file=""):
with open(csv_file, 'w') as f:
w = csv.writer(f)
w.writerows(raw_dict.items())
# convert dict to csv file(key-[value] 1-M pairs each row)
def row2_dict2csv(raw_dict={}, csv_file=""):
with open(csv_file, 'w') as f:
w = csv.writer(f)
for k, v in raw_dict.items():
w.writerows([k, v]) |
692585667a88981a77b87e1d35507d353342579a | JQ-WCoding/Python_base | /Base/Solution/Q.py | 483 | 3.640625 | 4 | class Calculator:
def __init__(self):
self.value = 0
def add(self, val):
self.value += val
class UpgradeCalculator(Calculator):
def minus(self, val):
self.value -= val
class MaxLimitCalculator(Calculator):
def maxLimit(self):
if self.value > 100:
self.value = 0
return self.value
else:
return self.value
cal = MaxLimitCalculator()
cal.add(10)
cal.add(90)
cal.add(2)
print(cal.value)
|
9ce46135324bb104ef8f201945dd2fec1922b977 | souza10v/Exercicios-em-Python | /activities1/codes/37.py | 638 | 4 | 4 | // -------------------------------------------------------------------------
// github.com/souza10v
// souza10vv@gmail.com
// -------------------------------------------------------------------------
s1=int(input("Primeiro segmento: "))
s2=int(input("Segundo segmento: "))
s3=int(input("Terceiro segmento:"))
if s1+s2>s3 and s1+s3>s2 and s2+s3>s1 :
print("É possível formar um triângulo. ")
if s1==s2==s3:
print("Triângulo equilátero")
elif s1 != s2 != s3:
print("Triângulo escaleno")
else:
print("Triangulo isóceles.")
else:
print("Não é possível formar um triângulo. ")
|
3ed77cb0475c6ba1258af189beb950698ecb1e51 | amrfekryy/course-CS50W | /lecture2 - Flask/24notes/application.py | 1,429 | 3.734375 | 4 | # import "session" to store user-specific data
from flask import Flask, render_template, request, session
# imoprt "Session" to control "session"
from flask_session import Session
app = Flask(__name__)
# store the sessions server-side
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# empty global list to store data (drowback: accessible by all users)
notes = []
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
note = request.form.get("note")
notes.append(note)
return render_template("index.html", notes=notes)
# START HERE:
# a session is the concept of storing data that is accessible as long as the app (server) is running
# if the server in shutdown, however, data will be lost. BUT this can be solved using database storage
# notes list is a global variable, meaning it will be accessed by all server users.
# to make a user-specific session, we use falsk's "session" dictionary variable
"""
@app.route("/", methods=["GET", "POST"])
def index():
# a session dict item is initialized inside the route function
if session.get("notes") == None:
session["notes"] = []
if request.method == "POST":
note = request.form.get("note")
session["notes"].append(note)
return render_template("index.html", notes=session["notes"])
"""
# flask's session identifies users browsers by storing cookies for each
|
05bf09066c39e7a7e808c78b4b79790b141c4356 | Mchighjohnny/Microsoft-DAT208x-Introduction-to-Python-for-Data-Science | /Manipulating Data.py | 1,874 | 3.59375 | 4 | ##Creating Columns I
# Add sharemen column
recent_grads['sharemen'] = recent_grads['men'] / recent_grads['total']
print(recent_grads)
##Select Row with Highest Value
# Find the maximum percentage value of men
max_men = np.max(recent_grads['sharemen'])
# Output the row with the highest percentage of men
print(recent_grads[recent_grads['sharemen'] == max_men])
##Creating columns II
recent_grads['gender_diff'] = ( ( recent_grads['women'] - recent_grads['men'] )/ ( recent_grads['women'] + recent_grads['men'] ))
##Updating columns
# Make all gender difference values positive
recent_grads['gender_diff'] = np.abs( np.array(recent_grads['gender_diff']))
# Find the 5 rows with lowest gender rate difference
print(recent_grads.nsmallest(5,'gender_diff'))
##Filtering rows
# Rows where gender rate difference is greater than .30
diff_30 = recent_grads['gender_diff'] > .30
# Rows with more men
more_men = recent_grads['men'] > recent_grads['women']
# Combine more_men and diff_30
more_men_and_diff_30 = np.logical_and(diff_30,more_men)
# Find rows with more men and and gender rate difference greater than .30
fewer_women = recent_grads[more_men_and_diff_30 == True]
##Grouping with Counts
# Group by major category and count
print(recent_grads.groupby(['major_category']).major_category.count())
##Grouping with Counts, Part 2
# Group departments that have less women by category and count
print(fewer_women.groupby(['major_category']).major_category.count())
##Grouping One Column with Means
#Report average gender difference by major category.
print(recent_grads.groupby('major_category')['gender_diff'].mean())
##Grouping Two Columns with Means
#Find average number of low wage jobs and unemployment rate of each major category
dept_stats = recent_grads.groupby(['major_category'])['low_wage_jobs', 'unemployment_rate'].mean()
print(dept_stats)
|
8c0a7ee4bc3f8bff16ea3ff3002a27e58de95f3c | arielramirez/people-sorter | /sort_people.py | 3,737 | 4.28125 | 4 | # Task:
# In the language of your choice, please write a function that takes in a list of unique people and returns a list of the people sorted.
# People have a name, age, and social security number. Their social security number is guaranteed to be unique.
# The people should be sorted by name (alphabetically) and age (oldest to youngest).
# When people have the same name and age, they should be sorted in reverse order of how they are in the original list.
# (When we say “list” you can interpret it as array, list, collection, etc.)
import json
import collections
import argparse
import sys
import pprint
from classes.quick_sort import QuickSort
TEST_FILENAME = 'test_people.json'
def sort_people_from_file():
# option to select file from command line
parser = argparse.ArgumentParser()
parser.add_argument('--filename', help="Select a file of people for sorting")
args = parser.parse_args()
filename = args.filename or TEST_FILENAME
# read file, sort it and print the sorted data
with open(filename) as json_file:
people_json = json.load(json_file)
sorted_people = sort_people(people_json)
print("Sorted people in %s:" % filename)
pprint.pprint(sorted_people)
# standardizes the data in preparation for sorting
def transform_to_sort_dimensions(raw_people):
#desired shape of data
# {name: {
# age: [ ssn, ssn ],
# age: [ ssn, ssn ]
# }
# }
formatted = {}
for person in raw_people:
if person['name'] not in formatted.keys():
formatted[person['name']] = { person['age']: [person['ssn']] }
elif person['age'] not in formatted[person['name']].keys():
formatted[person['name']][person['age']] = [ person['ssn'] ]
else:
formatted[person['name']][person['age']].append(person['ssn'])
return formatted
# this returns the results to the i/o format after sorting
def format_sort_results(sorted_people):
#input/output format
# [
# {
# "ssn": "123-45-6789"
# "name": "test",
# "age": 100,
# },
# {
# "ssn": "111-22-3333"
# "name": "test",
# "age": 100,
# }
# ]
# name dimension
formatted_people = []
for name, name_dim in sorted_people.items():
for age, ssn_arr in name_dim.items():
for ssn in (ssn_arr if isinstance(ssn_arr, list) else [ssn_arr]):
formatted_people.append({"ssn": ssn, "name": name, "age": age})
return formatted_people
# sorting helper function to keep primary script clean
def quick_sort_list(unsorted_list, sort_function = None):
sorter = QuickSort()
if sort_function:
sorter.sort_function = sort_function
return sorter.sort(unsorted_list, 0, len(unsorted_list) - 1)
# sorting implementation
def sort_people(raw_people):
#ensure list is not empty
if not raw_people:
return []
# create list of people indexed by name, then indexed by age (see function for format)
unsorted_people = transform_to_sort_dimensions(raw_people)
# sort by name, sorts asc by default
sorted_names_list = quick_sort_list(list(set(unsorted_people.keys())))
# ensure the final sort order is maintained
sorted_people = collections.OrderedDict()
for name in sorted_names_list:
# get the sorted ages in desc order within a given name
sorted_ages_list = quick_sort_list(list(set(unsorted_people[name].keys())), lambda a,b: a > b)
sorted_people[name] = {}
for age in sorted_ages_list:
# storing everything in sorted order by name and age
sorted_people[name][age] = unsorted_people[name][age]
# reversing original order of SSNs given
sorted_people[name][age].reverse()
# returning the results to their original format (totally optional)
return format_sort_results(sorted_people)
# for readability to put primary code at beginning of file
if __name__ == '__main__':
sort_people_from_file()
|
659c1b1a43d2f1005a8a63eb25983383cdf911d9 | JenZhen/LC | /lc_ladder/Basic_Algo/binary-tree/Binary_Tree_Path_Sum_III.py | 1,944 | 4.1875 | 4 | #!/usr/bin/python
import BinaryTree
# https://leetcode.com/problems/path-sum-iii/
# Example
# You are given a binary tree in which each node contains an integer value.
#
# Find the number of paths that sum to a given value.
#
# The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
#
# The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
#
# Example:
#
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
#
# 10
# / \
# 5 -3
# / \ \
# 3 2 11
# / \ \
# 3 -2 1
#
# Return 3. The paths that sum to 8 are:
#
# 1. 5 -> 3
# 2. 5 -> 2 -> 1
# 3. -3 -> 11
"""
Algo: DFS, Backtracking
D.S.: Binary Tree
Solution:
Important:
1) use self.res a member/global variable to track final result
2) Do need to check res before save the new value into cache,
An example: tree of a single node [5] target sum = 0, should return 0,
if save curSum in cache first it will return 1, which is the none node value
Time Complexity: O(N) -- N is number of nodes
Space Complexity: O(N) -- N is number of nodes
Corner cases:
"""
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
self.res = 0
cache = {0: 1} # it's like a padding
self.helper(root, sum, 0, cache)
return self.res
def helper(self, node, sum, curSum, cache):
if not node:
return
curSum += node.val
# Do need to check res before save the new value into cache
# none node is 0 which should not be considered
self.res += cache.get(curSum - sum, 0)
cache[curSum] = cache.get(curSum, 0) + 1
self.helper(node.left, sum, curSum, cache)
self.helper(node.right, sum, curSum, cache)
cache[curSum] -= 1
# curSum is just a variable no need to remove
# Test Cases
if __name__ == "__main__":
solution = Solution()
|
25cfee827f5c7cd472c7aabdedd6314365d4b662 | AddisonG/codewars | /python/stop-gninnips-my-sdrow/stop-gninnips-my-sdrow.py | 383 | 4 | 4 | def spin_words(sentence):
result = ''
words = sentence.split(' ')
for word in words:
if (len(word) >= 5):
result += " " + reverse(word)
else:
result += " " + word
return result[1::]
def reverse(word):
reversedWord = ''
for letter in word:
reversedWord = letter + reversedWord
return reversedWord
|
196ce00a26dd8405a219154329d188679fc60fbd | JaydipMagan/codingpractice | /leetcode/May-31-day/week5/edit_distance.py | 2,060 | 4.0625 | 4 | """
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
"""
from collections import deque
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
dp = [[0 for x in range(n + 1)] for x in range(m + 1)]
for i in range (0,m+1):
for j in range (0,n+1):
if i==0:
dp[i][j] = j
elif j==0:
dp[i][j] = i
elif word1[i-1]==word2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])
return dp[m][n]
def minDistanceQ(self, word1: str, word2: str) -> int:
visited = set()
q = deque([(word1, word2, 0)])
while q:
w1, w2, dist = q.popleft()
if (w1, w2) not in visited:
visited.add((w1, w2))
if w1 == w2:
return dist
while w1 and w2 and w1[0] == w2[0]:
w1 = w1[1:]
w2 = w2[1:]
dist += 1
q.extend([(
w1[1:], w2[1:], dist),
(w1, w2[1:], dist),
(w1[1:], w2, dist)])
|
30d00c14122802366b74d82c095875dc261946c5 | mrusinowski/pp1 | /01-TypesAndVariables/z20.py | 171 | 3.75 | 4 | r = 6
pi = 3.141592
pole = pi*r**2
obwod = 2*pi*r
print("Pole koła o promieniu {} wynosi {}".format(r,pole))
print("Obwód koła o promieniu {} wynoi {}".format(r,obwod)) |
a48c65586d74342cd8611930e1b458e8c6ef3da7 | carlosDevPinheiro/Python | /src/Unisa/Exemplos de programas em Python/árvore2.py | 1,811 | 3.84375 | 4 | # -*- coding: cp1252 -*-
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def printTreeIndented(tree, level=0):
if tree == None: return
printTreeIndented(tree.right, level+1)
print ' '*level + str(tree.cargo)
printTreeIndented(tree.left, level+1)
def printTreeIndented1(tree, level=0):
if tree == None: return
printTreeIndented1(tree.left, level+1)
print ' '*level + str(tree.cargo)
printTreeIndented1(tree.right, level+1)
def abertura():
a = input("Digite o valor da raiz da rvore: ")
b = input("Digite o valor de um n: ")
c = input("Digite o valor de um n: ")
d = input("Digite o valor de uma das folhas: ")
e = input("Digite o valor de uma das folhas: ")
if b > a and c > b > a and d > c > a and e > d > a:
tree = Tree(a, Tree(b, Tree(c, Tree(d, Tree(e)))))
#tree = Tree(a, Tree(c), Tree(b))
printTreeIndented(tree, level=0)
elif b < a and c < b < a and d < c < a and e < d < a:
tree = Tree(e, Tree(d, Tree(c, Tree(b, Tree(a)))))
printTreeIndented1(tree, level=0)
elif b < a and c < b < a and d < c < e and e > c < b and e > c > d and e > d:
tree = Tree(a, Tree(b, Tree(c, Tree(d), Tree(e))))
printTreeIndented(tree, level=0)
elif b > a and c > b > a and d < c < e and e > c > b and e > c > d and e > d:
tree = Tree(a, Tree(b, Tree(c, Tree(d), Tree(e))))
printTreeIndented1(tree, level=0)
elif a > b > d and b > d and a < c < e and c < e:
tree = Tree(a, Tree(c, Tree(e)), Tree(b, Tree(d)))
printTreeIndented1(tree, level=0)
else:
print "Os valores devem ser maiores ou menores que a raiz!"
abertura()
abertura()
|
6045b17e552e3b9315ba06a3a9029d29fe99c2b1 | NikolayVaklinov10/Interview_Preparation_Kit | /Recursion_and_Backtracking/Recursive_Digit_Sum.py | 326 | 3.5625 | 4 | def superDigit(n, k):
def add_digits(string):
if len(string) == 1:
return string
result = sum(int(s) for s in string)
return add_digits(str(result))
start = sum(int(s) for s in n) * k
return add_digits(str(start))
# OR
n, k = map(int, input().split())
print( n * k % 9 or 9)
|
428049684621761f24ac8e7e1a935b3fafcb5eed | vishnuvardhan1807/Datastructure-algorithms | /Triplets.py | 1,014 | 4.03125 | 4 | def triplets(array, targetsum):
array.sort()
for i in range(len(array)-2):
for j in range(i + 1, len(array) - 1):
for k in range(j + 1, len(array)):
if array[i] + array[j] + array[k] <= targetsum:
print((array[i], array[j], array[k]))
# Finding triplets equal to a given sum
'''for value in range(len(array) - 2):
left = value + 1
right = len(array) - 1
while left < right:
currentsum = array[left] + array[right] + array[value]
if currentsum == targetsum:
print((array[left], array[right], array[value]))
left = left + 1
right = right - 1
elif currentsum < targetsum:
print((array[left], array[right], array[value]))
left = left + 1
elif currentsum > targetsum:
right = right - 1'''
array = [2, 7, 4, 9, 5, 1, 3]
targetsum = 10
triplets(array, targetsum) |
e94debeb80bb50eb8562eacd6746ec929ae8d965 | Platforuma/Beginner-s_Python_Codes | /9_Loops/26_Conditional_Statement--each-even-digit-in-range.py | 355 | 4.0625 | 4 | '''
Write a program, which will find all such numbers between 1000 and 3000
(both included) such that each digit of the number is an even number
'''
values = []
for num in range(1000,3001):
num = str(num)
if int(num[0])%2==0 and int(num[1])%2==0 and int(num[2])%2==0 and int(num[3])%2==0:
values.append(num)
print (",".join(values))
|
a452489e25331014e4ea0e54ad03487fa0c41230 | Chadzero/Python_Tuturials | /Project_Euler/003-Largest_prime_factor.py | 1,121 | 4 | 4 | #!/usr/bin/env python
# Name: 003-Largest_prime_factor.py
# Auther: cRamey
# Problem
####################################################
# The prime factors of 13195 are 5, 7, 13 and 29.
#
# What is the largest prime factor of the number 600851475143 ?.
####################################################
# Get a number
# Check if number is int factor
# if factor check if number is prime
import sys
def isprime(guessnum):
result = True
for divisor in range(2, guessnum / 2):
if float(guessnum) % float(divisor) == 0:
result = False
return result
def main():
args = sys.argv[1:]
if len(args) < 1:
print 'Usage: .py upper_limit'
sys.exit(1)
#need to condition numbers so larger than the min needed
upper_limit = long(args[0])
result = "There are no factors. You're number is prime"
for num in range(3, upper_limit / 2, 2):
if isprime(num):
result = "The largest prime factor is %s" % num
print result
return
if __name__ == '__main__':
main()
# Consider switching over to using argparse
|
32e71b73e59d3885cfbc2cdd58c2f234da4a0c78 | JeanBilheux/python_101 | /exercises/Modern python tips and tricks/decorators.py | 474 | 3.765625 | 4 | """Decorator exercises"""
from functools import wraps
def catch_all(func):
"""Trap non-exiting errors and ask user if we should ignore."""
@wraps(func)
def new_func(*args):
try:
return func(*args)
except Exception as error:
print("Exception occurred: {}".format(error))
answer = input("Should we ignore this exception (Y/n)? ")
if answer.lower() == "n":
raise
return new_func
|
5659477a9eb3ad38e51c4337e027a7c1b6a6e871 | zzZ5/StudyNote | /Python/strategy.py | 1,301 | 3.9375 | 4 | #!usr/bin/python3
# -*- coding: utf-8 -*-
# author zzZ5
class Order:
# 建立订单时必须设定价格, 可以选择折扣方式, 若不选择则为原价
def __init__(self, price, discount_strategy=None):
self.price = price
self.discount_strategy = discount_strategy
# 可以临时更改折扣方式
def set_strategy(self, discount_strategy: function):
self.discount_strategy = discount_strategy
# 计算价格, 若无折扣, 则按原价, 若有折扣则减去折扣
def price_after_discount(self):
if self.discount_strategy:
discount = self.discount_strategy(self)
else:
discount = 0
# 若折扣超过原价, 则返回0
return self.price - discount if self.price > discount else 0
# 格式化tostring()方法
def __str__(self):
fmt = "<Price: {}, price after discount: {}>"
return fmt.format(self.price, self.price_after_discount())
# 打九折, 即减去原价的10%
def ten_percent_discount(order):
return order.price * 0.10
# 打75折再加20的优惠券
def on_sale_discount(order):
return order.price * 0.25 + 20
print(Order(100))
print(Order(100, discount_strategy=ten_percent_discount))
print(Order(100, discount_strategy=on_sale_discount))
|
445f0f524e1813dea78a79603ef97b0b647cbda6 | andesviktor/Python_adv_lessons | /homeworks/homework_library/book.py | 628 | 3.6875 | 4 | class Book:
""" Класс книги и действий с ней """
def __init__(self, book_id: int, book_name: str, book_author: str, book_year: int, book_available: bool):
"""
:param book_id: ID книги
:param book_name: Имя книги
:param book_author: Автор книги
:param book_year: Год выпуска книги
:param book_available: Наличие книги
"""
self.book_id = book_id
self.book_name = book_name
self.book_author = book_author
self.book_year = book_year
self.book_available = book_available |
1413a4380f2a3f56cdce48040bf95094729e6c68 | BStrope/Intro-to-algorithms | /hot_potato_queues.py | 496 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 10 13:41:38 2021
@author: - Benjamin Strope
"""
from datatypes import Queue
def hot_potato(players,passes):
q = Queue()
for player in players:
q.enqueue(player)
while q.size() > 1:
for i in range(passes):
has_potato = q.dequeue()
q.enqueue(has_potato)
q.dequeue()
return q.dequeue()
print(hot_potato(['Bill','David','Susan','Jane','Kent','Brad'], 7)) |
55bece2d8d5589962a6835f3fde0661446220d70 | orangedidlo/SOFTUNISHITZz | /24.07.py | 2,571 | 3.71875 | 4 | # for i in range(1, 101):
# print(i)
#
#
#
#
#
# num = int(input())
#
# for i in range(1, num + 1, 3):
# print(i)
#
#
#
#
# num = int(input())
#
# for i in range(0, num + 1, 2):
# print(2 ** i)
#
#
#
#
#
#
#
# num = int(input())
#
# for i in range(num, 0, -1):
# print(i)
#
#
#
#
# symbols = input()
#
# for i in symbols:
# print(i)
#
#
#
#
# word = input()
# score = 0
#
# for i in word:
# if i == 'a':
# score += 1
# elif i == 'e':
# score += 2
# elif i == 'i':
# score += 3
# elif i == 'o':
# score += 4
# elif i == 'u':
# score += 5
#
# print(score)
#
#
#
#
#
#
#
# numbers = int(input())
# sum_num = 0
#
# for i in range(numbers):
# num = int(input())
# sum_num += num
#
# print(sum_num)
#
#
#
#
#
# import sys
#
# num = int(input())
# max_number = -sys.maxsize
# min_number = sys.maxsize
#
# for i in range(num):
# number = int(input())
# if number > max_number:
# max_number = number
# if number < min_number:
# min_number = number
#
# print(f'Max number: {max_number}')
# print(f'Min number: {min_number}')
#
#
#
#
#
#
#
# sequences = int(input())
#
# left_sum = 0
# right_sum = 0
#
# for i in range(sequences):
# left_num = int(input())
# left_sum += left_num
#
# for j in range(sequences):
# right_num = int(input())
# right_sum += right_num
#
# diff = abs(left_sum - right_sum)
#
# if left_sum == right_sum:
# print(f'Yes, sum = {left_sum}')
# else:
# print(f'No, diff = {diff}')
#
#
#
#
#
#
#
# all_numbers = int(input())
# even_sum = 0
# odd_sum = 0
#
# for i in range(all_numbers):
# number = int(input())
#
# if i % 2 == 0:
# even_sum += number
# else:
# odd_sum += number
#
# if even_sum == odd_sum:
# print('Yes')
# print(f'Sum = {even_sum}')
# else:
# print('No')
# print(f'Diff = {abs(even_sum - odd_sum)}')
#
#
#
#
#
#
# lilly_age = int(input())
# laundry_m = float(input())
# price_toy = int(input())
# total_savings = 0
# odd_bday = 0
#
# for i in range(1, lilly_age + 1):
# if i % 2 == 0:
# total_savings += (i * 10 / 2) - 1
# else:
# odd_bday = price_toy * i
#
# total_savings += odd_bday
# diff = abs(total_savings - laundry_m)
# if total_savings >= laundry_m:
# print(f'Yes! {diff:.2f}')
# elif total_savings < laundry_m:
# print(f'No! {diff:.2f}')
|
c56c124bf4c34d0d7f50bc10a072480078f33ce3 | TayKristian/Python | /Estrutura_Decisão/Questão 01.py | 227 | 3.984375 | 4 | n1 = int(input('Informe o 1° numero: '))
n2 = int(input('Informe o 2 ºnumero: '))
if (n1 > n2):
print (n1, 'é maior que', n2)
elif (n1 < n2):
print (n2, 'é maior que', n1)
else:
print ('Os numeros sao iguais')
|
acca8016fdb8bcdc2d1446c610c1fdebcb8bf54d | zc2214/Introduction-to-Computer-Programming | /ICP exercise and assignment/A03/A03_exercise2.py | 552 | 4.3125 | 4 | # PROGRAMMING ASSIGNMENT 03
# Filename: 'exercise2.py'
#
# Write a program that does the following:
# 1. asks the user to input a password length N (type: int, positive)
# 2. then, generates and prints a random password of N characters*
#
# *see the list of valid characters in the pdf file
#
# NOTE: you MUST use a while loop for this exercise
#
# WRITE YOUR CODE AFTER THIS LINE
import random
length = int(input('Password length:'))
i = 0
pwd = ''
while i < length:
pwd += chr(random.randint(33, 126))
i += 1
print(pwd)
|
4125f9e1ff9732988c3df2b03bbce9d4adc8c67b | k4k7u3/betroot-test | /lesson11/task3json.py | 9,449 | 3.546875 | 4 | import json
json_info = None
class Product:
my_type = ""
name = ""
price = 0
def __init__(self, my_type, name, price):
if type(my_type) != str:
raise ValueError("Type should be a string")
if type(name) != str:
raise ValueError("Type should be a string")
if type(price) != int and type(price) != float:
raise ValueError("Price should be a number")
self.my_type = my_type
self.name = name
self.price = price
def __str__(self):
return f'{self.name} = {self.price}'
def __repr__(self):
return f'{self.name} = {self.price}'
class ProductStore:
amount = 0
profit = 0
storage = []
storage_json = []
store_type = ""
store_name = ""
store_price = 0
def __init__(self, *args):
for item in args:
for key in item:
if key == "type":
self.store_type = item[key]
elif key == "name":
self.store_name = item[key]
elif key == "price":
self.store_price = item[key]
elif key == "amount":
self.amount = item[key]
self.temporary_object = Product(self.store_type, self.store_name, self.store_price)
self.add(self.temporary_object, self.amount)
def add(self, product, amount):
x = {}
x["product"] = product
x["amount"] = amount
product.price *= 1.3
product.price = round(product.price, 2)
self.storage.append(x)
def set_discount(self, identifier, percent, identifier_name):
if type(percent) != int and type(percent) != float:
raise ValueError("Percent should be a number")
identifier_name = identifier_name.lower()
if identifier_name == "type":
for i in self.storage:
my_product = i["product"]
if my_product.my_type == identifier:
my_product.price = my_product.price * (1 - (percent / 100))
elif identifier_name == "name":
for i in self.storage:
my_product = i["product"]
if my_product.name == identifier:
my_product.price = my_product.price * (1 - (percent / 100))
else:
raise ValueError("Identifier_name should be a 'type' or 'name' ")
def sell_product(self, product_name, amount):
for i in self.storage:
my_product = i["product"]
if my_product.name == product_name:
if amount > i["amount"]:
raise CustomException("We don't have such amount of product")
else:
i["amount"] -= amount
self.profit += (amount * my_product.price)
if i["amount"] == 0:
self.storage.remove(i)
def get_json(self):
for item in self.storage:
temporary_dict = {}
my_product = item["product"]
temporary_dict["type"] = my_product.my_type
temporary_dict["name"] = my_product.name
temporary_dict["price"] = my_product.price
temporary_dict["amount"] = item["amount"]
self.storage_json.append(temporary_dict)
return self.storage_json
def set_profit(self, input_profit):
self.profit = input_profit
def get_profit(self):
return self.profit
def get_income(self):
return f"{self.profit} $"
def get_all_product(self):
return self.storage
def product_info(self, product):
for i in self.storage:
my_product = i["product"]
if my_product.name == product.name:
my_tuple = product.name, i["amount"]
return my_tuple
class CustomException(Exception):
message = ""
def __init__(self, msg):
self.message = msg
def __str__(self):
return f'{self.message}'
def __repr__(self):
return f'{self.message}'
def unpack_json(json_info):
for item in json_info:
for key in item:
if key == "type":
json_type = item[key]
if key == "name":
json_name = item[key]
if key == "price":
json_price = item[key]
if key == "amount":
json_amount = item[key]
temporary_product = Product(json_type, json_name, json_price)
my_product_store.add(temporary_product, json_amount)
def unpack_json_profit(json_info):
json_profit = json_info
my_product_store.set_profit(json_profit)
def input_check(input_str):
my_str = input_str.replace(".", "")
if my_str.isdigit():
if input_str.count(".") == 0:
return int(input_str)
elif input_str.count(".") == 1:
return float(input_str)
else:
return "error"
try:
try:
json_file = open("mystore.json", "r")
json_info = json.load(json_file)
except json.decoder.JSONDecodeError:
json_info = []
json_file.close()
my_product_store = ProductStore()
unpack_json(json_info)
try:
json_file = open("myprofit.json", "r")
json_info = json.load(json_file)
except json.decoder.JSONDecodeError:
json_info = []
json_file.close()
unpack_json_profit(json_info)
while True:
try:
input_choise = input("Choose, what do you want to do? (1 - add new product; 2 - sell product; 3 - add discount; 4 - show your store; 9 - close store) ")
input_choise = input_choise.strip().lower()
if input_choise == '1':
input_type = input("Please, input type of product: ")
input_name = input("Please, input name of product: ")
while True:
input_price = input("Please, input price per unit of product: ")
if input_price.isdigit():
input_price = int(input_price)
break
else:
print("Price should be a number")
continue
while True:
input_amount = input("Please, input amount of product: ")
input_amount = input_check(input_amount)
if input_amount == "error":
print("Percent should be a number")
continue
else:
break
input_product = Product(input_type, input_name, input_price)
my_product_store.add(input_product, input_amount)
continue
elif input_choise == '2':
input_name = input("Input name of product you want to sell: ")
while True:
input_amount = input("Input amount: ")
if input_amount.isdigit():
input_amount = int(input_amount)
break
else:
print("Amount should be a number")
continue
my_product_store.sell_product(input_name, input_amount)
continue
elif input_choise == '3':
while True:
input_identifier_name = input("Input identifier name (type, or name): ")
input_identifier_name = input_identifier_name.strip().lower()
if input_identifier_name != "type" and input_identifier_name != "name":
print("Identifier name should be a 'type' or 'name' ")
continue
else:
break
if input_identifier_name == "type":
input_name = input("Input type of product you want to sell: ")
elif input_identifier_name == "name":
input_name = input("Input name of product you want to sell: ")
while True:
input_percent = input("Input percent of discount: ")
input_percent = input_check(input_percent)
if input_percent == "error":
print("Percent should be a number")
continue
else:
break
my_product_store.set_discount(input_name, input_percent, input_identifier_name)
continue
elif input_choise == '4':
print("This is your store: ")
print(f"{my_product_store.get_all_product()}")
print(f"Income: {my_product_store.get_income()}")
continue
elif input_choise == '9':
json_info = my_product_store.get_json()
print("Our store is closing. See you tomorrow.")
break
except ValueError as e:
print(e)
continue
except CustomException as e:
print(e)
continue
except Exception as e:
print(e)
finally:
with open('mystore.json', 'w+') as json_file:
json.dump(json_info, json_file, indent=4)
json_info = my_product_store.get_profit()
with open('myprofit.json', 'w+') as json_file:
json.dump(json_info, json_file, indent=4)
print("Good Bye")
|
7dc1a7671c25503669480605988a3d14441ffc64 | weipanchang/FUHSD | /turtle-house.py | 779 | 3.609375 | 4 | #!/usr/bin/env python
import time
from turtle import *
def square(length):
for i in range(4):
fd(length)
rt(90)
def retangle(x,y):
fd(x)
rt(90)
fd(y)
rt(90)
fd(x)
rt(90)
fd(y)
rt(90)
def door(lx, ly, turn, x, y):
penup()
goto(lx,ly)
pendown()
rt(turn)
retangle(x,y)
rt(180)
square(100)
rt(90)
square(100)
rt(180)
square(100)
rt(270)
square(100)
door(-100,50,0,5,25)
#penup()
#goto(-100, 50)
#pendown()
#retangle(5, 25)
door(100,50,0,-5,25)
#penup()
#goto(100, 50)
#pendown()
#rt(180)
#retangle(5, -25)
door(-100,-50,0,5,-25)
#penup()
#goto(-100, -50)
#pendown()
#rt(180)
#retangle(5, -25)
door(100,-50,180,5,25)
#penup()
#goto(100, -50)
#pendown()
#rt(180)
#retangle(5, 25)
time.sleep(10)
|
106440bf8dbc8a5956d1344da2763040a16e8f84 | TylerBromley/fullstack_python_codeguild | /lab9-unit-converter_v4.py | 1,711 | 4.0625 | 4 | # lab9-unit-converter_v4.py
# get the user's distance, sans unit of measure
distance = float(input("What is the distance? "))
# ask for in an out units, but restrict the way they can be entered to numbers
in_unit = int(input("What is the input unit? Please enter\n\t[1] for feet\n\t" +
"[2] for miles\n\t[3] for kilometers\n\t[4] for meters\n> "))
out_unit = int(input("What is the output unit? Please enter\n\t[1] for feet\n" +
"\t[2] for miles\n\t[3] for kilometers\n\t[4] for meters\n> "))
# create a global meters variable
meters = 0
# convert the input to meters
def convert_to_meters(distance, in_unit):
global meters
if in_unit == 1:
meters = round(distance * 0.3048, 4)
elif in_unit == 2:
meters = round(distance * 1609.344, 4)
elif in_unit == 3:
meters = round(distance * 1000, 4)
elif in_unit == 4:
meters = distance
# convert the output to the user's chosen unit of measure
def convert_to_output(out_unit):
global meters
if out_unit == 1:
meters = round(meters / 0.3048, 4)
elif out_unit == 2:
meters = round(meters / 1609.344, 4)
elif out_unit == 3:
meters = round(meters / 1000, 4)
elif out_unit == 4:
meters = meters
# call the functions
convert_to_meters(distance, in_unit)
convert_to_output(out_unit)
# create a unit dictionary for printing
units = {
1 : "ft",
2 : "mi",
3 : "km",
4 : "m",
}
# set in_unit and out_unit to string from units dictionary
if in_unit in units:
in_unit = units[in_unit]
if out_unit in units:
out_unit = units[out_unit]
# print the conversion
print(f"{distance} {in_unit} is {meters} {out_unit}")
|
d46de45f5e5fa539a88e3ea411a0a2c0037ff9b1 | gabriellaec/desoft-analise-exercicios | /backup/user_148/ch19_2020_04_01_04_46_50_488834.py | 213 | 3.671875 | 4 | def classifica_triangulo(x, y, z):
if x==y==z:
print('equilátero')
elif x!=y!=z:
print('escaleno')
elif x==y and y!=z or x==z and z!=y or y==z and x!=z:
print('isósceles') |
063a6884b107d50c14715779425e5d3f2d053b58 | shakfu/polylab | /py/genetic/basic/basic35.py | 5,646 | 4.25 | 4 | """
helloevolve.py implements a genetic algorithm that starts with a base
population of randomly generated strings, iterates over a certain number of
generations while implementing 'natural selection', and prints out the most fit
string.
The parameters of the simulation can be changed by modifying one of the many
global variables. To change the "most fit" string, modify OPTIMAL. POP_SIZE
controls the size of each generation, and GENERATIONS is the amount of
generations that the simulation will loop through before returning the fittest
string.
This program subject to the terms of the BSD license listed below.
"""
import random
#
# Global variables
# Setup optimal string and GA input variables.
#
OPTIMAL = "Hello, World"
DNA_SIZE = len(OPTIMAL)
POP_SIZE = 20
GENERATIONS = 5000
#
# Helper functions
# These are used as support, but aren't direct GA-specific functions.
#
def weighted_choice(items):
"""
Chooses a random element from items, where items is a list of tuples in
the form (item, weight). weight determines the probability of choosing its
respective item. Note: this function is borrowed from ActiveState Recipes.
"""
weight_total = sum((item[1] for item in items))
n = random.uniform(0, weight_total)
for item, weight in items:
if n < weight:
return item
n = n - weight
return item
def random_char():
"""
Return a random character between ASCII 32 and 126 (i.e. spaces, symbols,
letters, and digits). All characters returned will be nicely printable.
"""
return chr(int(random.randrange(32, 126, 1)))
def random_population():
"""
Return a list of POP_SIZE individuals, each randomly generated via iterating
DNA_SIZE times to generate a string of random characters with random_char().
"""
pop = []
for i in range(POP_SIZE):
dna = ""
for c in range(DNA_SIZE):
dna += random_char()
pop.append(dna)
return pop
#
# GA functions
# These make up the bulk of the actual GA algorithm.
#
def fitness(dna):
"""
For each gene in the DNA, this function calculates the difference between
it and the character in the same position in the OPTIMAL string. These values
are summed and then returned.
"""
fitness = 0
for c in range(DNA_SIZE):
fitness += abs(ord(dna[c]) - ord(OPTIMAL[c]))
return fitness
def mutate(dna):
"""
For each gene in the DNA, there is a 1/mutation_chance chance that it will be
switched out with a random character. This ensures diversity in the
population, and ensures that is difficult to get stuck in local minima.
"""
dna_out = ""
mutation_chance = 100
for c in range(DNA_SIZE):
if int(random.random() * mutation_chance) == 1:
dna_out += random_char()
else:
dna_out += dna[c]
return dna_out
def crossover(dna1, dna2):
"""
Slices both dna1 and dna2 into two parts at a random index within their
length and merges them. Both keep their initial sublist up to the crossover
index, but their ends are swapped.
"""
pos = int(random.random() * DNA_SIZE)
return (dna1[:pos] + dna2[pos:], dna2[:pos] + dna1[pos:])
#
# Main driver
# Generate a population and simulate GENERATIONS generations.
#
if __name__ == "__main__":
# Generate initial population. This will create a list of POP_SIZE strings,
# each initialized to a sequence of random characters.
population = random_population()
# Simulate all of the generations.
for generation in range(GENERATIONS):
print("Generation %s... Random sample: '%s'" % (generation, population[0]))
weighted_population = []
# Add individuals and their respective fitness levels to the weighted
# population list. This will be used to pull out individuals via certain
# probabilities during the selection phase. Then, reset the population list
# so we can repopulate it after selection.
for individual in population:
fitness_val = fitness(individual)
# Generate the (individual,fitness) pair, taking in account whether or
# not we will accidently divide by zero.
if fitness_val == 0:
pair = (individual, 1.0)
else:
pair = (individual, 1.0 / fitness_val)
weighted_population.append(pair)
population = []
# Select two random individuals, based on their fitness probabilites, cross
# their genes over at a random point, mutate them, and add them back to the
# population for the next iteration.
for _ in range(POP_SIZE // 2):
# Selection
ind1 = weighted_choice(weighted_population)
ind2 = weighted_choice(weighted_population)
# Crossover
ind1, ind2 = crossover(ind1, ind2)
# Mutate and add back into the population.
population.append(mutate(ind1))
population.append(mutate(ind2))
# Display the highest-ranked string after all generations have been iterated
# over. This will be the closest string to the OPTIMAL string, meaning it
# will have the smallest fitness value. Finally, exit the program.
fittest_string = population[0]
minimum_fitness = fitness(population[0])
for individual in population:
ind_fitness = fitness(individual)
if ind_fitness <= minimum_fitness:
fittest_string = individual
minimum_fitness = ind_fitness
print("Fittest String: %s" % fittest_string)
exit(0)
|
9339060107bef177c65e11f8f90005a64e3ff59f | L200170153/coding | /da best/uas/uas3.py | 203 | 3.578125 | 4 | def putar(l):
k = []
a = l[-2:]
b = l[0:len(l)-2]
for i in a:
k.append(i)
for l in b:
k.append(l)
print(k)
l = [x for x in input().split(',')]
putar(l)
|
11f5f26f7d43db15614a8fb2e5a4a003b878307b | madhavibadekolu/python | /assignment programs/exception handling/ex1.py | 368 | 3.796875 | 4 | try:
n1=int(input('enter 1st number:'))
n2=int(input('enter 2nd number:'))
print('sum=',n1+n2)
try:
print('div=',n1/n2)
print('mul=',n1*n2)
print('sub=',n1-n2)
except ZeroDivisionError as ze:
print(ze)
print('mul=', n1 * n2)
print('sub=', n1 - n2)
except ValueError as ve:
print('invalid input') |
3eccc969ae4865e8cb27c56b4862248777089d2c | kbr1218/project_comcode | /파이썬_자료/TupleTest.py | 1,232 | 3.84375 | 4 | #Tuple 튜플
print("-" * 10, "tuple 생성/type 확인", "-" * 10)
t1 = (1, 2, 3) #괄호를 이용해서 만든 튜플
t2 = 5, 6, 7 #괄호 없이 만든 튜플
print(type(t1), type(t2)) #튜플의 type 확인
#요솟값 삭제 불가 del t[x]
# del t1[0] ---> 튜플의 값은 삭제할 수 없으므로 오류 발생
#요솟값 변경 불가 t[x] = x
# t1[0] = 3 ---> 튜플의 값은 수정할 수 없으므로 오류 발생
#튜플 인덱싱 t[x]
print("\n", "-" * 10, "tuple 인덱싱과 슬라이싱", "-" * 10)
print(t1[2]) #튜플 t1의 3번째 값 출력(인덱싱)
#튜플 슬라이싱 t[:]
print(t2[1:]) #튜플 t2의 두번째 값부터 끝까지 출력(슬라이싱)
#튜플 더하기 t1 + t2
print("\n", "-" * 10, "tuple 더하기", "-" * 10)
t3 = t1 + t2 #튜플 t1과 t2를 합쳐서 t3에 저장
print(t3)
#튜플 곱하기 t * x(int)
print("\n", "-" * 10, "tuple 곱하기", "-" * 10)
t4 = t1 *4 #튜플 t1을 4번 곱해서 t4에 저장
print(t4)
#튜플 길이구하기 len(t)
print("\n", "-" * 10, "tuple 길이 구하기", "-" * 10)
print(len(t4)) |
48250c93ca983b875d11dbda7652038d1fd7ca00 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2510/60705/297143.py | 64 | 3.65625 | 4 | l = input()
if l == "5 2 2 24":
print(19)
else:
print(l) |
0bd281dc799aa8c5b0e696125581a7acf5ce61d0 | wrossmorrow/cattree | /cattree.py | 16,844 | 3.765625 | 4 | import numpy as np
# utility function; return True if the argument is a positive integer
def is_pos_int( n ) :
import numbers
if not isinstance( n , numbers.Integral ) : return False
elif n <= 0 : return False
else : return True
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class CatTree :
"""
A binary (decision) tree class
The tree itself is implemented as a linked list construct... Each split is of the form
(i) [ p , k , y , t , f ]
i : internal "list" index
p : parent split in the list (note: not sure if this is needed)
k : feature this split splits over from {0,...,K-1}, or -1 if none
y : (majority) prediction for this level
t : "i" index in the list to move to for True features k
f : "i" index in the list to move to for False features k
The "i" indices are implicit, literally being the positional indices. The list is initialized as
[ -1 , k0 , 1 , 2 ]
standing for root (no parent) and k0 in {0,1,...,K-1} being the first split (if any).
The list can be traversed with the predict function, which basically does
i = 0
while T[i].t >= 0 and T[i].f >= 0 :
i = T[i].t if x[k] else T[i].f
y = T[i].y
"""
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class CatTreeNode :
""" A node class to build trees from """
def __init__( self , p=-1 , k=-1 , S=None , y=-1 , L=None ) :
self._p = p # Parent node in the tree
self._k = k # Feature to split over here
self._S = S # Split indices for this node... i.e. goto S[x[k]]
self._y = y # Prediction at this node (used for leafs)
self._L = L # List of indices this node concerns (used for leafs only?)
self._c = None # counts on items
self._C = 0 # Total counts, or node coverage size
self._e = None # Error on a set of data used to fit
def print( self , h=0 ) :
s = ''
for i in range(0,h) : s = '%s ' % s
print( '%sparent , feature , prediction , error :' % s , self._p , self._k , self._y , self._e )
print( '%s goto list: ' % s , self._S )
print( '%s indx list: ' % s , self._L )
def MajPred( self , y ) :
""" set self._y as a majority prediction over y(self._L), updating error as well """
import numpy as np
if y is None or self._L is None : return
# check for indexing mismatch?
try : y[self._L]
except Exception as e :
raise ValueError( 'passed y cannot be indexed by CatTreeNode._L (%s)' % e )
# search through unique items in y[L], getting counts and majority element.
# implementation differs for lists and for numpy.ndarrays
self._c = {} # empty dictionary for counts
self._C = 0
if isinstance( y , list ) :
u = set( y[self._L] )
for i in u :
self._c[i] = y[self._L].count(i)
if self._c[i] > self._C :
self._y = i
self._C = self._c[i]
elif isinstance( y , np.ndarray ) :
u = np.unique( y[self._L] )
for i in u :
self._c[i] = len( np.where( y[self._L] == i ) )
if self._c[i] > self._C :
self._y = i
self._C = self._c[i]
else :
raise ValueError( 'y is not a comprehensible object here (list, numpy.ndarray)' )
# now, self._y is set as a majority predictor, unique item counts are set in self._c,
# and we can (re)set self._C as the total coverage
self._C = len( self._L )
# set error for this majority prediction... note using np.nditer
self._e = sum( 1 if y[i] != self._y else 0 for i in self._L ) # np.nditer(self._L) )
# return error count
return self._e
def Split( self , k ) :
""" Split this node (wiping out some data) on feature k """
return
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def __init__( self , K , L=None ) :
"""
CatTree init function. Requires a feature "spec" :
K: number of features
L: a K-list of numbers of 'levels' per feature, defaults to binary if None
"""
import numpy as np
if not is_pos_int( K ) :
raise ValueError( 'CatTree requires a positive integer number of features' )
self._K = K
self._L = 2 * np.ones((K,)) # initialize as binary
self._T = [] # empty list initialization of the tree
if L != None :
if len(L) != K :
raise ValueError( 'if feature levels are provided, you must provide for ALL features' )
else :
for k in range(0,K) :
if not is_pos_int( L[k] ) :
raise ValueError( 'CatTree requires a positive integer number of feature levels when provided' )
elif L[k] == 1 :
raise ValueError( 'CatTree requires features with at least two levels (binary features)' )
else :
self._L[k] = L[k]
else : # nothing to do, as we've already done a binary feature initialization
pass
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def split( self , n , X , y ) :
"""
CatTree "split" function used in (recursive) fit routine
"""
import numpy as np
# should we split the tree node n? look at error (which we hope is defined)
e = self._T[n]._e
# if error at current node is zero, don't split
if e == 0 : return
# other conditions?
# otherwise... build trial splits, and compare to current node error
Tp = None
Ep = len( self._T[n]._L ) # we know e must be less than this
ip = None
kp = -1
for k in range(0,self._K) :
# Is there any variation in X[T[n]._L,k]? If so, we could split over it
u = np.unique( X[self._T[n]._L,k] ) # u holds unique elements in the kth feature
if len( u ) > 1 : # if there is variation
t = [] # initialize empty node list for this trial
j = [] # initialize empty index list for this trial
E = 0 # initialize error for this trial, accumulated below
for i in u : # evaluate each possible value
# get a LIST of indices such that X[T[n]._L,k] == i
l = np.where( X[self._T[n]._L,k] == i )[0].flatten()
# add a tree node to the trial list for that list, with node n as parent
t.append( self.CatTreeNode( p=n , L=l ) )
j.append( i )
# set predictor and error and accumulate error counts
E += t[i].MajPred( y )
if E < Ep : # find feature minimizing trial error
del Tp # delete the last version of update to tree
Tp = list( t ) # NOTE: need to make sure this is a "deep copy" operator
ip = j
Ep = E # reset minimum
kp = k # set feature index
del t # delete the temporary list (necessary?)
# if we are splitting, append the trial nodes to the Tree (node list) self._T
# ... and recurse into them in turn (depth-first "search")
if Ep < e : # we found a split that could lower error, and have the best one
# NOTE: at some point, take this naive splitting and attempt to merge it
# to a smaller ruleset when predictions are the same
# define the "goto" list in T[n]._S for this "branching"
self._T[n]._S = {}
for i in range(0,len(Tp)) :
self._T[n]._S[ ip[i] ] = n+i+1
# define the feature over which we are branching
self._T[n]._k = kp
# append (extend) the new elements to the tree (holding n for now)
self._T.extend( Tp[:] )
# recursively split on each of these new elements in turn, accumulating error
Ep = 0
for m in self._T[n]._S.values() :
self.split( m , X , y )
Ep += self._T[m]._e
# over-write error with this new value
self._T[n]._e = Ep
return
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def fit( self , N , X , y ) :
"""
CatTree "fit" function: fit a binary tree construct to feature data X and outcomes
y. Expects an (integral, positive) number of observations N, an N x K matrix X of
features, and an N vector y of outcomes.
"""
if not is_pos_int( N ) :
raise ValueError( 'CatTree requires a positive integer number of observations' )
if X is None or y is None :
raise ValueError( 'CatTree requires a feature matrix X and a observation vector y' )
try : S = X.shape
except AttributeError :
raise ValueError( 'CatTree requires feature matrices with a shape attribute' )
else : # don't catch other exceptions (which could be... what?)
if len(S) > 2 or len(S) == 0 :
raise ValueError( 'CatTree requires feature matrices; that is, dim-2 arrays' )
if S[0] != N :
raise ValueError( 'CatTree expects an N x K feature matrix' )
if len(S) == 1 and self._K > 1 :
raise ValueError( 'CatTree expects an N x K feature matrix' )
if len(S) == 2 :
if S[1] != self._K :
raise ValueError( 'CatTree expects an N x K feature matrix' )
# assert fit over categorical coded values in the data matrix
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# blank initialization of tree as a list of CatTreeNode classes
self._T = [ self.CatTreeNode( L=list(range(0,N)) ) ]
self._T[0].MajPred( y )
print( 'starting error: ' , self._T[0]._e )
# set current node at the root
n = 0
# start (recursive) iteration
self.split( 0 , X , y )
# when split returns, we have built out self._T...
print( 'fit error: ' , self._T[0]._e )
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def print( self , n=0 , h=0 ) :
""" print method, starting from a certain index """
self._T[n].print( h )
if self._T[n]._S is not None :
H = h+1
for i in self._T[n]._S.values() :
self.print( n=i , h=H )
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def predict_nocheck( self , x ) :
""" Method to do actual predictions via tree search, but with no argument checks """
n = 0
while True :
if self._T[n]._k < 0 : return self._T[n]._y
else : n = self._T[n]._S[ x[self._T[n]._k] ]
def predict( self , X=None ) :
""" Method to execute predictions via tree search, but with argument checks """
if X is None : return
if len(self._T) == 0 :
raise ValueError( 'CatTree has not yet been fit, so cannot predict' )
try : S = X.shape
except AttributeError as e :
raise ValueError( 'predict expects feature data X that has a shape attribute (%s)' % e )
print( S )
if len(S) > 2 or len(S) == 0 :
raise ValueError( 'predict expects feature data X that is N x K or K x 1' )
if len(S) == 1 :
if S[0] != self._K :
raise ValueError( 'predict expects feature data X that is N x K or K x 1' )
else : # use current tree to predict
y = self.predict_nocheck( X )
else : # len(S) == 2
if S[1] != self._K :
raise ValueError( 'predict expects feature data X that is N x K or K x 1' )
else : # use current tree to predict each element
if S[0] == 1 : y = self.predict_nocheck( X[0] )
else :
y = []
for i in range(0,S[0]) :
y.append( self.predict_nocheck( X[i] ) )
return y
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
e2fd0421db552cd047b2ec0351b7b002475f8fe8 | jeonggoun/python3 | /data_type.py | 1,338 | 3.84375 | 4 | # 데이터 자료형(data type)
# 숫자형
# 변수
# 문자, _으로 시작
# 공백x (한글x)
# 예약어 x - Camel Case / Snake Case
# 변수 : 데이터를 담는 그릇, 공간, 컨테이너, 변한다
# 리터럴 : 5; '한'
num1 = 13
num1 = 5
# num1의 공간에 숫자 3이 저장되어 있는 것
num2 = 3.5
# num2의 공간에 숫자 5가 저장되어 있는 것
print(num1+num2)
# 변수의 데이터 타입 확인 -type()
print(num1+num2)
print(type(num1))
print(type("hello world"))
# 연산자 : +, -, *, /
# a라는 변수를 선언(=메모리의 어떤 공간에 변수를 생성, 주소는 확인 가능!)
# id() - 메모리의 주소를 확인하는 함수
a = 20
b = 3
c, d = 20, 30
# 두 값을 동시에 입력할 수도 있음.
print("c의 값:", c)
print("d의 값:", d)
print("두 수의 합은", a+b)
print("두 수의 차는", a-b)
print("두 수의 곱은", a*b)
print("두 수의 나누기는", a/b)
# int() - 실수 데이터를 정수로 변환하는 함수
# //로 연산하면 값이 실수인 데이터도 정수 데이터로 나온다
print("두 수의 나누기는", int(a/b))
print("두 수의 나누기는", a//b)
print("두 수의 제곱은", a**b)
# 파이썬 연산자 : **, //
# 만능문자, asterisk
# 기본적인 연산자. 교재에 연산자 파트 열어봤을 때 여러 예문 있음. |
8a1b42d50065636aa2b86cc44e976cfda99b2b7d | xuzhendongfire/python | /日期_数码管.py | 2,095 | 3.578125 | 4 | import turtle
#设置回执日期长度和间隔
le = 50
itv = 20
#定义数字,传入(x,y)和number
def drowDate(x,y,n):
d = turtle.Turtle()
d.speed(5)
d.pensize(10)
d.color("red")
d.hideturtle()
d.penup()
d.goto(x,y)#画笔移动到起点
d.pendown()
#绘制 从上到下,从左到右
#第一横
if n==0 or n==2 or n==3 or n==5 or n==6 or n==7 or n==8 or n==9:
d.forward(le)
#第一竖
if n==0 or n==4 or n==5 or n==6 or n==8 or n==9:
xx = x
yy = y
d.penup()
d.goto(xx,yy)#画笔移动
d.pendown()
d.right(90)
d.forward(le)
d.left(90)
#第二竖
if n==0 or n==1 or n==2 or n==3 or n==4 or n==7 or n==8 or n==9:
xx = x+le
yy = y
d.penup()
d.goto(xx,yy)#画笔移动
d.pendown()
d.right(90)
d.forward(le)
d.left(90)
#第二横
if n==2 or n==3 or n==4 or n==5 or n==6 or n==8 or n==9:
xx = x
yy = y - le
d.penup()
d.goto(xx,yy)#画笔移动
d.pendown()
d.forward(le)
#第三竖
if n==0 or n==2 or n==6 or n==8:
xx = x
yy = y - le
d.penup()
d.goto(xx,yy)#画笔移动
d.pendown()
d.right(90)
d.forward(le)
d.left(90)
#第四竖
if n==0 or n==1 or n==3 or n==4 or n==5 or n==6 or n==7 or n==8 or n==9:
xx = x + le
yy = y - le
d.penup()
d.goto(xx,yy)#画笔移动
d.pendown()
d.right(90)
d.forward(le)
d.left(90)
#第三横
if n==0 or n==2 or n==3 or n==5 or n==6 or n==8:
xx = x
yy = y - le*2
d.penup()
d.goto(xx,yy)#画笔移动
d.pendown()
d.forward(le)
#接收日期(暂不做判断)
date = str(input("麻利点,快输入日期(如20171123):"))
turtle.setup(1000,800,0,0)#定义画布大小
x = -4*(le+itv)
y = le
for i in date:
drowDate(x,y,int(i))
x = x+le+itv
|
0764dec5163d43f1d34f36fdd25c1ee52df26e86 | junjongwook/programmers | /Skill Check/Level4/s12942.py | 916 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
최적의 행렬 곱셈 : https://programmers.co.kr/learn/courses/30/lessons/12942?language=python3
"""
M = dict()
def solution(matrix_sizes):
def MIN(i1, i2):
if i1 == i2:
return 0
if (i1, i2) in M:
return M[(i1, i2)]
if i1 + 1 == i2:
M[(i1, i2)] = matrix_sizes[i1][0] * matrix_sizes[i1][1] * matrix_sizes[i2][1]
return M[(i1, i2)]
_min = float('inf')
for i in range(i1, i2):
_sum = MIN(i1, i) + MIN(i + 1, i2) + matrix_sizes[i1][0] * matrix_sizes[i][1] * matrix_sizes[i2][1]
if _sum < _min:
_min = _sum
M[(i1, i2)] = _min
return M[(i1, i2)]
answer = MIN(0, len(matrix_sizes) - 1)
return answer
if __name__ == '__main__':
result = solution([[5,3],[3,10],[10,6]])
print(f'result = {result}')
assert result == 270 |
46dc24f0bb63753f5eab5114c0e10f9b2510f33b | Kiris-Wu/recipeProj | /EECS337/recipeNT.py | 512 | 3.671875 | 4 | import recipegenerator as recipe
import SL as sl
url = input("Please input URL(type a space in the end then enter): ")
print("You want to transform recipe url is :"+ url)
url=url.strip()
if(url==""):
print("You did not enter anything, using the default link...")
url="https://www.allrecipes.com/recipe/220125/slow-cooker-beef-pot-roast/?clickId=right%20rail0&internalSource=rr_feed_recipe_sb&referringId=237320%20referringContentType%3Drecipe"
myrecipe=recipe.returnRecipe(url)
sl.savingsingle(myrecipe)
|
3bfad7917439fefa88f74c1ceab0626ad744813e | EuricoDNJR/beecrowd-URI | /Em Python/1173.py | 133 | 3.546875 | 4 | first = int(input())
n = [first]
for i in range(0, 9):
n.append(n[i] * 2)
for i in range(10):
print("N[%d] = %d" % (i, n[i])) |
0a40bfd5e6e93bf7327296a4736e489dce891010 | deeplymore/erp | /get_summary.py | 2,573 | 3.84375 | 4 | # -*- coding: utf-8 -*-
def math_test():
a_contents = int(input("请输入第一种类型可以乘坐或拥有的个数:"))
a_price = int(input("请输入第一个类型的价格:"))
b_contents = int(input("请输入第二种类型可以乘坐或拥有的个数:"))
b_price = int(input("请输入第二个类型的价格:"))
print("--------------------------------------------------------------------------")
print("第一步: 我们来选择出哪种类型的最划算(单价最低)")
a_per_price = a_price/a_contents
b_per_price = b_price/b_contents
print("第一种类型的单价是: {}, 第二种类型的单价是:{}".format(a_per_price, b_per_price), end=". ")
if a_per_price < b_per_price:
print("所以我们尽可能多地选择第一种类型")
selected_contents, selected_price = a_contents, a_price
not_selected_contents, not_selected_price = b_contents, b_price
select_type = "a"
else:
print("所以我们尽可能多地选择第二种类型")
selected_contents, selected_price = b_contents, b_price
not_selected_contents, not_selected_price = a_contents, a_price
select_type = "b"
total_number = int(input("请输入需要的总个数:"))
print("--------------------------------------------------------------------------")
print("第二步: 我们从尽可能多的使用便宜类型来挨个试试......")
a_num = total_number/selected_contents
if select_type == "a":
print("最多需要{}第一种类型,还剩{}个未满足".format(int(a_num), total_number%selected_contents))
else:
print("最多需要{}第二种类型,还剩{}个未满足".format(int(a_num), total_number%selected_contents))
if a_num > int(a_num):
a_num = int(a_num) + 1
for i_a in range(a_num, 0, -1):
diff = total_number - i_a * selected_contents
print("开始从最大的便宜类型开始, 使用{}个便宜类型, 差额是{}".format(i_a, diff))
if diff == 0:
print("使用了{}个便宜类型就可以满足".format(i_a, ))
if diff % not_selected_contents == 0:
i_b = int(diff/not_selected_contents)
print("此时需要便宜类型 {}(个),较贵类型{} (个)".format(i_a, i_b))
print("总价是:{}*{} + {}*{}={}".format(i_a, selected_price, i_b, not_selected_price, i_a*selected_price + i_b*not_selected_price))
break
while True:
math_test()
input("请输入任何键做下一题。。。")
|
1f38ee947a36fc3e1ea2d2bd3a6347f5faf4832a | zhangchizju2012/LeetCode | /747.py | 914 | 3.578125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 19:28:32 2017
@author: zhangchi
"""
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = []
for item in nums:
if len(result) == 0:
result.append(item)
elif len(result) == 1:
if item > result[0]:
result = [item] + result
else:
result.append(item)
else:
if item > result[0]:
result = [item] + [result[0]]
elif item > result[1]:
result[1] = item
if len(result) == 1 or result[0] >= 2 * result[1]:
return nums.index(result[0])
else:
return -1
s = Solution()
print s.dominantIndex([1, 2, 3, 4]) |
ab44f100361e007e42be6013ef3fe9747d7a0ab9 | nielschristiank/DojoAssignments | /Python/pOOP/animal/animal.py | 1,479 | 3.84375 | 4 | class animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print "Animal:", self.name
print "Health:", self.health
print "\n"
return self
class dog(animal):
# def __init__(self, pet_name):
# self.name = "Dog"
# self.pet_name = pet_name
# self.health = 150
def __init__(self, pet_name):
self.name = "Dog"
self.pet_name = pet_name
self.health = 150
def pet(self):
self.health += 5
return self
def displayHealth(self):
print "Name:", self.pet_name
super(dog, self).displayHealth()
return self
class dragon(animal):
def __init__(self, dragon_name):
self.name = "Dragon"
self.dragon_name = dragon_name
self.health = 170
def fly(self):
self.health -= 10
return self
def displayHealth(self):
print "I AM DRAGON!"
print "Name:", self.dragon_name
super(dragon, self).displayHealth()
return self
tiger = animal("Tiger")
tiger.displayHealth().walk().walk().walk().run().run().run().displayHealth()
hazel = dog("Hazel")
hazel.displayHealth().walk().walk().run().run().displayHealth()
drogo = dragon("Drogo")
drogo.displayHealth().fly().fly().fly().displayHealth()
|
614fcc668465fee9bbc3af57696e3f535594a43e | arbalest339/myLeetCodeRecords | /main876middleNode.py | 942 | 3.6875 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@staticmethod
def build(lst):
if not lst:
return
res = ListNode(lst[0])
last = res
for i in range(1, len(lst)):
cur = ListNode(lst[i])
last.next = cur
last = cur
return res
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow = head
if head.next:
fast = head.next
else:
return slow
while fast.next:
fast = fast.next
slow = slow.next
if fast.next:
fast = fast.next
else:
return slow
slow = slow.next
return slow
if __name__ == "__main__":
solution = Solution()
nums = [1,2,3,4,5,6]
head = ListNode.build(nums)
solution.middleNode(head) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.