blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f0306870c55e02ef5c53a351afd6a30217acf968 | samyuktahegde/Python | /datastructures/arrays/insert_element.py | 314 | 4.21875 | 4 | def insert(arr, element):
arr.append(element)
# declaring array and key to insert
arr = [12, 16, 20, 40, 50, 70]
key = 26
# array before inserting an element
print ("Before Inserting: ")
print (arr)
# array after Inserting element
insert(arr, key)
print("After Inserting: ")
print (arr) |
3b78a1d564b7a0f21e46beb612a613a1738a2e02 | EwaGrela/ewagrela.github.io | /little_snakes/count_vowels.py | 1,249 | 3.953125 | 4 |
def counter(n):
count = 0;
vowels = []
for i in "aeiou":
for l in n.lower():
if l==i:
count +=1
return count;
print("counting vowels in a string")
to_count = "Adam Moceri"
print(counter(to_count))
print("counting vowels in an input:")
inp = input("Enter Text and count vowels: ")
print(counter(inp))
print("Making a file, writing to it, adding more text, then reading from it and counting vowels in text read:")
with open("text.txt", "w") as file:
file.write("Add random text to count vowels")
# or write whatever you like, srsly, just practice writing to file here, everyone ;)
with open("text.txt", "a") as fil:
fil.write("and now add even more, cause why not")
# practicing adding more txt to file
# here we are reading stuff from file:
with open("text.txt", "r") as f:
my_text = f.read()
print(counter(my_text))
print("Finally, using BeautifulSoup to count vowels on a website!")
from bs4 import BeautifulSoup
import requests
url = "https://ewagrela.github.io/"
r = requests.get(url)
content = r.text
page = BeautifulSoup(content, "lxml")
print(type(page))
contents = page.find_all()
soup_string =""
for tag in contents:
if tag.string is not None:
soup_string+=tag.string
print(counter(soup_string)) |
b88a2c42c30e2fb453e01cd9fb6b392d043ab3fc | laoshu198838/Data_Structure_and_Algrithm | /02_single_cycle_link.py | 4,040 | 3.703125 | 4 | # coding:utf-8
class Node(object):
"""节点"""
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkcircleList(object):
"""单链表"""
def __init__(self, node=None):
self.__head = node
def is_empty(self):
"""链表是否为空"""
return self.__head is None
def length(self): """链表长度"""
# cur游标,用来移动遍历节点
cur = self.__head
count = 1
if self.is_empty():
return 0
else:
while cur.next != self.__head:
cur = cur.next
count += 1
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
if self.is_empty():
return
else:
if self.length == 1:
print(cur.elem)
else:
while cur.next != self.__head:
print(cur.elem,end=' ')
cur = cur.next
print(cur.elem)
def add(self, item):
"""链表头部添加元素,头插法"""
node = Node(item)
cur = self.__head
if self.is_empty():
cur = node
node.next = node
else:
while cur.next != self.__head:
cur = cur.next
cur.next = node
node.next = self.__head
self.__head = node
def append(self, item):
"""链表尾部添加元素, 尾插法"""
node = Node(item)
if self.is_empty():
self.__head = node
node.next = node
else:
cur = self.__head
while cur.next != self.__head:
cur = cur.next
cur.next = node
node.next = self.__head
def insert(self, pos, item):
"""指定位置添加元素
:param pos 从0开始
"""
node = Node(item)
cur = self.__head
pre = None
count = 1
if pos <= 0:
self.add(item)
print(True)
return
else:
if pos > self.length():
self.append(item)
else:
while count < pos:
cur = cur.next
pre = cur
pre.next = node
node.next = cur
def remove(self, item):
"""删除节点"""
cur = self.__head
pre = None
if self.is_empty():
print(False)
return False
else:
if self.length == 1:
if cur.elem == item:
cur = None
else:
while cur.next != self.__head:
if cur.elem == item:
if cur == self.__head:
self.__head = cur.next
else:
pre.next = cur.next
break
pre = cur
cur = cur.next
def search(self, item):
"""查找节点是否存在"""
cur = self.__head
count = 0
if self.length == 1:
if cur.elem == item:
return True
else:
return False
else:
while cur.next != self.__head:
if cur.elem==item:
return True
count+=1
cur=cur.next
return False
if __name__=='__main__':
sll=SingleLinkcircleList()
print(sll.is_empty())
print(sll.length())
sll.append(10)
print(sll.length())
sll.travel()
sll.append(2)
sll.add(8)
sll.append(3)
sll.append(4)
sll.append(5)
sll.append(6)
sll.travel()
sll.remove(10)
sll.travel()
print(sll.search(8))
sll.insert(0,110)
sll.travel()
sll.insert(100,120)
sll.travel()
print(id(110))
print(id(8)) |
aec065cbf8fc1797f1bda9d5f06f10dbad291f54 | 18684092/AdvProg | /ProjectEuler/General-first-80-problems/problem63.py | 744 | 3.59375 | 4 | ###############
# Problem 63 #
###############
"""
The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power.
How many n-digit positive integers exist which are also an nth power?
"""
# So the easy answer is the sum over i from 2 to 9 of (int)(i/log(i)) plus 1. The extra 1 is for 1^1 since log of 1 is zero we can't divide by zero.
# Obviously I didn't know that and brute force can't do it.
import time, math
print("Problem 63")
start = time.time()
count = 0
for n in range(2, 9):
count += int(n/math.log10(n))
end = time.time()
print("There are",count + 1,"powerful numnbers")
print("Time taken:", int((end - start)*100) / 100, "Seconds")
print()
|
ae6154d4c17695d2591912af57e2192234408ae6 | chaitanya-j/python-learning | /Basics/Programs on loops/loop_missle.py | 497 | 3.90625 | 4 | # MISSILE DETECTION PROGRAM #
import time
no = int(input("How many times do i scan this area?:"))
for z in range(no):
print("SCANNING THE AREA.....")
time.sleep(2)
Detected = input("detcted or not?? yes/no:")
if Detected == "yes":
print("MISSILE DETECTED LAUNCHING ANTI-MISSILE BRAMHOS*****")
print(3)
time.sleep(2)
print(2)
time.sleep(2)
print(1)
time.sleep(2)
print('**Boom**')
if Detected == "no":
print("MISSILE NOT DETECTED ... SAFE")
|
8f66b30156f73428d8d83b09b757ce17d179203a | gem5/gem5 | /ext/ply/example/unicalc/calc.py | 2,532 | 3.796875 | 4 | # -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables. This is from O'Reilly's
# "Lex and Yacc", p. 63.
#
# This example uses unicode strings for tokens, docstrings, and input.
# -----------------------------------------------------------------------------
import sys
sys.path.insert(0, "../..")
tokens = (
'NAME', 'NUMBER',
'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'EQUALS',
'LPAREN', 'RPAREN',
)
# Tokens
t_PLUS = ur'\+'
t_MINUS = ur'-'
t_TIMES = ur'\*'
t_DIVIDE = ur'/'
t_EQUALS = ur'='
t_LPAREN = ur'\('
t_RPAREN = ur'\)'
t_NAME = ur'[a-zA-Z_][a-zA-Z0-9_]*'
def t_NUMBER(t):
ur'\d+'
try:
t.value = int(t.value)
except ValueError:
print "Integer value too large", t.value
t.value = 0
return t
t_ignore = u" \t"
def t_newline(t):
ur'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print "Illegal character '%s'" % t.value[0]
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lex.lex()
# Parsing rules
precedence = (
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE'),
('right', 'UMINUS'),
)
# dictionary of names
names = {}
def p_statement_assign(p):
'statement : NAME EQUALS expression'
names[p[1]] = p[3]
def p_statement_expr(p):
'statement : expression'
print p[1]
def p_expression_binop(p):
'''expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression'''
if p[2] == u'+':
p[0] = p[1] + p[3]
elif p[2] == u'-':
p[0] = p[1] - p[3]
elif p[2] == u'*':
p[0] = p[1] * p[3]
elif p[2] == u'/':
p[0] = p[1] / p[3]
def p_expression_uminus(p):
'expression : MINUS expression %prec UMINUS'
p[0] = -p[2]
def p_expression_group(p):
'expression : LPAREN expression RPAREN'
p[0] = p[2]
def p_expression_number(p):
'expression : NUMBER'
p[0] = p[1]
def p_expression_name(p):
'expression : NAME'
try:
p[0] = names[p[1]]
except LookupError:
print "Undefined name '%s'" % p[1]
p[0] = 0
def p_error(p):
if p:
print "Syntax error at '%s'" % p.value
else:
print "Syntax error at EOF"
import ply.yacc as yacc
yacc.yacc()
while 1:
try:
s = raw_input('calc > ')
except EOFError:
break
if not s:
continue
yacc.parse(unicode(s))
|
871a5dcff233df3467270c90ba4bc695910ed4bb | hanlsin/udacity_DLNF | /Part2.NeuralNetworks/L9.TensorFlow/classify_nn_train.py | 3,570 | 3.59375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('.', one_hot=True, reshape=False)
import numpy as np
train_imgs = mnist.train.images
print(train_imgs.shape)
print(train_imgs[0].shape)
import matplotlib.pyplot as plt
img = (train_imgs[0] * 255).astype("uint8")
plt.imshow(img.reshape([28, 28]))
# plt.show()
'''
Learning Parameters
'''
learning_rate = 0.001
training_epochs = 1
# Decrease batch size if you don't have enough memory
batch_size = 128
display_step = 1
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
n_hidden_layer = 256 # layer number of features
# Store layers weight & bias
weights = {
'hidden_layer': tf.Variable(tf.random_normal([n_input, n_hidden_layer]), name='w_h'),
'out': tf.Variable(tf.random_normal([n_hidden_layer, n_classes]), name='w_o')
}
biases = {
'hidden_layer': tf.Variable(tf.random_normal([n_hidden_layer]), name='b_h'),
'out': tf.Variable(tf.random_normal([n_classes]), name='b_o')
}
# tf Graph input
x = tf.placeholder("float", [None, 28, 28, 1], name='x')
y = tf.placeholder("float", [None, n_classes], name='y')
x_flat = tf.reshape(x, [-1, n_input])
# probability to keep units
keep_prob = tf.placeholder(tf.float32)
# Hidden layer with RELU activation
layer_1 = tf.add(
tf.matmul(x_flat, weights['hidden_layer']), biases['hidden_layer'])
layer_1 = tf.nn.relu(layer_1)
layer_1 = tf.nn.dropout(layer_1, keep_prob)
# Output layer with linear activation
logits = tf.add(tf.matmul(layer_1, weights['out']), biases['out'])
# Define loss and optimizer
cost = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))
optimizer = tf.train.GradientDescentOptimizer(
learning_rate=learning_rate).minimize(cost)
# Calculate accuracy
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(
tf.cast(correct_prediction, tf.float32), name='accuracy')
# Saving Variables
save_file = './model.ckpt'
saver = tf.train.Saver()
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
sess.run(init)
# Training cycle
for epoch in range(training_epochs):
total_batch = int(mnist.train.num_examples / batch_size)
# Loop over all batches
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
# Run optimization op (backprop) and cost op (to get loss value)
result = sess.run([optimizer, cost],
feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5})
# print(result)
# Print status for every 10 epochs
if epoch % 10 == 0:
valid_accuracy = sess.run(
accuracy,
feed_dict={
x: mnist.validation.images,
y: mnist.validation.labels,
keep_prob: 1.0})
print('Epoch {:<3} - Validation Accuracy: {}'.format(
epoch,
valid_accuracy))
valid_accuracy = sess.run(
accuracy,
feed_dict={
x: mnist.validation.images,
y: mnist.validation.labels,
keep_prob: 1.0})
print('Validation Accuracy: {}'.format(valid_accuracy))
print(weights['hidden_layer'].eval()[0])
print(weights['out'].eval()[0])
print(biases['hidden_layer'].eval()[0])
print(biases['out'].eval()[0])
saver.save(sess, save_file)
|
1f521d8e9bcf0348778a656f012d9278406d2ada | oopxiajun/python | /base_grammar/isinstance_type.py | 672 | 3.78125 | 4 | '''
Created on 2019年11月19日
@author: Administrator
'''
num=1.1
print(isinstance(num, int)) #False
print(isinstance(num, float)) #True
print(isinstance(num, bool)) #False
print(isinstance(num, complex)) #False
num=2
print(isinstance(num, int)) #True
a=1
b=2.2
d=2
c=a+b
print (c)
c=a/d #结果是小数
print (c)
c=a//d #结果是求商(类似于c#的)
print (c)
c=a%d #结果是求余数(求模)
print (c)
print(3 * 7)
print(2 ** 3)
print(2 ** 5)
"""
isinstance 和 type 的区别在于:
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
""" |
7cda4fd0f2538a12b0c626a529ad25b0a7d6754e | shivamkaushik12007/practice | /leetCode/sumNumbersRootToLeaf.py | 594 | 3.625 | 4 | # 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:
sum=0
def sumNumbers(self, root: TreeNode) -> int:
self.checkNode(root,0)
return self.sum
def checkNode(self,root,x):
if(root==None):
return
p=(x*10)+root.val
if(root.left==None and root.right==None):
self.sum+=p
return
self.checkNode(root.left,p)
self.checkNode(root.right,p)
|
18908a97fdd16d6a2c5f72e3360298966c8ea5a7 | snarkfog/python_learning | /lesson_7/slicing.py | 281 | 3.953125 | 4 | my_list = [5, 7, 9, 1, 1, 2]
sub_list = my_list[:3]
print(sub_list)
print(my_list[2:-2])
print(my_list[4:5])
sub_list = my_list[:-1:2]
print(sub_list)
print(my_list[2:-2:2])
print(my_list[::-1])
print(my_list[2:])
print(my_list[2::2])
print(my_list[:-2])
print(my_list[::-2])
|
c48f6d7e74211baf2d1ee9a1146e3d32a233bd3e | sarthak815/MyCAP_AI | /Dictionary_deletion.py | 313 | 4.0625 | 4 | a = {"India":"Delhi",
"France":"Paris",
"United Kingdom":"London",
"USA":"Washington DC"}
print(a)
c = "y"
while c == "y":
b = input("Enter country to be deleted: ")
del a[b]
c = input("Would you like to delete another element(y/n):")
print(f"The updated dictionary is\n{a}")
|
71e3187b7fc1b9c263909175606b62d51d9f1f00 | afelfgie/GameAndAnimation | /robot.py | 3,938 | 3.796875 | 4 | #! /usr/bin/python
#Author : GunadiCBR & afel
#Date : 30-09-2018
#Team : Mls18hckr
#Github : https://github.com/afelfgie
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
import random
from random import randrange, randint
def printRobot(win, pos_x, pos_y, size):
''' Prints the Robot '''
for i in range(size):
for j in range(size):
win.addch(pos_y + i, pos_x + j, 'X')
def printDefuses(win, defuses):
''' Print the defuse codes '''
for i in defuses:
win.addch(i[0], i[1], '#')
def printBomb(win, bombPos):
''' Prints the bomb '''
win.addch(bombPos[0], bombPos[1], '*')
def checkDefuse(pos_x, pos_y, size, defuses):
''' Checks if the Robot has collected a defuse code '''
for d in defuses:
if d[0] < pos_y + size and d[0] >= pos_y and d[1] < pos_x + size and d[1] >= pos_x:
return d
return []
def checkBomb(pos_x, pos_y, size, bombPos):
''' Checks if the Robot has stepped over a bomb '''
if bombPos[0] < pos_y + size and bombPos[0] >= pos_y and bombPos[1] < pos_x + size and bombPos[1] >= pos_x:
return 1
return 0
def endGame(status, score):
''' Ends the game and displays the final message '''
curses.endwin()
print("\nScore - " + str(score))
if status == 0:
print("Congratulations!! You won the game!!")
else:
print("You lost the game!!")
print("\nThanks for Playing! (http://bitemelater.in).\n")
exit(0)
if __name__ == '__main__':
curses.initscr()
curses.curs_set(0)
width = 50 # Width and
height = 15 # height of the window
win = curses.newwin(15, 50, 0, 0)
win.keypad(1)
win.border(0)
win.nodelay(1)
curses.noecho()
key = -1
defaultKey = KEY_RIGHT # Goes along this path by default
score = 0 # Initializing score
pos_x = 2 # Initial coordinates of
pos_y = 2 # the Robot
size = 3 # Size of the Robot
defuses = []
nDefuses = 5 # Number of defuse codes
while len(defuses) < nDefuses + 1: # Randomly calculating the coordinates of defuse codes
defuses.extend([n for n in [[randint(1, height-2), randint(1, width-2)] for x in range(10)] if (n[0] < pos_y or n[0] > pos_y + size) and (n[1] < pos_x or n[1] > pos_x + size)])
bombPos = defuses[len(defuses) - 1] # Position of bomb is the last coordinate calculated
defuses = defuses[:nDefuses] # Only nDefuses (here, 5) co-ordinates are taken
while key != 27: # Until Esc key is not pressed
win.clear()
win.border(0)
if pos_x <= 0 or pos_y <=0 or pos_x + size >= width or pos_y + size >= height:
''' If the Robot goes out of the boundary '''
endGame(1, score)
printRobot(win, pos_x, pos_y, size)
temp = checkDefuse(pos_x, pos_y, size, defuses)
if temp:
defuses.remove(temp)
score += 1
if checkBomb(pos_x, pos_y, size, bombPos):
if score == 5:
endGame(0, score)
else:
endGame(1, score)
printDefuses(win, defuses)
printBomb(win, bombPos)
win.addstr(0, 2, 'Score: ' + str(score) + ' ')
win.timeout(150);
key = win.getch()
key = defaultKey if key == -1 else key
if key == KEY_RIGHT:
pos_x += 1
defaultKey = key
elif key == KEY_LEFT:
pos_x -= 1
defaultKey = key
elif key == KEY_DOWN:
pos_y += 1
defaultKey = key
elif key == KEY_UP:
pos_y -= 1
defaultKey = key
curses.endwin()
|
1bc67de90ce462d8fcfd9e8e56db985e2faa8ca3 | BiggerDragon/machine-learn-demo | /bin/numpy/day02/demo04.py | 369 | 3.71875 | 4 | import numpy as np
a = np.array([10,11,12,13,14,15,16,17])
b = a.reshape((2,2,2))
print(b)
# 将轴2放在轴0前,其他轴相对位置不变
print(np.rollaxis(b, 2))
# 将轴2滚动到轴1,轴1移动到轴2原来的位置
print('\n')
print(np.rollaxis(b,2,1))
# 交换数组的两个轴
a = np.arange(8).reshape(2,2,2)
print(a)
print(np.swapaxes(a, 2, 0))
|
b7a6531291bf456203e42b548d447ead7138b175 | DhruvSrivastava-16/LinkedList-Practise | /sublist_reverse.py | 1,124 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 19:02:35 2021
@author: dhruv
"""
class listnode:
def __init__(self,val = 0,next = None):
self.val = val;
self.next = next
def reverse_sublist(List1_n1,s,f):
print("Yo!")
dummy_head = List1_n1
sublist_head = listnode();
temp = List1_n1
for _ in range(1,s-1):
temp = temp.next
sublist_head = temp
print(temp.val) #we have reached the predecessor of the sublist head
sublist_iter = temp.next #we are address 3
for _ in range(f-s):
temp = sublist_iter.next
sublist_iter.next = temp.next
temp.next = sublist_head.next
sublist_head.next = temp
List1_n1 = listnode(11)
List1_n2 = listnode(3)
List1_n3 = listnode(5)
List1_n4 = listnode(7)
List1_n5 = listnode(2)
List1_n6 = listnode(1)
List1_n1.next = List1_n2
List1_n2.next = List1_n3
List1_n3.next = List1_n4
List1_n4.next = List1_n5
List1_n5.next = List1_n6
s = 2
f = 4
reverse_sublist(List1_n1,s,f) |
778899c766bfecf7b452001de40ec9c3fa9eea1c | 150801116/python_100 | /python_100/实例024:斐波那契数列II.py | 306 | 3.84375 | 4 | #题目 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13…求出这个数列的前20项之和。
molecule = 2 #分子
denominator = 1 #分母
sum = 0 #总和
for i in range(20):
sum += molecule/denominator
molecule,denominator = (molecule+denominator),molecule
print("前20项和:",sum) |
d517350eda72ada085900a28c1366f9dad1e5374 | sanshitsharma/pySamples | /binary_search.py | 653 | 3.875 | 4 | #!/usr/bin/python
class BinarySearch:
def __binary_search(self, a, elem, l, r):
if l > r:
return -1
mid = (l+r)/2
if elem == a[mid]:
return mid
elif elem < a[mid]:
return self.__binary_search(a, elem, l, mid-1)
else:
return self.__binary_search(a, elem, mid+1, r)
return -1
@staticmethod
def find(a, elem):
if len(a) == 0:
return -1
return BinarySearch().__binary_search(a, elem, 0, len(a)-1)
def main():
a = [0, 1, 2, 3, 4, 5, 6, 7]
print BinarySearch.find(a, -1)
if __name__ == "__main__":
main() |
cd3a0cbd5117b4ae3c1b5ba208c1a977142271a7 | wadoodalam/RiverCrossingPuzzles | /oldsrc/animation.py | 429 | 3.5 | 4 | '''
Created on Oct 30, 2019
@author: sauga, wadood, and mashfik
'''
class Animation:
def moveBoat(self, x1, y1, x2, y2):
pass
def updateImage(self, charID, imageID):
#Update characters
pass
def moveChar(self, x, y):
#Taking previous x and y coordinates and animates it towards new x and y coordinates
#Move boat to a new location
pass
|
54427e6c259cad594b074b2738b8364e4726cecc | Chinna2002/Python-Lab | /L13-Binary Tree with Single Node.py | 322 | 3.734375 | 4 | print("121910313006","Kadiyala Rohit Bharadwaj")
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def print(self):
print(self.data)
n=int(input("Enter a value to add a node to Binary Tree:"))
r = Node(n)
print("Nodes in Binary Tree are:")
r.print() |
f24b8a204d70c2c4d1d41337b49ad9957c599d3b | josecervan/Python-Developer-EOI | /module2/bot_window/center.py | 1,081 | 3.796875 | 4 | from graphics import *
from random import randint
import sys
def main(width, height, n_points):
win = GraphWin("Exercise-02, Points", width, height)
win.setBackground(color_rgb(0, 0, 0))
x1 = int(width / 4)
x2 = int(3 * width / 4)
y1 = int(height / 4)
y2 = int(3 * height / 4)
for i in range(n_points):
# x = randint(x1, x2)
# y = randint(y1, y2)
x = randint(int(round((1 / 3) * width)), int(round((2 / 3) * width)))
y = randint(int(round((1 / 3) * height)), int(round((2 / 3) * height)))
p = Point(x, y)
# Get random color
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
p.setFill(color_rgb(r, g, b))
p.draw(win)
win.getMouse()
win.close()
if __name__ == '__main__':
if len(sys.argv) != 4:
print('Uso: python center.py <width> <height> <n_points>')
else:
width = int(sys.argv[1])
height = int(sys.argv[2])
n_points = int(sys.argv[3])
main(width, height, n_points)
print('Bye!') |
81160702cb9236bbb727761b1d94050284dde95e | denizgurzihin/PythonBasic | /main.py | 5,467 | 4 | 4 | import math
########################################################################################################################
# first question
print(" Question 1:")
array_1A = [67, 'ankara', 'istanbul', 20, 'izmir']
array_1B = ['izmir', 20, 'istanbul', 'ankara', 67]
print("First array is " + str(array_1A))
print("Second array is " + str(array_1B))
def question_1(arr1, arr2):
length = len(arr1) # ilk arrayin uzunluğunu bulduk
length_2 = len(arr2) # ikinci arrayin uzunluğunu bulduk
if(length==length_2): # iki arrayin uzunluğu eşit mi kontrol ettik
for index in range(length): #eşitse her elemanı tersindeki eleman ile eşitliğini kontrol ettik
if(arr1[index] != arr2[length-index-1]): #eğer eşit olmayan eleman bulursak false return ettik
return False
return True # eşitse True return etttik
else:
return False # eşit değlse False return ettik
sol_1 = question_1(array_1A, array_1B) # yazdığımız function çağırdık ve sonucu değişkene verdik
print("The result is " + str(sol_1))
print("-------------------------------------------------------------------------")
########################################################################################################################
# second question
print("\n Question 2:")
array_2 = [10, 20, 30, 40, 50, 60, 70]
print("The input array is " + str(array_2))
def question_2(arr1):
new_arr = [] # yeni bir array tanımladık
length = len(arr1) # verdiğimiz input arrayin uzunluğunu bulduk
length_half = math.floor(length/2) # ve uzunluğuun yarısını bulup, en yakın en küçük sayıya yuvarladık 4.5sa 4 gibi
length_control = length % 2 # length çiftse 0, tekse 1
if(length_control==0): # eğer çift sayıda eleman varsa, farklı bir şekilde arraye yüjke
for index in range(length): # 0dan başla, arrayin son indexine kadar tekrarla
if (index < length_half): # indeximiz yarıdan azsa
new_arr.append(arr1[length_half + index]) # arraydeki indexi, ortadaki index ve güncel index ile topla ve bunu yeni arraye yükle(append)
if (index >= length_half): # indeximiz yarıya eşit veya fazla ise
new_arr.append(arr1[index - length_half]) #arraydeki indexi, şuanki indexden yarısının indexini çıkar, ve arraye yükle
elif(length_control==1): # eğer tek sayıda eleman varsa, farklı bir şekilde arraye yüjke
for index in range(length):
if (index < length_half): #yukardaki gibi kontrol edip yükledik gene
new_arr.append(arr1[ length_half + index + 1 ])
elif(index == length_half):
new_arr.append(arr1[length_half])
elif(index > length_half):
new_arr.append(arr1[ index - length_half - 1 ])
return new_arr
sol_2 = question_2(array_2)
print("The result array is " + str(sol_2))
print("-------------------------------------------------------------------------")
########################################################################################################################
# third question
print("\n Question3:")
def question_3():
n = input("Enter an Integer: ")
while(len(n)!=1 or ord(n) < 49 or ord(n) > 57): # aldığımız input, 1 ve 9 aralığında tek bir sayı mı diye kontrol edelim.
print(n + " is not a valid input...")
n = input("Enter an Integer: ")
int_n = int(n) # kullanıcıdan aldığımız değeri integer değişkenine çeviriyoruz
result = int_n + (11*int_n) + (111*int_n) + (1111*int_n) + int(11111*int_n) # istenen formulü implemente edip, sonucu buluyoruz
print(" When n is "+str(int_n)+", result of n + nn + nnn + nnnn + nnnnn is " + str(result)) #sonucu ekrana bastırıyoruz
return result # bastırdığımız sonucu ayrıca bir değişkene return ediyoruz
sol_3 = question_3()
print("-------------------------------------------------------------------------")
########################################################################################################################
print("\n Question4: ")
def question_4():
string = input("Enter an string: ") # kullanıcıdan bir yazı istedik
set_string = set(string) # bu yazıda geçen karakterleri bulduk
dictionary = {} # karakterleri koymak için bi sözlük oluşturduk
for elements in set_string: # bulduğumuz karakterler içinden, teker teker seçtkik
number = string.count(elements) # seçtiğimiz karakterin, inputta kaç defa geçtiğini bulduk
dictionary[elements] = number # bulduğumuz sonuçları sözlük yapısına ekledik
print(dictionary) # sözlüğü ekrana bastırdık
return dictionary # ayrıca sözlüğü, bir değişkene return yaptık
sol_4 = question_4()
print("-------------------------------------------------------------------------") |
87fd46bf4e9acd79d5070eaf2456e2f6da7b23a7 | simona-boop/esposito | /stringa 2.py | 298 | 3.671875 | 4 | s=str(input("Inserisci una stringa: "))
ripetizioni=0
for i in range(0, len(s)):
r=l
x=s[i]
for j in range(i+l, len(s)):
if s[i] == s[j]:
r = r + l
if r > ripetizioni:
carattere = x
ripetizioni = r
print(carattere)
print(ripetizioni)
|
95f18fdecc5f9ff7b2130b52d7c269070f3cec9e | annarob/testing | /christopher's programming/rgn.py | 2,311 | 3.515625 | 4 | from tkinter import *
import random
import time
tk = Tk()
canvas = Canvas(tk, width=500, height=500)
canvas.pack()
def random_rectangle(width, height, fill_color):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectangle(x1, y1, x2, y2, fill=fill_color)
pass
for x in range(1, 100):
random_rectangle(400, 400, 'green')
random_rectangle(400, 400, 'red')
random_rectangle(400, 400, 'blue')
random_rectangle(400, 400, 'orange')
random_rectangle(400, 400, 'yellow')
random_rectangle(400, 400, 'pink')
random_rectangle(400, 400, 'purple')
random_rectangle(400, 400, 'violet')
random_rectangle(400, 400, 'magenta')
random_rectangle(400, 400, 'cyan')
random_rectangle(400, 400, '#ffd800')
pass
canvas.create_text(190, 150, text='Robot funland!!!',
font=('Helvitica',50))
robot4 = canvas.create_rectangle(100, 110, 100, 120)
robot1 = canvas.create_rectangle(500, 500, 480, 480,fill='black')
robot2 = canvas.create_rectangle(100, 100, 105, 105,fill='black')
robot3 = canvas.create_rectangle(95, 90, 105, 110)
def moverobot2(event):
canvas.move(robot2, 2, 0)
canvas.move(robot3, 2, 0)
canvas.move(robot4, 2, 0)
canvas.bind_all('<KeyPress-1>', moverobot2)
def moverobot1(event):
canvas.move(robot2, -2, 0)
canvas.move(robot3, -2, 0)
canvas.move(robot4, -2, 0)
canvas.bind_all('<KeyPress-2>', moverobot1)
def moverobot3(event):
canvas.move(robot2, 0, -2)
canvas.move(robot3, 0, -2)
canvas.move(robot4, 0, -2)
canvas.bind_all('<KeyPress-3>', moverobot3)
def moverobot4(event):
canvas.move(robot2, 0, 2)
canvas.move(robot3, 0, 2)
canvas.move(robot4, 0, 2)
canvas.bind_all('<KeyPress-4>', moverobot4)
for x in range(1, 200):
canvas.move(robot1, -2, 0)
tk.update()
time.sleep(0.05)
pass
for x in range(1, 200):
canvas.move(robot1, 0, -2)
tk.update()
time.sleep(0.05)
pass
for x in range(1, 200):
canvas.move(robot1, 2, 0)
tk.update()
time.sleep(0.05)
pass
for x in range(1, 200):
canvas.move(robot1, 0, 2)
tk.update()
time.sleep(0.05)
pass
time.sleep(1)
canvas.create_text(190, 100, text='game over.',
font=('Helvitica',50))
|
b0bbf1ed0a3f9685a54be79df1db4c71929172eb | BTJEducation/ReadMyTimeTable | /6a Read My Timetable.py | 314 | 3.625 | 4 | #Read My Timetable
#----------------------------------------
def readfile(day):
filename=day+".txt"
channel = open(filename,"r+")
lesson=channel.readlines()
channel.close()
return lesson
#----------------------------------------
day=input("Day of week")
lesson=readfile(day)
print(lesson) |
d488a41ac89710f52ac27d260ff5838e88e7e033 | PedroMarco/Day8 | /TryingAppend.py | 187 | 3.671875 | 4 | __author__ = 'acpb859'
list = [0,1,2,3,4]
list2 = []
for x in list:
list2.append(x * 0.5)
print(list2)
list3 = []
for x in list2:
if x <1.5:
list3.append(x)
print(list3) |
1a0b8206c49a2a63b55416cd093a709f89d7db86 | heitorchang/learn-code | /checkio/scientific_expedition/completely_empty.py | 1,298 | 3.609375 | 4 | def completely_empty_visit(val, visited):
# look for infinite loop : c = []; c.append(c)
id_val = id(val)
if id_val in visited:
return False
try:
val = list(val)
if isinstance(val, dict) and len(val) == 1:
if list(val.keys())[0] != '':
return False
elif len(val) != 0:
return all(completely_empty_visit(v, visited+[id_val]) for v in val)
except TypeError:
return False
return True
def completely_empty(val):
return completely_empty_visit(val, [])
def completely_empty_top(val):
try:
return all(map(completely_empty, val))
except:
return False
def test():
assert completely_empty([]) == True, "First"
assert completely_empty([1]) == False, "Second"
assert completely_empty([[]]) == True, "Third"
assert completely_empty([[],[]]) == True, "Forth"
assert completely_empty([[[]]]) == True, "Fifth"
assert completely_empty([[],[1]]) == False, "Sixth"
assert completely_empty([0]) == False, "[0]"
assert completely_empty(['']) == True
assert completely_empty([[],[{'':'No WAY'}]]) == True
assert completely_empty([iter(())]) == True
c = []
c.append(c)
assert completely_empty_top(c) == False
print('Done')
|
cdd1800eb863639ad824ca90cfe285dd4f3ffba8 | mrazzakov/advent-of-code-2020 | /day14/day14-1.py | 4,391 | 4.125 | 4 | # --- Day 14: Docking Data ---
# As your ferry approaches the sea port, the captain asks for your help again. The computer system that runs this port isn't compatible with the docking program on the ferry, so the docking parameters aren't being correctly initialized in the docking program's memory.
# After a brief inspection, you discover that the sea port's computer system uses a strange bitmask system in its initialization program. Although you don't have the correct decoder chip handy, you can emulate it in software!
# The initialization program (your puzzle input) can either update the bitmask or write a value to memory. Values and memory addresses are both 36-bit unsigned integers. For example, ignoring bitmasks for a moment, a line like mem[8] = 11 would write the value 11 to memory address 8.
# The bitmask is always given as a string of 36 bits, written with the most significant bit (representing 2^35) on the left and the least significant bit (2^0, that is, the 1s bit) on the right. The current bitmask is applied to values immediately before they are written to memory: a 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged.
# For example, consider the following program:
# mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# mem[8] = 11
# mem[7] = 101
# mem[8] = 0
# This program starts by specifying a bitmask (mask = ....). The mask it specifies will overwrite two bits in every written value: the 2s bit is overwritten with 0, and the 64s bit is overwritten with 1.
# The program then attempts to write the value 11 to memory address 8. By expanding everything out to individual bits, the mask is applied as follows:
# value: 000000000000000000000000000000001011 (decimal 11)
# mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# result: 000000000000000000000000000001001001 (decimal 73)
# So, because of the mask, the value 73 is written to memory address 8 instead. Then, the program tries to write 101 to address 7:
# value: 000000000000000000000000000001100101 (decimal 101)
# mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# result: 000000000000000000000000000001100101 (decimal 101)
# This time, the mask has no effect, as the bits it overwrote were already the values the mask tried to set. Finally, the program tries to write 0 to address 8:
# value: 000000000000000000000000000000000000 (decimal 0)
# mask: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
# result: 000000000000000000000000000001000000 (decimal 64)
# 64 is written to address 8 instead, overwriting the value that was there previously.
# To initialize your ferry's docking program, you need the sum of all values left in memory after the initialization program completes. (The entire 36-bit address space begins initialized to the value 0 at every address.) In the above example, only two values in memory are not zero - 101 (at address 7) and 64 (at address 8) - producing a sum of 165.
# Execute the initialization program. What is the sum of all values left in memory after it completes?
def fileInput():
f = open(inputFile, 'r')
with open(inputFile) as f:
read_data = f.read().split('\n')
f.close()
return read_data
def splitData(data):
dataLine = []
maxSize = 0
global mem
for line in data:
newLine = line.split(' = ')
if newLine[0] != 'mask':
newLine[0] = int(newLine[0].lstrip("mem[").rstrip("]"))
maxSize = max(maxSize,newLine[0]+1)
newLine[1] = f'{int(newLine[1]):036b}'
dataLine.append(newLine)
mem = [0 for x in range(maxSize)]
return dataLine
def processData(data):
global mask
global mem
global maskCount
for line in data:
if line[0] == 'mask':
mask = line[1]
maskCount = mask.count('X')
else:
line[1] = updateBits(mask,line[1])
mem[line[0]] = int(line[1],2)
def updateBits(mask,bits):
mask = [bit for bit in mask]
bits = [bit for bit in bits]
for i in range(36):
if mask[i] != 'X':
bits[i] = mask[i]
return ''.join(bits)
#///////////////////////////////////////////////////
inputFile = 'day14-input.txt'
mask = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
maskCount = 0
mem = []
if __name__ == "__main__":
data = fileInput()
data = splitData(data)
processData(data)
print(sum(mem)) |
9dce3385021c8538dbd60c2f9be299931a0a8328 | MaryaMohsen/pdsnd_github | /bikeshare_2.py | 10,355 | 4.53125 | 5 | #Import required packages
import time
import pandas as pd
import numpy as np
#dictionary of cities corresponding to their data files
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
months = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6}
days = {'monday': 0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday': 5, 'sunday': 6}
#The following fuction will get the user choices for filters: city, month, and day.
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
#The following loop will get the user's choice of which city to display results.
while True:
#New Edit gives the user more choices to pick the city to ease typing
city = input('Would you like to see data for Chicago/Ch, New York City/NYC, or Washington/WA: ').lower()
if city not in CITY_DATA.keys() and city not in ['ch', 'nyc', 'wa']:
print('this city is not available, please enter one of the three provided cities')
continue
else:
if city == 'ch':
city = 'chicago'
elif city == 'nyc':
city = 'new york city'
elif city == 'wa':
city = 'washington'
city = CITY_DATA[city]
break
#The following loop will get the user choice whether to use filters or display unfiltered results.
while True:
filter = input('Would you like to filter the data by month or day, or not at all? \nPlease chose(yes/no): ').lower()
if filter == 'yes':
filter = True
elif filter == 'no':
filter = False
else:
print('Please enter a valid answer!')
continue
break
#the following loop will get the user choice for filters: whether by month, by day, or include both.
while True:
if filter:
choice = input('What filter do you want to apply? please choose (month/day/both) ').lower()
if choice not in ['month', 'day', 'both']:
print('Please Enter a valid answer!')
continue
if choice == 'month':
month = input('Which month - January, February, March, April, May, or June? ')
if month not in months.keys():
print('This month is invalid, Please Try again.')
continue
else:
month = months[month]
day = days
break
elif choice == 'day':
day = input('Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday? ').lower()
if day not in days.keys():
print('This day is invalid. Please try again.')
continue
else:
day = days[day]
month = months
break
elif choice == 'both':
month = input('Which month - January, February, March, April, May, or June? ').lower()
if month not in months.keys():
print('This month is invalid. Please try again')
continue
month = months[month]
day = input('Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday? ').lower()
if day not in days.keys():
print('This day is invalid. Please try again')
continue
day = days[day]
break
else:
day = days
month = months
break
#Print Separator
print('-'*40)
#Return chosen values
return city, month, day
#The following function will load the data from the provided data files
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(city)
#add a column for day of week extracted from start time column
df['day_of_week'] = pd.to_datetime(df['Start Time']).dt.dayofweek
#add a column for month extracted from start time column
df['month'] = pd.to_datetime(df['Start Time']).dt.month
#add a column for hour extracted from start time column
df['hour'] = pd.to_datetime(df['Start Time']).dt.hour
if day != days:
df = df[df['day_of_week'] == day]
if month != months:
df = df[df['month'] == month]
return df
#The following function will display time statistics of most frequent schedules.
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
most_common_month = df['month'].mode()[0]
for key, value in months.items():
if value == most_common_month:
print('The most common month is {}'.format(key))
# display the most common day of week
most_common_day = df['day_of_week'].mode()[0]
for key, value in days.items():
if value == most_common_day:
print('The most common day is {}'.format(key))
# display the most common start hour
most_common_hour = df['hour'].mode()[0]
print('The most common hour is {}'.format(most_common_hour))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
#The following function will display station statistics of most frequent rides.
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
print('The most commonly used Start Station is: {}'.format(df['Start Station'].mode()[0]))
# display most commonly used end station
print('The most commonly used End Station is: {}'.format(df['End Station'].mode()[0]))
# display most frequent combination of start station and end station trip
print('The most common station combination is: {}'.format((df['Start Station'] + ' to ' + df['End Station']).mode()[0]))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
#The following function will display duration statistics of travel time.
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
trip_duration = pd.to_datetime(df['End Time']) - pd.to_datetime(df['Start Time'])
# display total travel time
total_travel_time = trip_duration.sum()
print('Total trave time was: {}'.format(total_travel_time))
# display mean travel time
mean_travel_time = trip_duration.mean()
print('Average travel time was: {}'.format(mean_travel_time))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
#The following function will display user info statistics of most common user type and gender if applicable.
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
user_types = df['User Type'].value_counts()
print('Counts of each user type is:\n{}'.format(user_types))
# Display counts of gender
try:
user_gender = df['Gender'].value_counts()
print('\nCounts for each gender is:\n{}'.format(user_gender))
except:
print('\nCounts for each gender is: No data available.')
#No gender data available for washington
# Display earliest, most recent, and most common year of birth
try:
earliest_year = df['Birth Year'].min()
print('\nEarliest year: Oldest users were born in {}'.format(earliest_year))
except:
print('\nEarliest year: No available data')
try:
latest_year = df['Birth Year'].max()
print('Latest year: Youngest users were born in {}'.format(latest_year))
except:
print('Latest year: No available data')
try:
most_common_year = df['Birth Year'].value_counts().idxmax()
print('Most common Year of Birth is {}'.format(most_common_year))
except:
print('Most common year of Birth: No available data')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
while True:
raw_data_iterator = 0
display_raw = input('\nWould you like to see some of the raw data for that City? Please choose yes or no.\n')
if display_raw.lower() == 'yes':
print(df.iloc[raw_data_iterator : raw_data_iterator+5])
while True:
display_more = input('Above is displayed 5 rows by the chosen filters.\nDo you want to see the next 5 rows? Please choose yes or no.\n')
if display_more.lower() == 'yes':
raw_data_iterator += 5
print(df.iloc[raw_data_iterator : raw_data_iterator+5])
else:
break
break
else:
break
restart = input('\nWould you like to restart? Please choose yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
507ffaef91cfc749e830b0feae13c24820111b06 | szbrooks2017/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_square.py | 3,883 | 3.515625 | 4 | #!/usr/bin/python3
""" tests for the base class"""
import os
import io
import unittest
import unittest.mock
from models import square
from models.base import Base
Square = square.Square
class TestSquare(unittest.TestCase):
""" tests for Square"""
def test_save_to_file(self):
filename = "Square.json"
if os.path.exists(filename):
os.remove(filename)
Square.save_to_file(None)
with open(filename, 'r') as f:
self.assertEqual(f.read(), '[]')
if os.path.exists(filename):
os.remove(filename)
Square.save_to_file([])
self.assertTrue(os.path.exists(filename))
if os.path.exists(filename):
os.remove(filename)
Square.save_to_file([Square(1, 1, 0, 32)])
self.assertTrue(os.path.exists(filename))
def test_create_rec(self):
s = {"id": 1, "size": 1, "x": 0, "y": 0}
screate = Square.create(**s)
self.assertEqual("[Square] (1) 0/0 - 1", str(screate))
def test_dictionary(self):
s = Square(1, 1, 1, 7)
d = s.to_dictionary()
self.assertEqual({'id': 7, 'size': 1, 'x': 1, 'y': 1}, d)
def test_square_exists(self):
s = Square(3, 3, 5)
self.assertEqual(s.width, 3)
self.assertEqual(s.height, 3)
self.assertEqual(s.x, 3)
self.assertEqual(s.y, 5)
def test_square_width_height_x_exists(self):
s = Square(3, 3, 3)
self.assertEqual(s.width, 3)
self.assertEqual(s.height, 3)
self.assertEqual(s.x, 3)
def test_square_width_height_exists(self):
s = Square(3, 3)
self.assertEqual(s.width, 3)
self.assertEqual(s.height, 3)
def test_width_height_value(self):
with self.assertRaises(ValueError):
s = Square(0, 1)
def test_update(self):
s = Square(1, 0, 0, 1)
self.assertEqual(str(s), "[Square] (1) 0/0 - 1")
s.update(1, 2)
self.assertEqual(str(s), "[Square] (1) 0/0 - 2")
s.update(1, 2, 3)
self.assertEqual(str(s), "[Square] (1) 3/0 - 2")
s.update(1, 2, 3, 4)
self.assertEqual(str(s), "[Square] (1) 3/4 - 2")
def test_negative_value(self):
with self.assertRaises(ValueError):
s = Square(-1, 2, 3)
with self.assertRaises(ValueError):
s = Square(1, -2, 3)
with self.assertRaises(ValueError):
s = Square(1, 2, -3)
def test_area(self):
s = Square(10, 10)
self.assertEqual(s.area(), 100)
def test_area2(self):
s = Square(2, 2, 0, 0)
self.assertEqual(s.area(), 4)
def test_str(self):
s = Square(1, 0, 0, 1)
self.assertEqual(str(s), "[Square] (1) 0/0 - 1")
def test_args(self):
with self.assertRaises(TypeError):
s = Square(1, 1, 1, 1, 1, 1, 1, 1)
def test_value_type(self):
with self.assertRaises(TypeError):
s = Square(1, 1, "4")
with self.assertRaises(TypeError):
s = Square(1, "1", 3)
with self.assertRaises(TypeError):
s = Square("1", 1, 3)
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_display(self, mock_stdout):
s = Square(1)
s.display()
self.assertEqual(mock_stdout.getvalue(), "#\n")
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_display2(self, mock_stdout):
s1 = Square(1, 1, 1)
s1.display()
self.assertEqual(mock_stdout.getvalue(), "\n #\n")
def test_load_from_file(self):
filename = 'Square.json'
if os.path.exists(filename):
os.remove(filename)
self.assertEqual(Square.load_from_file(), [])
Square.save_to_file([])
self.assertTrue(os.path.exists(filename))
if __name__ == '__main__':
unittest.main()
|
f6ee7453e6fd4e465f6517f4ac7320ee31f41be6 | elhamsyahrianputra/Pemrograman-Terstruktur | /Chapter 06/Chapter06_Latihan No.2_c.py | 240 | 3.578125 | 4 | def starFormation1(n):
for star in range(1, n+1):
print(star * "*")
def starFormation2(n):
for star in range (1, n+1):
print((n+1-star) * "*")
def starFormation3(n):
starFormation1(n//2)
starFormation2(n-(n//2))
starFormation3(7) |
8eefd641993ca7aa18e9ffac1e63c67b85b8cbca | ausaki/data_structures_and_algorithms | /leetcode/generate-random-point-in-a-circle/286376927.py | 812 | 3.859375 | 4 | # title: generate-random-point-in-a-circle
# detail: https://leetcode.com/submissions/detail/286376927/
# datetime: Mon Dec 16 21:00:13 2019
# runtime: 144 ms
# memory: 23.1 MB
import math
import random
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
radian = random.random() * math.pi * 2
radius = math.sqrt(random.random()) * self.radius
x = radius * math.cos(radian)
y = radius * math.sin(radian)
return [x + self.x_center, y + self.y_center]
# Your Solution object will be instantiated and called as such:
# obj = Solution(radius, x_center, y_center)
# param_1 = obj.randPoint() |
04d25d91f20151bd515fad46d84b7eb7b8020bcf | Ankitmahida/Catenation | /task1.py | 761 | 3.765625 | 4 | # Exercise 1
a=10,;b=10.20;c='Ankit'
# Exercise 2
a=complex(2,4)
print(type(a))
b=15
a=b
print(type(a))
#Exercise 3
a=10,b=90
Result=a
a=b
y=Result
Print(a)
Print(b)
# Exercise 4
#python version 2
x=raw_input("Enter the value")
print x
#python version3x
input1=eval(input("Enter the value"))
print(x)
# Exercise 5
a, b = input("Enter two numbers between 1-10 : ").split()
print("first value:",a)
print("second value:",b)
z= int(a) + int(b)
print(result)
# Exercise 6
x=input("Enter the number:")
print("The value of number is :",x)
# Exercise 7
a='AnkitMahida'
b='ankitmahida'
c='ANKITMAHIDA'
# Exercise 8
# the value will be changed because python take recent value if have an option for variable.
|
57b9602123431800b4d2bba0507716b360ddb475 | edson-gonzales/SICARIOS | /src/admin_module/user_module/customer.py | 2,556 | 3.59375 | 4 | #customer.py
__author__ = 'Roy Ortiz'
from admin_module.user_module.person import Person
from db.transactions.DBManager import DBManager
class Customer(Person):
"""
Creation of an instance of customer
"""
def __init__(self, first_name, last_name, birth_date, address, phone, email, membership, is_active):
Person.__init__(self, first_name, last_name)
self._address = address
self._birth_date = birth_date
self._phone = phone
self._email = email
self._membership = membership
self._isactive = is_active
def get_birth_date(self):
"""
Returns the customer birth date
:return: the birth date
"""
return self._birth_date
def get_address(self):
"""
Returns the customer address
:return: the address
"""
return self._address
def get_phone_number(self):
"""
Returns the customer phone number
:return: the phone number
"""
return self._phone
def get_email(self):
"""
Returns user personal email
:return: user personal email
"""
return self._email
def get_membership_assigned(self):
"""
Returns current user membership
:return: membership assigned to user
"""
return self._membership
def get_customer_status(self):
"""
Returns an integer that indicates if the customer is active or not 1 for true 0 for false
:return: returns the integer
"""
return self._isactive
def inactive_customer(self):
"""
this method will deactivate user by changing te value to 0
"""
self._is_active = 0
def save_customer (self):
"""
this method will save the customer information
"""
conn = DBManager()
first_name = self.first_name
last_name = self.last_name
birth_date = self._birth_date
address = self._address
phone = self._email
email =self._email
is_active = 1
execution_query = "insert into customer values('"+ first_name + "','" + last_name + "','" + birth_date + "','" + address + "','" + phone + "','" + email + "'," + is_active +")"
try:
conn.query(execution_query)
except ValueError:
print ("there was an error in the process")
|
ca004a03ffb30d75cff01a4b323631d2db67b52a | kiranrraj/100Days_Of_Coding | /Day_48/sphere.py | 1,091 | 4.5625 | 5 | # Title : Sphere Calculations
# Author : Kiran Raj R.
# Date : 1/12/2020
PI = 3.14
print("Enter 's' to calculate volume of Sphere")
print("Enter 'c' to calculate volume of Cylinder")
choice = input().lower()
if choice == 's' :
radius = float(input('Enter the Radius of a Sphere: '))
s_area = 4 * PI * radius * radius
vol = (4 / 3) * PI * radius * radius * radius
print(f"The Surface area of a Sphere: {s_area:.2f}")
print(f"The Volume of a Sphere: {vol:.2f}")
elif choice == 'c':
radius = float(input('Enter the Radius of a Cylinder: '))
height = float(input('Enter the Height of a Cylinder: '))
s_area = 2 * PI * radius * (radius + height)
vol = PI * radius * radius * height
l_s_area = 2 * PI * radius * height
t_area = PI * radius * radius
print(f"The Surface area of a cylinder: {s_area:.2f}")
print(f"The Volume of a cylinder: {vol:.2f}")
print(f"Lateral Surface Area of a cylinder: {l_s_area:.2f} ")
print(f"Top / Bottom Surface Area of a cylinder: {t_area:.2f}")
else:
print("Sorry, option not found")
exit() |
69322814507de3a13d61f3d87ebb16ac0c822362 | cn5036518/xq_py | /python16/day1-21/day009 函数入门/02作业题/练习3.py | 543 | 4.09375 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
3,写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
'''
def greater5(arg): #arg或者obj作为形参的名字
if len(arg) >5:
print('实参的长度大于5')
return True
# return len(arg) >5 #也可以
else:
print('实参的长度小于等于5')
return False
s1 = 'jack'
greater5(s1) #实参的长度小于等于5
li1 = ['jack','tom','bob']
greater5(li1) #实参的长度小于等于5
|
6f3d23dc4cff15137b3d8fd9907f31893c6f2394 | vfedoroff/interview-python | /simple-elevator/solution.py | 19,320 | 3.796875 | 4 | UP = 1
DOWN = 2
FLOOR_COUNT = 6
import time
class Elevator(object):
def __init__(self, logic_delegate, starting_floor=1):
self._current_floor = starting_floor
self._history = [starting_floor]
print ("%s..." % starting_floor)
self._motor_direction = None
self._logic_delegate = logic_delegate
self._logic_delegate.callbacks = self.Callbacks(self)
def call(self, floor, direction):
self._logic_delegate.on_called(floor, direction)
def select_floor(self, floor):
self._logic_delegate.on_floor_selected(floor)
def step(self):
delta = 0
if self._motor_direction == UP: delta = 1
elif self._motor_direction == DOWN: delta = -1
if delta:
self._current_floor = self._current_floor + delta
print("%s..." % self._current_floor)
self._history.append(self._current_floor)
self._logic_delegate.on_floor_changed()
else:
self._logic_delegate.on_ready()
assert self._current_floor >= 1
assert self._current_floor <= FLOOR_COUNT
def run_until_stopped(self):
self.step()
while self._motor_direction is not None: self.step()
def run_until_floor(self, floor):
for _ in range(100):
self.step()
if self._current_floor == floor: break
else: assert False
@property
def history(self):
return self._history
class Callbacks(object):
def __init__(self, outer):
self._outer = outer
@property
def current_floor(self):
return self._outer._current_floor
@property
def motor_direction(self):
return self._outer._motor_direction
@motor_direction.setter
def motor_direction(self, direction):
self._outer._motor_direction = direction
class ElevatorLogic(object):
"""
An incorrect implementation. Can you make it pass all the tests?
Fix the methods below to implement the correct logic for elevators.
The tests are integrated into `README.md`. To run the tests:
$ python -m doctest -v README.md
To learn when each method is called, read its docstring.
To interact with the world, you can get the current floor from the
`current_floor` property of the `callbacks` object, and you can move the
elevator by setting the `motor_direction` property. See below for how this is done.
"""
class Call(object):
def __init__(self, floor, time):
self.floor = floor
self.time = time
def __repr__(self):
return "%d" % self.floor
def __init__(self):
# Feel free to add any instance variables you want.
self.destination_floor = None
self.callbacks = None
self.orders = {}
self.orders[UP] = []
self.orders[DOWN] = []
self.current_direction = None
self.bounded_direction = None
def on_called(self, floor, direction):
"""
This is called when somebody presses the up or down button to call the elevator.
This could happen at any time, whether or not the elevator is moving.
The elevator could be requested at any floor at any time, going in either direction.
floor: the floor that the elevator is being called to
direction: the direction the caller wants to go, up or down
"""
if not self.valid_floor(floor) or direction not in [UP, DOWN]:
return
direction_to_floor = self.direction_to(floor)
if self.current_direction is None:
# Change direction
self.current_direction = direction_to_floor
if self.callbacks.current_floor != floor:
self.index(direction, floor)
# Reorder
self.sort(UP)
self.sort(DOWN)
if self.current_direction == UP and self.orders[UP]:
self.destination_floor = self.orders[UP][0].floor
else:
self.destination_floor = self.orders[direction][0].floor
else:
# Missed the boat, come back later
self.index(self.other_direction(self.current_direction), floor)
# print "direction to floor: ", self.direction_str(direction_to_floor)
self.log("on called")
def index(self, direction, floor):
if not direction:
return
self.orders[direction].insert(0, self.Call(floor, time.time()))
def sort(self, direction):
if direction == UP:
if self.callbacks.motor_direction:
self.orders[UP].sort(key=lambda x: x.floor)
elif all(x.floor > self.callbacks.current_floor for x in self.orders[UP]):
self.orders[UP].sort(key=lambda x: x.floor)
else:
self.orders[UP].sort(key=lambda x: x.time)
elif direction == DOWN:
self.orders[DOWN].sort(key=lambda x: x.time, reverse=True)
else:
pass
@staticmethod
def valid_floor(floor):
return floor >= 1 or floor <= FLOOR_COUNT
def on_floor_selected(self, floor):
"""
This is called when somebody on the elevator chooses a floor.
This could happen at any time, whether or not the elevator is moving.
Any floor could be requested at any time.
floor: the floor that was requested
"""
if not self.valid_floor(floor):
return
direction_to_floor = self.direction_to(floor)
if direction_to_floor is None:
self.log("missed the boat")
return
# Check the other queue for duplicates
other_direction = self.other_direction(direction_to_floor)
if self.orders[other_direction]:
_floor = self.orders[other_direction][0].floor
if _floor == floor:
# Serve that, but not this floor request (line 485)
return
if self.bounded_direction:
self.log("floor selected. bounded direction detected. direction to floor %d: %s"
% (floor, self.direction_str(direction_to_floor))
)
if direction_to_floor == self.bounded_direction:
self.current_direction = self.bounded_direction
self.bounded_direction = None
else:
self.log("floor selection ignored. Mismatch between bounded direction and direction to floor selected")
# self.bounded_direction = None
return
if self.current_direction and self.current_direction != direction_to_floor:
# Set it to wait for requests to move to the other direction
other_direction = self.other_direction(self.current_direction)
self.current_direction = other_direction
self.log("""\
floor selection ignored.
floor selected: %d
Direction to floor: %s.
Must wait for requests to move to the other direction"""
% (floor, self.direction_str(direction_to_floor)))
# Clear for the next call
if self.callbacks.current_floor == self.destination_floor:
self.log("Clear for the next call")
# Reverse again
other_direction = self.other_direction(other_direction)
if self.orders[other_direction] and self.orders[other_direction][0].floor == self.callbacks.current_floor:
self.orders[other_direction].pop(0)
self.current_direction = None
return
self.index(direction_to_floor, floor)
# sort the list so closer floors are attended first
# self.orders[direction_to_floor].sort()
self.sort(direction_to_floor)
if self.current_direction is None:
self.current_direction = direction_to_floor
self.destination_floor = self.orders[self.current_direction][0].floor
self.log("on floor selected")
def on_floor_changed(self):
"""
This lets you know that the elevator has moved one floor up or down.
You should decide whether or not you want to stop the elevator.
"""
if self.destination_floor == self.callbacks.current_floor:
self.log("on change. Destiny %d reached" % self.destination_floor)
self.callbacks.motor_direction = None
if self.current_direction and self.orders[self.current_direction]:
self.orders[self.current_direction].pop(0)
else:
if self.current_direction and self.orders[self.other_direction(self.current_direction)]:
self.orders[self.other_direction(self.current_direction)].pop(0) # something had to be served (
if self.current_direction and self.orders[self.current_direction]:
next_destination = self.orders[self.current_direction][0].floor
if next_destination != self.callbacks.current_floor:
self.destination_floor = next_destination
else:
self.orders[self.current_direction].pop(0) # drop it, already there
self.destination_floor = None
self.bounded_direction = self.current_direction
else:
self.bounded_direction = self.current_direction
if self.current_direction and not self.orders[self.current_direction]:
other_direction = self.other_direction(self.current_direction)
if other_direction and self.orders[other_direction]:
self.current_direction = other_direction
# Set the new target floor
if self.orders[self.current_direction]:
self.destination_floor = self.orders[self.current_direction][0].floor
if self.is_idle():
self.current_direction = None # Elevator is idle
if self.callbacks.current_floor <= 1 and self.callbacks.motor_direction == DOWN:
# self.callbacks.current_floor = 1
self.callbacks.motor_direction = None
self.current_direction = None
self.bounded_direction = None
if self.callbacks.motor_direction == UP and self.callbacks.current_floor == FLOOR_COUNT:
self.callbacks.motor_direction = DOWN
self.bounded_direction = None
self.destination_floor = FLOOR_COUNT
self.log("on_changed")
def on_ready(self):
"""
This is called when the elevator is ready to go.
Maybe passengers have embarked and disembarked. The doors are closed,
time to actually move, if necessary.
"""
if self.destination_floor and not self.valid_floor(self.destination_floor):
self.destination_floor = None
self.callbacks.motor_direction = None
# print "on ready: dest floor: %d" % self.destination_floor
if self.destination_floor > self.callbacks.current_floor:
self.callbacks.motor_direction = UP
elif self.destination_floor < self.callbacks.current_floor:
self.callbacks.motor_direction = DOWN
else:
self.bounded_direction = None
if self.callbacks.motor_direction == DOWN and self.callbacks.current_floor == 1:
self.callbacks.motor_direction = None
if self.callbacks.motor_direction == UP and self.callbacks.current_floor == FLOOR_COUNT:
self.callbacks.motor_direction = None
self.bounded_direction = None
self.destination_floor = None
self.log("on ready")
def direction_to(self, floor):
direction = None
if floor > self.callbacks.current_floor:
direction = UP
elif floor < self.callbacks.current_floor:
direction = DOWN
return direction
def is_idle(self):
return not self.orders[UP] and not self.orders[DOWN]
@staticmethod
def other_direction(direction):
if UP == direction:
return DOWN
if DOWN == direction:
return UP
return None
@staticmethod
def direction_str(direction):
if UP == direction:
return "UP"
elif DOWN == direction:
return "DOWN"
else:
return "None"
def status(self):
return """\
Current direction: %s
Current floor: %s
Destination floor: %s
Bounded direction: %s
orders UP: %s
orders DOWN: %s
""" % (self.direction_str(self.current_direction),
self.callbacks.current_floor,
self.destination_floor,
self.direction_str(self.bounded_direction),
self.orders[UP],
self.orders[DOWN])
def log(self, msg):
# print "%s. \nstatus:\n%s" % (msg, self.status())
pass
if __name__ == "__main__":
e = Elevator(ElevatorLogic())
e.call(5, DOWN)
e.run_until_stopped()
e.select_floor(1)
e.call(3, DOWN)
e.run_until_stopped()
e.run_until_stopped()
assert e.history == [1, 2, 3, 4, 5, 4, 3, 2, 1]
print("------")
"""
Elevators want to keep going in the same direction. An elevator will serve as many requests in one direction as it can before going the other way. For example, if an elevator is going up, it won't stop to pick up passengers who want to go down until it's done with everything that requires it to go up.
"""
e = Elevator(ElevatorLogic())
e.call(2, DOWN)
e.select_floor(5)
e.run_until_stopped()
e.run_until_stopped()
assert e.history == [1, 2, 3, 4, 5, 4, 3, 2]
print("------")
"""
In fact, if a passenger tries to select a floor that contradicts the current direction of the elevator, that selection is ignored entirely. You've probably seen this before. You call the elevator to go down. The elevator shows up, and you board, not realizing that it's still going up. You select a lower floor. The elevator ignores you.
"""
# e = Elevator(ElevatorLogic())
# e.select_floor(3)
# e.select_floor(5)
# e.run_until_stopped()
# e.select_floor(2)
# e.run_until_stopped()
# e.run_until_stopped() # nothing happens, because e.select_floor(2) was ignored
# e.select_floor(2)
# e.run_until_stopped()
# print("------")
# """
# The process of switching directions is a bit tricky. Normally, if an elevator going up stops at a floor and there are no more requests at higher floors, the elevator is free to switch directions right away. However, if the elevator was called to that floor by a user indicating that she wants to go up, the elevator is bound to consider itself going up.
# """
# e = Elevator(ElevatorLogic())
# e.call(2, DOWN)
# e.call(4, UP)
# e.run_until_stopped()
# e.select_floor(5)
# e.run_until_stopped()
# e.run_until_stopped()
# print("------")
# """
# If nobody wants to go further up though, the elevator can turn around.
# """
# e = Elevator(ElevatorLogic())
# e.call(2, DOWN)
# e.call(4, UP)
# e.run_until_stopped()
# e.run_until_stopped()
# print("------")
# """
# If the elevator is called in both directions at that floor, it must wait once for each direction. You may have seen this too. Some elevators will close their doors and reopen them to indicate that they have changed direction.
# """
# e = Elevator(ElevatorLogic())
# e.select_floor(5)
# e.call(5, UP)
# e.call(5, DOWN)
# e.run_until_stopped()
# """
# Here, the elevator considers itself to be going up, as it favors continuing in the direction it came from.
# """
# e.select_floor(4) # ignored
# e.run_until_stopped()
# """
# Since nothing caused the elevator to move further up, it now waits for requests that cause it to move down.
# """
# e.select_floor(6) # ignored
# e.run_until_stopped()
# """
# Since nothing caused the elevator to move down, the elevator now considers itself idle. It can move in either direction.
# """
# e.select_floor(6)
# e.run_until_stopped()
# print("------")
# """
# Keep in mind that a user could call the elevator or select a floor at any time. The elevator need not be stopped. If the elevator is called or a floor is selected before it has reached the floor in question, then the request should be serviced.
# """
# e = Elevator(ElevatorLogic())
# e.select_floor(6)
# e.run_until_floor(2) # elevator is not stopped
# e.select_floor(3)
# e.run_until_stopped() # stops for above
# e.run_until_floor(4)
# e.call(5, UP)
# e.run_until_stopped() # stops for above
# """
# On the other hand, if the elevator is already at, or has passed the floor in question, then the request should be treated like a request in the wrong direction. That is to say, a call is serviced later, and a floor selection is ignored.
# """
# e = Elevator(ElevatorLogic())
# e.select_floor(5)
# e.run_until_floor(2)
# e.call(2, UP) # missed the boat, come back later
# e.step() # doesn't stop
# e.select_floor(3) # missed the boat, ignored
# e.step() # doesn't stop
# e.run_until_stopped() # service e.select_floor(5)
# e.run_until_stopped() # service e.call(2, UP)
# """
# No amount of legal moves should compel the elevator to enter an illegal state. Here, we run a bunch of random requests against the simulator to make sure that no asserts are triggered.
# """
# import random
# e = Elevator(ElevatorLogic())
# try:
# print("-")
# finally:
# for i in range(100000):
# r = random.randrange(6)
# if r == 0: e.call(
# random.randrange(FLOOR_COUNT) + 1,
# random.choice((UP, DOWN)))
# elif r == 1: e.select_floor(random.randrange(FLOOR_COUNT) + 1)
# else: e.step()
# """
# An elevator is called but nobody boards. It goes idle.
# """
# e = Elevator(ElevatorLogic())
# e.call(5, UP)
# e.run_until_stopped()
# e.run_until_stopped()
# e.run_until_stopped()
# """
# The elevator is called at two different floors.
# """
# e = Elevator(ElevatorLogic())
# e.call(3, UP)
# e.call(5, UP)
# e.run_until_stopped()
# e.run_until_stopped()
# """
# Like above, but called in reverse order.
# """
# e = Elevator(ElevatorLogic())
# e.call(5, UP)
# e.call(3, UP)
# e.run_until_stopped()
# e.run_until_stopped()
# """
# The elevator is called at two different floors, but going the other direction.
# """
# e = Elevator(ElevatorLogic())
# e.call(3, DOWN)
# e.call(5, DOWN)
# e.run_until_stopped()
# e.run_until_stopped()
# """
# The elevator is called at two different floors, going in opposite directions.
# """
# e = Elevator(ElevatorLogic())
# e.call(3, UP)
# e.call(5, DOWN)
# e.run_until_stopped()
# e.run_until_stopped()
|
cbbf8a818af7b40a6219fe7c451f626bcb45b086 | aluisq/Python | /estrutura_repeticao/ex7.py | 143 | 3.953125 | 4 | x = 1
soma = 0
while x <= 10:
y = abs(float(input("Digite um número: ")))
soma += y # soma = soma + y
x += 1
print((soma / 10))
|
eba6e4ee462843c48e13fd910eebe845144245ef | p02e909/web_mk | /exercises/ex7_6.py | 1,495 | 3.59375 | 4 | #!/usr/bin/env python3
import random # NOQA
import string # NOQA
def your_function(length=16):
'''Tạo một mật khẩu ngẫu nhiên (random password),
mật khẩu này bắt buộc phải chứa ít nhất 1 chữ thường,
1 chữ hoa, 1 số, 1 ký tự punctuation (string.punctuation).
'''
# Xoá dòng sau và viết code vào đây set các giá trị phù hợp
raise NotImplementedError("Học viên chưa làm bài này")
def generate_and_append(length, passwords=[]):
'''
Sinh password ngẫu nhiên và append vào list passwords.
Nếu không có list nào được gọi với function, trả về list chứa một
password vừa tạo ra.
Sửa argument tùy ý.
'''
pass
def solve(input_data):
result = your_function(input_data)
return result
def main():
'''
Sinh ra 10 password và viết code đảm bảo chúng đều khác nhau.
'''
passwords8 = generate_and_append(8)
passwords10 = generate_and_append(10)
passwords12 = generate_and_append(12)
passwords12 = generate_and_append(12, passwords12)
assert len(passwords8) == 1, passwords8
assert len(passwords10) == 1, passwords10
assert len(passwords12) == 2, passwords12
for ps in passwords8, passwords10, passwords12:
for p in ps:
plen = len(p)
print('Mậu khẩu tự tạo {0} ký tự của bạn là {1}'.format(plen, p))
if __name__ == "__main__":
main()
|
e31b2677f51d1174fff2c6e099483a0cf7b92c7f | Tarun17NE404/python-programs | /Factorial.py | 131 | 4.09375 | 4 | n = int(input("Enter the number"))
output = 1
for i in range(n,0,-1):
output = output*i
print("Factorial of", n , "is", output) |
64bad160d45e1f011a2a8da15f8bce64c5d330ac | snejy/Programming101 | /week0/prime_factorization/solution.py | 557 | 3.703125 | 4 | def prime_factorization(n):
if is_prime(n):
return [(n,1)]
else:
result=[]
for i in divisors(n):
k = 0
while n % i == 0:
k=k+1
if is_prime(n):
result.append((n,k))
return result
n=n//i
result.append((i,k))
return result
def is_prime(n):
return len([x for x in range(1, abs(n)) if abs(n) % x == 0]) == 1
def divisors(n):
return [x for x in range (1, n + 1) if n % x == 0 and is_prime(x)]
|
fdef3ac657a9faa183d2defbbe1ccc88fdafaa0b | Srinjana/CC_practice | /MATH PROB/evnnum.py | 525 | 3.921875 | 4 | # a string has a mixture of letter, integer and special char. from here find the largest even number combination possible from the available digits after removing duplicates. If no even number, return -1.
# Author @Srinjana
import itertools
s = input()
s_unique = set()
x = -1
for i in s:
if i.isdigit():
s_unique.add(i)
# for i in s:
# print(i)
comb = list(itertools.permutations(s_unique))
for i in comb:
num = "".join(i)
if int(num)%2 == 0 and int(num)>x:
x= int(num)
print(x)
|
6b4a26baa7373f82e160778bd390b5e2d292df6d | mjoze/kurs_python | /codewars/Format_a_string_of_names.py | 1,166 | 4.09375 | 4 | """Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'
namelist([ {'name': 'Bart'} ])
# returns 'Bart'
namelist([])
# returns ''
Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'."""
# def namelist(names):
# b = []
# for i in names:
# for v in i.values():
# b.append(v)
# if len(b) == 0:
# return ''
# if len(b) == 1:
# return b[0]
# if len(b) == 2:
# return ' & '.join(b)
# if len(b) > 2:
# c = b[0:len(b)-2]
# d = b[len(b)-2:]
# return ', '.join(c) + ', ' + ' & '.join(d)
def namelist(names):
if len(names) > 1:
return '{} & {}'.format(', '.join(name['name'] for name in names[:-1]),
names[-1]['name'])
elif names:
return names[0]['name']
else:
return ''
|
7f30fd1a8f458aa067417f6a616c450242e7fcf6 | LEEHyokyun/Sparta_algorithm | /week1/01_00_find_alphabet.py | 368 | 3.953125 | 4 | print("a".isalpha())
# 지정변수가 문자인지 확인
array = "Hello world"
# 문자열의 해당 자리의 문자가 문자인지 확인
print(array[2].isalpha())
print(array[5].isalpha())
alphabet_occurence_array = [0]*26
# 해당 배열에는 원소 0이 26개로 배열되어 저장됨
ord("a")
print(ord('a')) #97, 아스키코드
print(ord('a')-ord('c')) |
d9d2abb6f21855a3ec27cd285bf4f8325cbfa077 | TianyuDu/csc148 | /lecture/mar192018_0101.py | 505 | 3.875 | 4 | # March 19 2018, Lecture 0101
def fib(n: int) -> int:
""" Return nth fibonacci number
>>> fib(0)
0
>>> fib(1)
1
>>> fib(3)
2
"""
if n < 2:
return n
else:
return fib(n - 2) + fib(n - 1)
def fib_mem(n: int, seen: dict) -> int:
"""
return nth fibonacci number *quickly*
"""
if n not in seen:
if n < 2:
seen[n] = n
else:
seen[n] = fib_mem(n - 2, seen) + fib_mem(n - 1, seen)
return seen[n] |
334920f67ac6cafe8e47cfcff0d6859d4307c05f | NAKSEC/finance_book | /fin_scrapy/maya/string_utils.py | 625 | 3.515625 | 4 | import re
def is_year_by_regex(string):
regex_pattern = "(19|20)\d{2}"
result = re.match(regex_pattern, string)
return result
def remove_empty_key_value_from_dictionary(dictionary_of_strings):
new_dictionary = {}
regex = re.compile(r'[\(*\)\n\r\t]')
for elem in list(dictionary_of_strings.keys()):
key = regex.sub("", elem)
value = regex.sub("", dictionary_of_strings[elem])
if key != None and bool(value.strip()) == True:
new_dictionary[key] = value
return new_dictionary
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
|
56322c3258e0bbb6c2596fb776e4e9a756bf33ab | DimaDanilov/algoritm-programming | /1 Sort/heapsort.py | 1,361 | 3.734375 | 4 | import time
arr_num = 1000 # Выбор файла
filename = "generatedfiles/" + str(arr_num) + ".txt"
# Считывание массива из файла
file = open(filename, "r")
arr = (file.read()).split(' ') # Считывание строки и разбиение её на массив
for i in range(len(arr)):
arr[i] = int(arr[i]) # Перевод массива строк в массив чисел
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[largest] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
start_time = time.time()
heapSort(arr)
print("--- %s seconds ---" % (time.time() - start_time))
# Запись в файл
filename = "sortedfiles/heapsort_"+str(arr_num)+".txt"
file = open(filename, "w")
for i in range(len(arr)):
file.write(str(arr[i]))
if i!=(len(arr)-1): # Проверка последнее ли это число, чтобы ставить пробел
file.write(' ')
file.close() |
c0f99b18aa87f30ed6a90473bfbeb00b9e787ab4 | zgle-fork/OpenCV-Python-Tutorial | /ch09-图像的基础操作/9.itemset.py | 348 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import cv2
import numpy as np
img = cv2.imread('../data/messi5.jpg')
#
px = img[100, 100]
print(px)
blue = img[100, 100, 0]
print(blue)
#
img[100, 100] = [255, 255, 255]
print(img[100, 100])
# 获取像素值及修改的更好方法。
print(img.item(10, 10, 2))
img.itemset((10, 10, 2), 100)
print(img.item(10, 10, 2))
|
e7ba3fd84f12e426cb6324261cc6fdf5acac7096 | fander2468/pythoncrashcourseproblems | /chapter7/pizza_toppings.py | 219 | 4.1875 | 4 |
pizza_toppings = ''
while pizza_toppings != 'quit':
pizza_toppings = input("Enter a pizza topping, enter 'quit' to quit ")
if pizza_toppings == 'quit':
continue
print('I add ' + pizza_toppings)
|
818f452713e6fce3908f59df610f6a9e4dd073b9 | mo2274/CS50 | /pset7/houses/import.py | 1,508 | 4.375 | 4 | from sys import argv, exit
import cs50
import csv
# check if the number of arguments is correct
if len(argv) != 2:
print("wrong argument number")
exit(1)
# create database
db = cs50.SQL("sqlite:///students.db")
# open the input file
with open(argv[1], "r") as characters:
# Create Reader
reader_csv = csv.reader(characters)
# skip the first line in the file
next(reader_csv)
# Iterate over csv
for row in reader_csv:
# get the name of the character
name = row[0]
# counter for the number of words in the name
count = 0
# check if the name is three words or two
for c in name:
if c == ' ':
count += 1
# if the name contain three words
if count == 2:
# split the name into three words
name_list = name.split(' ', 3)
first = name_list[0]
middle = name_list[1]
last = name_list[2]
# if the name contain two words
if count == 1:
# split the name into two words
name_list = name.split(' ', 2)
first = name_list[0]
middle = None
last = name_list[1]
# get the name of house
house = row[1]
# get the year of birth
birth = int(row[2])
# insert the data into the table
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", first, middle, last, house, birth)
|
520454f7fc3fe0c05bdc0ee882dffb2c9d35566c | hussamh10/EvolutionaryScheduler | /xmlconverterforunitime.py | 6,811 | 3.5625 | 4 | import csv
import xlrd
import datetime
def csv_from_excel(myfile,mysheet='Sheet1'):
wb = xlrd.open_workbook(myfile)
sh = wb.sheet_by_name(mysheet)
outputfilename = "readable" + myfile + ".csv"
your_csv_file = open(outputfilename, 'wb')
wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
for rownum in range(sh.nrows):
wr.writerow(sh.row_values(rownum))
your_csv_file.close()
def xmlconverter():
# Reading basic info
fin = open("xmlinfo.txt","r")
giveninfo = fin.readlines()
myfields = giveninfo[0].split(",")
fout = open("studentlist.xml","w")
fout.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
fout.write("<!--University Course Timetabling-->")
fout.write("<timetable")
fout.write("version=\"2.4\"")
fout.write("initiative=\"{0}\"",myfields[0])
fout.write("term=\"{0}\"",myfields[1])
fout.write("created=\"{0}\"",datetime.datetime.now())
fout.write("nrDays=\"{0}\"",myfields[2])
fout.write("slotsPerDay=\"{0}\">",myfields[3])
# Reading and Inserting Rooms Data into xml file
myfields = giveninfo[1].split(",")
csv_from_excel(myfields[0],myfields[1])
fin = open("readable" + myfields[0] + ".csv","r")
totalrooms = fin.readlines()
totalrooms.pop(0)
fout.write("<rooms>")
for room in totalrooms:
myfields = room.split(",")
fout.write("<room id=\"{0}\" constraint=\"true\" capacity=\"{1}\" ignoreTooFar=\"true\"/>",myfields[0],myfields[2])
fout.write("</rooms>")
# Finding all available combinations of days for any class
daysallowed = giveninfo[0].split(",")[2]
daystrings = []
index = 0
for i in range(daysallowed - 1):
for k in range(daysallowed - i - 1):
daystrings[index] = ""
for j in range(i):
daystrings[index]+="0"
daystrings[index]+="1"
for l in range(k):
daystrings+="0"
daystrings[index]+="1"
for m in range(7 - len(daystrings[index])):
daystrings[index]+="0"
index+=1
for i in range(daysallowed):
daysallowed[index] = ""
for j in range(i):
daysallowed[index]+="0"
daysallowed[index]+="1"
for k in range(7 - len(daysallowed[index])):
daysallowed[index]+="0"
index+=1
# Calculating Time Intervals
periodduration = 0
#atomictime = giveninfo[3].split(",")[0] # You forgot to use this somehow
myfields = giveninfo[4].split(",")
shour = myfields[0]
smin = myfields[1]
startinmin = shour * 60
startinmin += smin
myfields = giveninfo[5].split(",")
ehour = myfields[0]
emin = myfields[1]
endinmin = ehour * 60
endinmin += emin
startinmin/=5
endinmin/=5
#Cleaning Courses Codes from Excel file
myfields = giveninfo[2].split(",")
csv_from_excel(myfields[0],myfields[1])
fin = open("readable" + myfields[0] + ".csv","r")
myfields.pop(0)
myfields.pop(1) # myfields is a list of values in excel file that are not course codes (headers)
totalcourses = fin.readlines()
tempfields = []
thisisnotacourse = []
for course in totalcourses:
tempfields = totalcourses[i].split(",")
if(tempfields[1] in myfields):
thisisnotacourse.append(course)
for invalidcourserow in thisisnotacourse:
totalcourses.remove(invalidcourserow)
updatedlist = open("updatedcourselist.txt","w")
fout.write("<classes>")
before = []
after = []
sections = []
code = 0 # xml course ids
instructorid = 0
instructorlookup = dict()
for c in range(len(totalcourses)):
myfields = totalcourses[c].split(")")
after = myfields[1].split(",") # I've considered element No.1 as an empty element
before = myfields[0].split("(")
sections = before[1].split(",")
before = before[0].split(",")
periodduration = (eval(after[2]) / 2.0) * 12.0
for s in sections:
updatedlist.write(before[0] + s)
fout.write("<class id=\"{0}\" offering=\"{0}\" config=\"{0}\" committed=\"false\" subpart=\"{0}\" classLimit=\"{1}\" scheduler=\"0\"",code,eval(after[3].split("x")[0])) # i don't know what scheduler meaans
fout.write("dates=\"1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\">")
if after[1] in instructorlookup:
fout.write("<instructor id=\"{0}\" solution=\"false\"/>",instructorlookup[after[i]]) # False, right?
else:
instructorlookup[after[1]] = instructorid
fout.write("<instructor id=\"{0}\" solution=\"false\"/>", instructorid) # False, right?
instructorid+=1
for room in totalrooms:
myfields = room.split(",")
fout.write("<room id=\"{0}\" pref=\"0\"/>",myfields[0],myfields[2])
for days in daysallowed:
for t in range(startinmin,endinmin-periodduration):
fout.write("<time days=\"{0}\" start=\"{1}\" length=\"{2}\" pref=\"0.0\"/>",days,t,periodduration)
fout.write("</class>")
code+=1
fout.write("</classes>")
updatedlist.close()
# The mapping from course codes to xml course ids
mycourselistfile = open("updatedcourselist.txt","r")
courseids = mycourselistfile.readlines()
courselookup = dict()
for c in range(len(courseids)):
courselookup[courseids[c]] = c
# Alloting Student Xml ids to Student Roll No's
studentnos = open("studentnos","w")
myfields = giveninfo[6].split(",")
csv_from_excel(myfields[0],myfields[1])
studentlist = open("readable" + myfields[0] + ".csv","r")
studentlist.pop(0)
# Dictionary containing keys as students and values as the courses that student hs registered in
registeration = dict()
for row in studentlist:
myfields = row.split(",")
if myfields[1] in registeration:
registeration[myfields[1]].append(myfields[4] + myfields[6])
else:
registeration[myfields[1]] = [myfields[4] + myfields[6]]
# Writing Students data in xml file
fout.write("<students>")
newstudentnum = 0
for r in registeration:
studentnos.write(newstudentnum+", " + registeration[r])
fout("<student id=\"{0}\">",newstudentnum)
newstudentnum+=1
for coursetaking in registeration[r]:
fout.write("<class id=\"{0}\"/>",courselookup[coursetaking])
fout.write("</students>")
# Done ! :)
fout.write("</timetable>")
|
b736d580b41f3d193b0bf835e9b58c89a39e18a2 | Aasthaengg/IBMdataset | /Python_codes/p02546/s638739854.py | 82 | 3.6875 | 4 | i=str(input())
leng=len(i)
if i[leng-1]=="s":
print(i+"es")
else:
print(i+"s") |
a6f31a90b1315fc24e851c6c1205d8423f5a78ee | whoyoung388/algos | /maximum-depth-of-binary-tree.py | 963 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
// BFS
import collections
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
depth = 0
que = collections.deque()
que.append(root)
while que:
for _ in range(len(que)):
node = que.popleft()
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
depth += 1
return depth
// DFS
class Solution:
def maxDepth(self, root: TreeNode) -> int:
depth = self.dfs(root, 0)
return depth
def dfs(self, root, depth):
if not root:
return depth
return max(self.dfs(root.left, depth+1),
self.dfs(root.right, depth+1))
|
9fbf739bb9e4b000d8f4676814dfd94476838c1d | tpagliocco/Python-Examples | /30 Day Python Challenge/Binary_Conversion.py | 481 | 3.59375 | 4 | #!/bin/python3
#Given a base-10integer, N , convert it to binary (base-2). Then find and print the base-10 integer
#denoting the maximum number of consecutive 1's in N's binary representation.
import sys
n = int(input().strip())
count= 0
maxcount = 0
for i in str(bin(n)):
if i == '1':
count +=1
elif count > maxcount:
maxcount = count;
count = 0
else:
count = 0
if count > maxcount:
maxcount = count
print(maxcount)
|
f2a115dd0f07e65f09469d754b718eb8e62db217 | ANKquil/PracticeDV | /task139.py | 1,070 | 4.28125 | 4 | # Написать функцию special_number(number), которая определяет является ли число особенным.
# Назовем число особенным, если сумма цифр числа, возведенных в степень, равную позиции цифры, равна самому числу.
#
# Примеры:
# special_number(89) => True -> 8^1 + 9^2 = 8 + 81 = 89
import traceback
def special_number(number):
string_number = str(number)
sum_nums = 0
for i in range(0, len(string_number)):
sum_nums += int(string_number[i]) ** (i+1)
if sum_nums == number:
special = True
else:
special = False
return special
# Тесты
try:
assert special_number(1) == True
assert special_number(2) == True
assert special_number(89) == True
assert special_number(77) == False
assert special_number(518) == True
except AssertionError:
print("TEST ERROR")
traceback.print_exc()
else:
print("TEST PASSED") |
19e845cc29dd965df8b40ac3d7b4f67abfc825ca | viii1/Pong | /pong.py | 3,340 | 3.890625 | 4 | import turtle # Small "T" cause its a modular name
#For windows
wn = turtle.Screen() # Here the origin is at the center of the screen unlike pygame or openCV
wn.title("PONG")
wn.bgcolor("black")
wn.setup(width=800,height=600)
""" stop the windows from updating
we have to update it manually
And it helps in speeding up the game """
wn.tracer(0)
score_a = 0
score_b = 0
#pen
pen=turtle.Turtle()
pen.speed(0) # animation speed
pen.color("white")
pen.penup() # dont wanna see the line between the points
pen.hideturtle()
pen.goto(0,270)
pen.write("Player A :0 Player B :0",align="center",font=("courier",24,"normal"))
#Paddle A
paddle_a = turtle.Turtle() # Capital "T" cause its the class name
paddle_a.speed(0) # this is the speed of animation not the sped of the paddle, it is set to the maximum possible speed
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5,stretch_len=1)
paddle_a.penup() # turtle drawas a line when moving and we dont want this
paddle_a.goto(-350,0)
#Padle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5,stretch_len=1)
paddle_b.penup()
paddle_b.goto(350,0)
#Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0,0)
ball.dx=3
ball.dy=3
#Functions
def paddle_a_up():
y=paddle_a.ycor()
if paddle_a.ycor() <250:
y+=20
paddle_a.sety(y)
else:
paddle_a.sety(250)
def paddle_a_down():
y=paddle_a.ycor()
if paddle_a.ycor() >-250:
y-=20
paddle_a.sety(y)
else:
paddle_a.sety(-250)
def paddle_b_up():
y=paddle_b.ycor()
if paddle_b.ycor() <250:
y+=20
paddle_b.sety(y)
else:
paddle_b.sety(250)
def paddle_b_down():
y=paddle_b.ycor()
if paddle_b.ycor() >-250:
y-=20
paddle_b.sety(y)
else:
paddle_b.sety(-250)
# Keyboard binding
wn.listen()
wn.onkeypress(paddle_a_up,"w") #Lowercase "w" will only work not the upper case
wn.onkeypress(paddle_a_down,"s")
wn.onkeypress(paddle_b_up,"Up")
wn.onkeypress(paddle_b_down,"Down")
#Main game loop
while True:
wn.update() #tap = 4 spaces keys use either not both otherwise you may face some error
#Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
#Border checking
if ball.ycor() > 290 :
ball.sety(290)
ball.dy *=-1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *=-1
if ball.xcor() > 390:
ball.setx(0)
ball.dx *=-1
score_a +=1
pen.clear()
pen.write("Player A :{} Player B :{}".format(score_a,score_b),align="center",font=("courier",24,"normal"))
if ball.xcor() < -390:
ball.setx(0)
ball.dx *=-1
score_b +=1
pen.clear()
pen.write("Player A :{} Player B :{}".format(score_a,score_b),align="center",font=("courier",24,"normal"))
#Paddle and ball collision
if ball.xcor()>340 and (ball.ycor() < (paddle_b.ycor()+ 50) and ball.ycor() > (paddle_b.ycor() -50)):
ball.setx(340)
ball.dx *= -1
if ball.xcor()<-340 and (ball.ycor() < (paddle_a.ycor()+ 50) and ball.ycor() > (paddle_a.ycor() -50)):
ball.setx(-340)
ball.dx *= -1
|
0fa9e6ec57f9db3b9eaa7d583e974517833d594e | wimbuhTri/Kelas-Python_TRE-2021 | /P4/0.py | 223 | 3.875 | 4 | x=float(input("Masukkan nilai X= "))
y=float(input("Masukkan nilai Y= "))
p = x + y
q1 = x * y
q2 = x / y
print("Hasil dari P=",p)
if p >= 0:
print('maka Q=x*y adalah =',q1)
else:
print('maka Q=x/y adalah =',q2) |
d0a27452e39ff7a24e6032c72dbba6688b050c1d | Bambur31/python | /Homework_8_task_7.py | 469 | 4 | 4 | class ComplexNum:
def __init__(self, num):
self.num = complex(num[0], num[1])
def __add__(self, other):
return self.num + other.num
def __mul__(self, other):
return self.num * other.num
x = [1, 2]
y = [2, 3]
num_1 = ComplexNum(x)
num_2 = ComplexNum(y)
print(f"Сумма комплексных чисел: {num_1 + num_2}")
print(f"Произведение комплексных чисел: {num_1 * num_2}")
|
1a5d42c87178a51d0ca470b491694d78fb6e73d1 | drestion/leetcode | /python/MergeTwoSortedLists.py | 855 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# two pointer
h, pl1, pl2 = ListNode(), l1, l2
oh = h
while pl1 and pl2:
if pl1.val <= pl2.val:
h.next = pl1
h = h.next
pl1 = pl1.next
else:
h.next = pl2
h = h.next
pl2 = pl2.next
# while pl1:
# h.next = pl1
# h = h.next
# pl1 = pl1.next
# while pl2:
# h.next = pl2
# h = h.next
# pl2 = pl2.next
h.next = pl1 or pl2
return oh.next |
86bc17fe69ce36a28ae4c03979a84f548665dde3 | Scrapey-Doo/Scraper | /server.py | 7,364 | 3.59375 | 4 | # CSCI 3800 Final Project
# Group: ScrapeyDo
# Group leader: Yuzhe Lu
# Group members: Yuzhe Lu, David Oligney, Prinn Prinyanut, Eric Slick, Patrick Tate
# first run server.py, then run client.py to connect as many different clients to the Server as you want
from socket import socket, AF_INET, SOCK_STREAM # because we need sockets to connect to clients
import threading # multi-thread the clients
#import sys not sure if we will need this or not, works with it uncommented so...
from User import User # because Server has a list of users
# Server class to handle multiple clients
# file is run by instantiating a Server object and calling member function run() at the bottom of this file
# Server object stays open and listens for clients
# Server object can handle multiple clients and takes advantage of multi-threading
# ********************************************************************************
# run() method calls the handler method which takes the connection and address as paramters
# from there, a client is greeted with an inital menu screen to create and account or login
class Server:
# *** member variables ***
# socket to bind and listen for clients
serversocket = socket(AF_INET, SOCK_STREAM)
# list of client connections, when client chooses to disconnect, connection is removed from list and connection is closed
connections = []
# list of User objects, will be a dictionary {} that is serialized and read in
clients = []
# *** member variables ***
# default initializer, listen for clients on socket 5000
def __init__(self):
self.serversocket.bind(('localhost', 5000))
self.serversocket.listen(5)
self.connections = []
self.clients = []
# only function we need to call to start the server while it waits for clients
# will run this in a main/App file later, but for now just runs at the bottom of this file
def run(self):
# wait for clients, need to figure out the best way to end this loop other than pressing the "stop" button
while True:
# accept connection from client
connection, address = self.serversocket.accept()
# add connection to the list of connections self.connections
self.connections.append(connection)
# thread for this connection, call self.handler() function
cthread = threading.Thread(target=self.handler, args=(connection, address))
cthread.daemon = True
cthread.start()
# print the address for reference
print(str(address[0]) + ':' + str(address[1]) + " connected")
# calls initialMenu(connection, address) function to display the first menu to the user
def handler(self, connection, address):
self.initialMenu(connection, address)
# first menu client/user sees when connecting to server
# takes connection and address variables from serversocket.accept() function in run(self)
def initialMenu(self, connection, address):
while True:
# initial menu message for user/client
initialMsg = "Welcome to the Scraping Server\n" \
"Choose an option\n" \
"1: create account\n" \
"2: sign in\n" \
"3: disconnect"
# send itial menu message to user
connection.send(bytes(initialMsg, 'utf-8'))
# receive input from the user on which option
data = connection.recv(1024)
# convert client input to string
clientOption1 = str(data, 'utf-8')
# switch on user input option
# 1 = create account
# calls createAccount() function
# account user name must not already exist in self.clients list
if clientOption1 == "1":
# print message on server for reference
print("client chose create account")
# call createAccount function with connection, address info
self.createAccount(connection, address)
# can delete lines below, printing on the server the user names in self.clients just for reference
for user in self.clients:
print(user.name)
# client wants to sign in
# password needs to be validated in list/dictionary of users
# *** need to write this function ***
elif clientOption1 == "2":
print("client chose sign in")
# client wants to disconnect
# remove client from list of connections and close connection
# *** need to add this as a case, and have last else as default catch bad input ***
else:
self.connections.remove(connection)
print(str(address[0]) + ':' + str(address[1]) + " disconnected")
connection.close()
break
# this is a catch if there is no more connections of data incoming
if not data:
self.connections.remove(connection)
print(str(address[0]) + ':' + str(address[1]) + " disconnected")
connection.close()
break
# void function to create a user account
# creates a User object based on client input and adds user to self.clients list/dictionary
# user is prompted to enter another name if user name alerady exists in self.clients
def createAccount(self, connection, address):
# msg to send client
chooseName = "Enter a username (must not be taken)\n"
# send msg to client
connection.send(bytes(chooseName, 'utf-8'))
# receive name
name = connection.recv(1024)
# convert name to a string, always utf-8 encoding
sname = str(name, 'utf-8')
print(sname) # print for reference
# check if name exists in self.clients
valid = self.isValid(sname)
# if name is valid, prompt for a password, create a User object and add to self.clients
if valid:
successMsg = "valid username"
connection.send(bytes(successMsg, 'utf-8'))
choosePassword = "Enter a password: \n"
connection.send(bytes(choosePassword, 'utf-8'))
password = connection.recv(1024)
spassword = str(password, 'utf-8')
print(spassword)
user = User(sname, spassword)
self.clients.append(user)
# else prompt user to enter another name
else:
errMsg = "Name taken, try again"
connection.send(bytes(errMsg, 'utf-8'))
# returns True if name isn't in self.clients
# returns False if name is equal to user.name in self.clients
def isValid(self, name):
validName = True
# if self.clients list is empty, no user names exist yet, return True
if len(self.clients) == 0:
print("zero size")
return True
# check list of users to see if user name already exists
# return False if user name already exists
for user in self.clients:
if user.name == name:
return False
# return True is all above checks passed
return validName
# instantiate Server object
server = Server()
# run the whole party
server.run()
|
2b71e43c5b3aee49d4388e192ed5ed57054ce839 | diogoandrade1999/FP-1ano | /aula04/exercicio1.py | 442 | 4.125 | 4 | num = float( input("Escreva o número zero: ") )
soma = 0
media = 0
elementos = 0
maximo = num
minimo = num
while num != 0:
soma = soma + num
elementos = elementos + 1
media = soma / elementos
if maximo < num:
maximo = num
if minimo > num:
minimo = num
num = float( input("Escreva o número zero: ") )
print("Soma: ",soma,"Número de elementos: ",elementos,"Média: ",media,"Máximo: ",maximo,"Mínimo: ",minimo)
|
58e4d65f849dd72b7ffca2091d3ea01498c05c02 | GarvenYu/Algorithm-DataStructure | /58数组中只出现一次的两个数字/findnumsappearonce.py | 1,522 | 3.921875 | 4 | # !usr/bin/env python
# -*-coding:utf-8-*-
"""
一个整型数组里除2个数字外,其他数字都出现了2次。请找出这2个只出现1次的数字。
要求:时间复杂度O(n),空间复杂度O(1)。
示例:数组{2,4,3,6,3,2,5,5},输出4和6。
思路:
1.相同数字进行异或结果为0;
2.从头到尾异或数组中每个数字,得到的结果是数组中只出现1次的两个数字的异或结果,在结果数字中
找到第一个为1的位置,记为第n位。以第n位是否为1将数组分成两部分,这样两个子数组中第n位分别为0和1,
而且每个子数组都包含一个只出现一次的数字,再进行异或输出最后结果。
"""
def array_xor(array):
i = 0
result = array[i]
while i < len(array) - 1:
result ^= array[i + 1]
i += 1
return result
def find_first_bit_1(number):
"""找到右边第一个为1的位置
"""
index = 0
while number & 1 == 0:
number = number >> 1
index += 1
return index
def is_bit_1(number, n):
"""判断第n位是否为1
"""
number = number >> n
return number & 1
def find_two_numbers(array):
xor_result = array_xor(array)
index = find_first_bit_1(xor_result)
result1 = result2 = 0
for i in range(0, len(array)):
if is_bit_1(array[i], index):
result1 ^= array[i]
else:
result2 ^= array[i]
return result1, result2
array = [2, 4, 3, 6, 3, 2, 5, 5]
print(find_two_numbers(array))
|
fd65a27a4d5de44a223e7366cfed999c098c859a | joansekamana/FunMooc | /UpyLab_4_10.py | 1,005 | 3.5 | 4 | import random
def bat(joueur_1, joueur_2):
PIERRE = 0
FEUILLE = 1
CISEAUX = 2
if (joueur_1 == PIERRE and joueur_2 == CISEAUX) or (joueur_1 == CISEAUX and joueur_2 == FEUILLE) or (
joueur_1 == FEUILLE and joueur_2 == PIERRE):
return True
else:
return False
def main():
nom_coup = ("Pierre", "Feuille", "Ciseaux")
points = 0
coup_j = []
s = int(input())
for _ in range(5):
coup_j.append(int(input()))
random.seed(s)
for x in range(5):
coup_o = int(random.randint(0, 2))
if bat(coup_o, coup_j[x]):
verbe = "bat"
points -= 1
elif coup_o != coup_j[x]:
verbe = "est battu par"
points += 1
else:
verbe = "annule"
print(nom_coup[coup_o], verbe, nom_coup[coup_j[x]], ":", points)
if points < 0:
print("Perdu")
elif points == 0:
print("Nul")
elif points > 0:
print("Gagné")
main()
|
f8e2f1b3f4f987f10a35bddf18318290405f8cf1 | mustafaha1/python-work | /save the princess.py | 3,975 | 4 | 4 |
# import time # used for short delay
# from random import randrange # used for random number generator
# print(' _____ _ _ _ _ ')
# print(' / ____| | | | | (_) | |')
# print(' | (___ __ ___ _____ | |_| |__ ___ _ __ _ __ _ _ __ ___ ___ ___ ___| |')
# print(' \___ \ / _` \ \ / / _ \ | __| _ \ / _ \ | _ \| __| | _ \ / __/ _ \/ __/ __| |')
# print(' ____) | (_| |\ V / __/ | |_| | | | __/ | |_) | | | | | | | (_| __/\__ \__ \_|')
# print(' |_____/ \__,_| \_/ \___| \__|_| |_|\___| | .__/|_| |_|_| |_|\___\___||___/___(_)')
# print(' | | ')
# print(' |_| ')
# name = input('Thanks for finding the princess the KINGDOME will apperciate your kindness now enter your name: ')
# print('{} you are now in the forest tasked to finding the princess you are currently on the way to the castle: '.format(name.capitalize()))
# num = randrange(10)
# result = num
# def short_cut(text, monster): # function for the player chosen short-cut option
# time.sleep(1)
# print(text)
# time.sleep(1)
# print(monster)
# # choices and input if statements
# choice1 = str(input("1. Do you want to try your luck in defeating the monster?\n2. Do you want to try running away and hope for the best? \n"))
# if choice1 == "1" and result > 5:
# print("You have been blessed by the gods and escape,{}".format(result))
# elif choice1 == "1" and result < 5:
# print("you have died. game over {}.".format(result))
# elif choice1 == "2" and result < 5:
# print("Better luck next time. game over {}.".format(result))
# elif choice1 == "2" and result > 5:
# print("You escape with your life {}.".format(result))
# short_cut("You have decided to take the short-cut", "Suddenly a monster jumps out from behind a tree! \n") # end of function
# time.sleep(1)
# choice_long_or_short = str(input(" Do you want to take the \n 1. Long way (safer) \n 2. the Shortcut (dangerous)"))
# if choice_long_or_short == '1':
# short_cut()
# import time
# import time
# response1 = "A masked creature jumps out from behind a tree and quickly draws a sword."
# def yes_or_no(question):
# reply = str(input(question+' (yes/no): ')).lower().strip()
# if reply == 'yes':
# return True
# if reply == 'no':
# return False
# else:
# return yes_or_no("Uhhhh... please enter ")
# print("you have decided to take the long way")
# time.sleep(2.5)
# print("you begin your ascent up a large hill, the forest seems to become more dense")
# time.sleep(3)
# print("before you know it, hours have passed and it is almost dark.")
# time.sleep(3)
# print("You hear a rustling from some nearby shrubs")
# time.sleep(3)
# print("...")
# time.sleep(2)
# yes_or_no("Do you investigate?")
# if yes_or_no == "yes":
# print(response1)
# time.sleep(2)
# response1 = "A masked creature jumps out from behind a tree and quickly draws a sword."
# print(response1)
# print("He tells you he can't let you proceed unless you asnwer his question correctly.")
# time.sleep(2)
# def func1():
# question1 = str(input("What is the 6th letter of the 'alphabet'?: "))
# if question1 == "b":
# print("That is correct!")
# elif question1 != "b":
# print("The creature raises his sword and strikes you down.. You have failed.. Please try again.")
# func1()
# func1()
# print("The creeature steps aside, letting you past.")
# time.sleep(2)
# print("You turn around to notice he has disappeared in to the night")
# time.sleep(2)
# print("You press on until you reach an opening in the trees")
# time.sleep(2)
# print("You spot a castle in the distance and begin to head in its direction")
|
7283fe0c25af12327b5ccda0316f8c12a8a13506 | AG-droid/Python-Projects | /unit_conv.py | 13,357 | 4.28125 | 4 |
print('WELCOME TO THE UNIT CONVERTER')
print('')
print('')
y = input("What do you want to measure ? :")
a = input('What do you want to convert from (Full forms only) -->')
b = input('What do you want to convert to -->')
c = float(input('pls enter the value that you want to convert -->'))
def weight():
if a == "kilogram" or a == "Kg" or a == "Kilogram" or a == "kg" :
if b == 'hectogram'or b == 'Hectogram':
print(c * 10 , 'hectogram')
elif b == "dekagram" or b == "Dekagram":
print(c * 100 , 'dekagram')
elif b == 'gram' or b =='Gram':
print(c * 1000 , 'gram')
elif b == "decigram" or b == 'Decigram':
print(c * 10000, 'decigram')
elif b == 'centigram' or b == 'Centigram':
print(c * 100000 , 'centigram')
elif b == 'Mililgram' or b == 'miligram':
print(c * 1000000, 'miligram')
elif a == "hectagram" or a == "Hg" or a == "Hectagram" or a == "hg" :
if b == 'Kilogram'or b == 'kilogram':
print(c / 10 , 'Kilogram')
elif b == "dekagram" or b == "Dekagram":
print(c * 10 , 'dekagram')
elif b == 'gram' or b =='Gram':
print(c * 100 , 'gram')
elif b == "decigram" or b == 'Decigram':
print(c * 1000, 'decigram')
elif b == 'centigram' or b == 'Centigram':
print(c * 10000 , 'centigram')
elif b == 'Mililgram' or b == 'miligram':
print(c * 100000, 'miligram')
elif a == "dekagram" or a == "Dag" or a == "Dekagram" or a == "dag" :
if b == 'Kilogram'or b == 'kilogram':
print(c / 100 , 'Kilogram')
elif b == "hectagram" or b == "Hectagram":
print(c / 10 , 'Hectagram')
elif b == 'gram' or b =='Gram':
print(c * 10 , 'gram')
elif b == "decigram" or b == 'Decigram':
print(c * 100, 'decigram')
elif b == 'centigram' or b == 'Centigram':
print(c * 1000 , 'centigram')
elif b == 'Mililgram' or b == 'miligram':
print(c * 10000, 'miligram')
elif a == "gram" or a == "g" or a == "Gram" or a == "G":
if b == 'Kilogram' or b == 'kilogram':
print(c / 1000, 'Kilogram')
elif b == "hectagram" or b == "Hectagram":
print(c / 100, 'Hectagram')
elif b == 'dekagram' or b == 'Dekaram':
print(c / 10, 'gram')
elif b == "decigram" or b == 'Decigram':
print(c * 10, 'decigram')
elif b == 'centigram' or b == 'Centigram':
print(c * 100, 'centigram')
elif b == 'Mililgram' or b == 'miligram':
print(c * 1000, 'miligram')
elif a == "decigram" or a == "dg" or a == "Decigram" or a == "Dg":
if b == 'Kilogram' or b == 'kilogram':
print(c / 10000, 'Kilogram')
elif b == "hectagram" or b == "Hectagram":
print(c / 1000, 'Hectagram')
elif b == 'dekagram' or b == 'Dekaram':
print(c / 100, 'gram')
elif b == "gram" or b == 'Gram':
print(c / 10, 'decigram')
elif b == 'centigram' or b == 'Centigram':
print(c * 10, 'centigram')
elif b == 'Mililgram' or b == 'miligram':
print(c * 100, 'miligram')
elif a == "centigram" or a == "cg" or a == "Centigram" or a == "Cg":
if b == 'Kilogram' or b == 'kilogram':
print(c / 100000, 'Kilogram')
elif b == "hectagram" or b == "Hectagram":
print(c / 10000, 'Hectagram')
elif b == 'dekagram' or b == 'Dekaram':
print(c / 1000, 'gram')
elif b == "gram" or b == 'Gram':
print(c / 100, 'gram')
elif b == 'decigram' or b == 'Decigram':
print(c / 10, 'Decigram')
elif b == 'Mililgram' or b == 'miligram':
print(c * 10, 'miligram')
elif a == "miliigram" or a == "mg" or a == "miligram" or a == "Mg":
if b == 'Kilogram' or b == 'kilogram':
print(c / 1000000, 'Kilogram')
elif b == "hectagram" or b == "Hectagram":
print(c / 100000, 'Hectagram')
elif b == 'dekagram' or b == 'Dekaram':
print(c / 10000, 'gram')
elif b == "gram" or b == 'Gram':
print(c / 1000, 'gram')
elif b == 'centigram' or b == 'Centigram':
print(c / 10, 'centigram')
elif b == 'decigram' or b == 'Decigram':
print(c/100, 'decigram')
def length():
if a == "kilometer" or a == "Km" or a == "Kilometer" or a == "km" :
if b == 'hectometer'or b == 'Hectometer':
print(c * 10 , 'hectometer')
elif b == "dekameter" or b == "Dekameter":
print(c * 100 , 'dekameter')
elif b == 'meter' or b =='Meter':
print(c * 1000 , 'meter')
elif b == "decimeter" or b == 'Decimeter':
print(c * 10000, 'decimeter')
elif b == 'centimeter' or b == 'Centimeter':
print(c * 100000 , 'centimeter')
elif b == 'Mililmeter' or b == 'milimeter':
print(c * 1000000, 'milimeter')
elif a == "hectameter" or a == "Hm" or a == "Hectameter" or a == "hm" :
if b == 'Kilometer'or b == 'kilometer':
print(c / 10 , 'Kilometer')
elif b == "dekameter" or b == "Dekameter":
print(c * 10 , 'dekameter')
elif b == 'meter' or b =='Meter':
print(c * 100 , 'meter')
elif b == "decimeter" or b == 'Decimeter':
print(c * 1000, 'decimeter')
elif b == 'centimeter' or b == 'Centimeter':
print(c * 10000 , 'centimeter')
elif b == 'Mililmeter' or b == 'milimeter':
print(c * 100000, 'milimeter')
elif a == "dekameter" or a == "Dam" or a == "Dekameter" or a == "dam" :
if b == 'Kilometer'or b == 'kilometer':
print(c / 100 , 'Kilometer')
elif b == "hectameter" or b == "Hectameter":
print(c / 10 , 'Hectameter')
elif b == 'meter' or b =='Meter':
print(c * 10 , 'meter')
elif b == "decimeter" or b == 'Decimeter':
print(c * 100, 'decimeter')
elif b == 'centimeter' or b == 'Centimeter':
print(c * 1000 , 'centimeter')
elif b == 'Mililmeter' or b == 'milimeter':
print(c * 10000, 'milimeter')
elif a == "meter" or a == "m" or a == "Meter" or a == "M":
if b == 'Kilometer' or b == 'kilometer':
print(c / 1000, 'Kilometer')
elif b == "hectameter" or b == "Hectameter":
print(c / 100, 'Hectameter')
elif b == 'dekameter' or b == 'Dekaram':
print(c / 10, 'meter')
elif b == "decimeter" or b == 'Decimeter':
print(c * 10, 'decimeter')
elif b == 'centimeter' or b == 'Centimeter':
print(c * 100, 'centimeter')
elif b == 'Mililmeter' or b == 'milimeter':
print(c * 1000, 'milimeter')
elif a == "decimeter" or a == "dm" or a == "Decimeter" or a == "Dm":
if b == 'Kilometer' or b == 'kilometer':
print(c / 10000, 'Kilometer')
elif b == "hectameter" or b == "Hectameter":
print(c / 1000, 'Hectameter')
elif b == 'dekameter' or b == 'Dekarameter':
print(c / 100, 'meter')
elif b == "meter" or b == 'Meter':
print(c / 10, 'decimeter')
elif b == 'centimeter' or b == 'Centimeter':
print(c * 10, 'centimeter')
elif b == 'Mililmeter' or b == 'milimeter':
print(c * 100, 'milimeter')
elif a == "centimeter" or a == "cm" or a == "Centimeter" or a == "Cm":
if b == 'Kilometer' or b == 'kilometer':
print(c / 100000, 'Kilometer')
elif b == "hectameter" or b == "Hectameter":
print(c / 10000, 'Hectameter')
elif b == 'dekameter' or b == 'Dekaram':
print(c / 1000, 'meter')
elif b == "meter" or b == 'Gram':
print(c / 100, 'meter')
elif b == 'decimeter' or b == 'Decimeter':
print(c / 10, 'Decimeter')
elif b == 'Mililmeter' or b == 'milimeter':
print(c * 10, 'milimeter')
elif a == "miliimeter" or a == "mm" or a == "milimeter" or a == "Mm":
if b == 'Kilometer' or b == 'kilometer':
print(c / 1000000, 'Kilometer')
elif b == "hectameter" or b == "Hectameter":
print(c / 100000, 'Hectameter')
elif b == 'dekameter' or b == 'Dekaram':
print(c / 10000, 'meter')
elif b == "meter" or b == 'Meter':
print(c / 1000, 'meter')
elif b == 'centimeter' or b == 'Centimeter':
print(c / 10, 'centimeter')
elif b == 'decimeter' or b == 'Decimeter':
print(c/100, 'decimeter')
def Capacity():
if a == "kilolitre" or a == "Kl" or a == "Kilolitre" or a == "kl" :
if b == 'hectolitre'or b == 'Hectolitre':
print(c * 10 , 'hectolitre')
elif b == "dekalitre" or b == "Dekalitre":
print(c * 100 , 'dekalitre')
elif b == 'litre' or b =='Litre':
print(c * 1000 , 'litre')
elif b == "decilitre" or b == 'Decilitre':
print(c * 10000, 'decilitre')
elif b == 'centilitre' or b == 'Centilitre':
print(c * 100000 , 'centilitre')
elif b == 'Milillitre' or b == 'mililitre':
print(c * 1000000, 'mililitre')
elif a == "hectalitre" or a == "Hl" or a == "Hectalitre" or a == "hl" :
if b == 'Kilolitre'or b == 'kilolitre':
print(c / 10 , 'Kilolitre')
elif b == "dekalitre" or b == "Dekalitre":
print(c * 10 , 'dekalitre')
elif b == 'litre' or b =='Litre':
print(c * 100 , 'litre')
elif b == "decilitre" or b == 'Decilitre':
print(c * 1000, 'decilitre')
elif b == 'centilitre' or b == 'Centilitre':
print(c * 10000 , 'centilitre')
elif b == 'Milillitre' or b == 'mililitre':
print(c * 100000, 'mililitre')
elif a == "dekalitre" or a == "Dal" or a == "Dekalitre" or a == "dal" :
if b == 'Kilolitre'or b == 'kilolitre':
print(c / 100 , 'Kilolitre')
elif b == "hectalitre" or b == "Hectalitre":
print(c / 10 , 'Hectalitre')
elif b == 'litre' or b =='Litre':
print(c * 10 , 'litre')
elif b == "decilitre" or b == 'Decilitre':
print(c * 100, 'decilitre')
elif b == 'centilitre' or b == 'Centilitre':
print(c * 1000 , 'centilitre')
elif b == 'Milillitre' or b == 'mililitre':
print(c * 10000, 'mililitre')
elif a == "litre" or a == "g" or a == "Litre" or a == "G":
if b == 'Kilolitre' or b == 'kilolitre':
print(c / 1000, 'Kilolitre')
elif b == "hectalitre" or b == "Hectalitre":
print(c / 100, 'Hectalitre')
elif b == 'dekalitre' or b == 'Dekaram':
print(c / 10, 'litre')
elif b == "decilitre" or b == 'Decilitre':
print(c * 10, 'decilitre')
elif b == 'centilitre' or b == 'Centilitre':
print(c * 100, 'centilitre')
elif b == 'Milillitre' or b == 'mililitre':
print(c * 1000, 'mililitre')
elif a == "decilitre" or a == "dl" or a == "Decilitre" or a == "Dl":
if b == 'Kilolitre' or b == 'kilolitre':
print(c / 10000, 'Kilolitre')
elif b == "hectalitre" or b == "Hectalitre":
print(c / 1000, 'Hectalitre')
elif b == 'dekalitre' or b == 'Dekaram':
print(c / 100, 'litre')
elif b == "litre" or b == 'Litre':
print(c / 10, 'decilitre')
elif b == 'centilitre' or b == 'Centilitre':
print(c * 10, 'centilitre')
elif b == 'Milillitre' or b == 'mililitre':
print(c * 100, 'mililitre')
elif a == "centilitre" or a == "cl" or a == "Centilitre" or a == "Cl":
if b == 'Kilolitre' or b == 'kilolitre':
print(c / 100000, 'Kilolitre')
elif b == "hectalitre" or b == "Hectalitre":
print(c / 10000, 'Hectalitre')
elif b == 'dekalitre' or b == 'Dekaram':
print(c / 1000, 'litre')
elif b == "litre" or b == 'Litre':
print(c / 100, 'litre')
elif b == 'decilitre' or b == 'Decilitre':
print(c / 10, 'Decilitre')
elif b == 'Milillitre' or b == 'mililitre':
print(c * 10, 'mililitre')
elif a == "miliilitre" or a == "ml" or a == "mililitre" or a == "Ml":
if b == 'Kilolitre' or b == 'kilolitre':
print(c / 1000000, 'Kilolitre')
elif b == "hectalitre" or b == "Hectalitre":
print(c / 100000, 'Hectalitre')
elif b == 'dekalitre' or b == 'Dekaram':
print(c / 10000, 'litre')
elif b == "litre" or b == 'Litre':
print(c / 1000, 'litre')
elif b == 'centilitre' or b == 'Centilitre':
print(c / 10, 'centilitre')
elif b == 'decilitre' or b == 'Decilitre':
print(c/100, 'decilitre')
if y == "weight" or "Weight" :
weight()
if y == 'length' or y == 'Length' or y == 'Height' or y == 'height':
length()
if y == 'capacity' or y == 'Capacity':
Capacity()
if y == "":
print('ERROR : pls assign a value')
|
745ab76c07b89b02ad45b15dee1f563d4aeeaa98 | bibiksh/Python_trainging | /2.Python_basic/Chapter01/Problem01.py | 212 | 4.1875 | 4 | Numslist=[]
num=int(input("input your number : "))
for i in range(0,num):
element=int(input("input number : "))
Numslist.append(element)
avg=sum(Numslist)/num
F=round(avg,2)
print(avg)
print(f'avg = {F}') |
ae569f759f0ac9765dc2df0a7d10ad97e83c6d12 | wangyendt/LeetCode | /Easy/496. Next Greater Element I/Next Greater Element I.py | 559 | 3.546875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# author: wang121ye
# datetime: 2019/7/16 10:12
# software: PyCharm
class Solution:
def nextGreaterElement(self, nums1: list, nums2: list) -> list:
ret = []
for n in nums1:
i = nums2.index(n)
for j in range(i + 1, len(nums2)):
if nums2[j] > n:
ret.append(nums2[j])
break
else:
ret.append(-1)
return ret
so = Solution()
print(so.nextGreaterElement([4, 1, 2], [1, 3, 4, 2]))
|
3fbe7f33d4a50efeac427b8e85a4503e9380ebe2 | Svyat33/beetroot_python | /lesson_7_functions/lesson7_task1_simple_function.py | 406 | 4.25 | 4 | # Task 1
# A simple function.
# Create a simple function called favorite_movie, which takes
# a string containing the name of your favorite movie.
# The function should then print “My favorite movie is
# named {name}”.
def favorite_movie(film_name):
print(f'My favorite movie is named "{film_name}".\n')
if __name__ == "__main__":
film = "Best movie in the world!"
favorite_movie(film)
|
415059588b98e64211aefbd028e6650b2ac229da | Joaovictoroliveira/Exercicios-Python---Hora-Extra | /calcular_salario.py | 242 | 3.953125 | 4 | salario_hora = int(input("Digite o salario/hora do funcionario: "))
horas_por_mes = int(input("Digite a quantidade de horas trabalhadas no mes: "))
salario_mes = salario_hora * horas_por_mes
print("salario do funcionario: ", salario_mes)
|
adcb99912aaab699c446712a4fd3714debd669c5 | ddh/leetcode | /python/maximum_average_subarray_i.py | 1,525 | 4.0625 | 4 | """
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].
"""
# Idea: We're going to use a sliding window. Good that we know k, the length of the subarray.
# We will slide the window along and compute the SUM as we go. No need to compute the average
# until the very end since what we're looking for is the largest sum that will thus give
# us the largest average. To get the new sum, we subtract the element we slide away from on the left,
# then add the value from the element we slid into on the right
from typing import List
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
# Keep pointers at opposites ends of sliding window
start = 0
end = k - 1
current_sum = sum(nums[:k])
max_sum = current_sum
while end < len(nums) - 1:
current_sum -= nums[start] # Subtract the left element
current_sum += nums[end + 1] # Tack on the right element
max_sum = max(max_sum, current_sum) # Keep the largest sum we've encountered so far
# Moving the window up
start += 1
end += 1
return max_sum / k
# Driver
print(Solution().findMaxAverage([1,12,-5,-6,50,3], 4)) # 12.75 |
d8c08777006dbd9940ef6a297954b1c871273d46 | ahmedzaabal/Feet-to-Meter | /main.py | 1,400 | 3.515625 | 4 | from tkinter import Tk, Button, Label, DoubleVar, Entry
window = Tk()
window.title("Feet to Meter Conversion App")
window.configure(background="light green")
window.geometry("320x220")
window.resizable(width = False, height = False)
def convert():
"""
docstring
"""
value = float(feet_entry.get())
meter = value * 0.3048
meter_value.set("%.4f" %meter)
def clear():
feet_value.set("")
meter_value.set("")
feet_label = Label(window, text="Feet", bg = "purple", fg="white", width = 14)
feet_label.grid(column= 0 , row=-0, padx = 15, pady = 15)
feet_value = DoubleVar()
feet_entry = Entry(window, textvariable=feet_value, width = 14)
feet_entry.grid(column = 1, row = 0)
feet_entry.delete(0, 'end')
meter_label = Label(window, text="Meter", bg = "red", fg="white", width = 14)
meter_label.grid(column= 0 , row=1, padx = 15, pady = 15)
meter_value = DoubleVar()
meter_entry = Entry(window, textvariable=meter_value, width = 14)
meter_entry.grid(column = 1, row = 1)
meter_entry.delete(0, 'end')
convert_button = Button(window, text = "Convert" , bg = "blue", fg = "white", width = 14, command = functions.convert)
convert_button.grid(column=0 , row = 2, padx = 15, pady = 20)
clear_button = Button(window, text = "Clear", bg = "black", fg = "white", width = 14, command = functions.clear)
clear_button.grid(column= 1 , row = 2, padx = 15)
window.mainloop() |
7b1cd5af373265bb6f1d112b476a499629db984d | shapovalovdev/AlgorythmsAndDataStructures | /src/Stack/stack_linked_list_head.py | 2,298 | 4.125 | 4 | class Node:
def __init__(self, v):
self.value=v
self.next=None
self.prev=None
class StackHead:
def __init__(self):
self.head=None
self.tail=None
def size(self):
node = self.head
length=0
while node is not None:
length+=1
node = node.next
return length
def is_empty(self):
if self.size()==0:
return True
else:
return False
def pop(self):
if self.head is None:
return None #if the stack is empty
else:
item=self.head
if self.head.next is not None:
self.head=self.head.next
elif self.head.next is self.tail:
self.head=self.tail
else:
self.head=None
self.tail=None
return item.value
def push(self, value):
item=Node(value)
if self.head is None:
self.head=item
self.tail=item
elif self.tail is self.head: # case of 1 item
self.tail.prev=item
self.head=item
item.next=self.tail
else:
prev_head=self.head
self.head=item
item.next=prev_head
def peek(self):
if self.is_empty():
return None
else:
return self.head.value
def print_stack(self):
node=self.head
while node is not None:
print(node.value)
node=node.next
if "__main__"==__name__:
test_stack=StackHead()
print (test_stack.size())
print (test_stack.is_empty())
test_stack.push(2)
test_stack.push(3)
test_stack.push(-100)
test_stack.print_stack()
test_stack.pop()
print("##############")
test_stack.print_stack()
while test_stack.size() > 0:
print(f"I've popped the value of {test_stack.pop()}")
print(f"I've popped the value of {test_stack.pop()}")
test_stack.print_stack()
print("##############")
stack=StackHead()
for i in range (1,9):
stack.push(i)
while stack.size() > 0:
print (stack.pop())
print (stack.pop())
|
85afc94838f479658b4c21f0d1cbdf00d80faa5a | SamuelTeguh/UPH | /ex.inp.2.py | 104 | 3.84375 | 4 | age = int(input("Please enter your age:"))
olderAge = age + 1
print ("Next year you will be", olderAge)
|
e58bcfc7605c2e099f693fefecf4a4c47542838d | cronJ/scan-rename | /main.py | 2,425 | 3.5625 | 4 | #!/usr/bin/env python3
import os
from tkinter import *
from tkinter import filedialog
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.directory = ""
self.list_of_files = []
self.image = None
self.directory_label = Label(frame, text="Directory")
self.directory_label.grid(row=0, column=0)
self.directory_entry = Entry(frame, width=90)
self.directory_entry.grid(row=0, column=1)
self.directory_btn = Button(frame,
text="Load",
command=self.load_directory)
self.directory_btn.grid(row=0, column=2)
self.name_label = Label(frame, text="Filename")
self.name_label.grid(row=1, column=0)
self.name_entry = Entry(frame, width=90)
self.name_entry.grid(row=1, column=1)
self.rename_btn = Button(frame,
text="Rename",
command=self.rename_file)
self.rename_btn.grid(row=1, column=2)
self.file_list = Listbox(frame,
listvariable=self.list_of_files,
selectmode=SINGLE,
height=30,
width=50)
self.file_list.grid(row=3, column=0, columnspan=1)
self.canvas = Canvas(frame,
bg='white',
height=100,
width=80)
self.canvas.grid(row=3, column=1, columnspan=2)
def load_directory(self):
self.directory = filedialog.askdirectory()
self.directory_entry.insert(0, self.directory)
self.update_file_list()
def rename_file(self):
print("Rename file to: " + self.name_entry.get())
def update_file_list(self):
if self.directory != "":
for _, _, self.file in os.walk(self.directory):
for self.element in self.file:
self.file_list.insert(END, self.element)
self.list_of_files.append(self.element)
def create_file_image(self):
self.image = None
def show_file_image(self):
self.canvas.create_image(100, 80, anchow=NW, image=self.image)
root = Tk()
root.title("Scan rename")
root.minsize(width=800, height=640)
app = App(root)
root.mainloop()
|
479c0af84249064d2b1833df8af57e6449fff74a | NicoR10/PythonUNSAM | /ejercicios_python/envido.py | 2,401 | 3.640625 | 4 | import random
from collections import Counter
valores = [1, 2, 3, 4, 5, 6, 7, 10, 11, 12]
palos = ['oro', 'copa', 'espada', 'basto']
naipes = [(valor, palo) for valor in valores for palo in palos]
def buscar_envido():
'''
Pide una mano y se fija si hay envido.
Retorna el puntaje.
Para mas detalle descomentar los prints
'''
mano = random.sample(naipes, k=3)
#print('Mano: ', mano)
cartas_validas_para_envido = [(valor,palo) for (valor, palo) in mano if valor < 10]
#print('Cartas que pueden sumar: ', cartas_validas_para_envido)
palos_de_la_mano = [palo for (valor, palo) in mano if valor < 10]
palo_repetido = Counter(palos_de_la_mano).most_common(1)
#print('Palo y repeticiones: ', palo_repetido)
valores_de_la_mano = [valor for (valor, palo) in cartas_validas_para_envido if palo == palo_repetido[0][0]]
#print('Numero de los palos repetidos: ', valores_de_la_mano)
if len(cartas_validas_para_envido) < 2:
#print('No hay envido')
return 0
else:
if palo_repetido[0][1] == 1:
#print('No hay envido')
return 0
elif palo_repetido[0][1] == 2:
#print('Hay chance de envido')
puntaje = sum(valores_de_la_mano) + 20
#print(puntaje)
return puntaje
else:
#print('Hay 3 palos iguales hay que elegir las dos mayores')
valores_ordenados = valores_de_la_mano.copy()
valores_ordenados.sort()
puntaje = valores_ordenados[1] + valores_ordenados[2] + 20
return puntaje
# %% Probabilidad de obtener 31, 32 o 33 puntos en una mano
N = 1000000
resultados = [buscar_envido() for _ in range(N)]
G = sum([1 for resultado in resultados if resultado == 31])
prob = G/N
print(f'Jugué {N} veces, de las cuales {G} saqué envido con 31.')
print(f'Podemos estimar la probabilidad de sacar envido con 31 mediante {prob:.6f}.')
G = sum([1 for resultado in resultados if resultado == 32])
prob = G/N
print(f'Jugué {N} veces, de las cuales {G} saqué envido con 32')
print(f'Podemos estimar la probabilidad de sacar envido con 32 mediante {prob:.6f}.')
G = sum([1 for resultado in resultados if resultado == 33])
prob = G/N
print(f'Jugué {N} veces, de las cuales {G} saqué envido con 33')
print(f'Podemos estimar la probabilidad de sacar envido con 33 mediante {prob:.6f}.') |
52363037c0f5acdd6f929369cfe38717d73cdd79 | Marceloalf/Edustation | /escola_v1/s_year.py | 503 | 3.734375 | 4 | def school_years():
pre_school = 2
basic_school = 9
high_school = 3
levels = []
for level in range(1, pre_school + 1):
levels.append(("{}º PS".format(level), "{}º ano primário".format(level)))
for level in range(1, basic_school + 1):
levels.append(("{}º BS".format(level), "{}º ano fundamental".format(level)))
for level in range(1, high_school + 1):
levels.append(("{}º HS".format(level), "{}º ano medio".format(level)))
return levels
|
b299ad79275f5d32cdb2c4cf95d97feaa33aa37f | artbohr/codewars-algorithms-in-python | /7-kyu/sort-gift-code.py | 932 | 3.9375 | 4 | sort_gift_code = lambda x: ''.join(sorted(x))
'''
Happy Holidays fellow Code Warriors!
Santa's senior gift organizer Elf developed a way to represent up to
26 gifts by assigning a unique alphabetical character to each gift.
After each gift was assigned a character, the gift organizer Elf
then joined the characters to form the gift ordering code.
Santa asked his organizer to order the characters in alphabetical order,
but the Elf fell asleep from consuming too much hot chocolate and candy
canes! Can you help him out?
Sort the Gift Code
Write a function called sortGiftCode/sort_gift_code/SortGiftCode that accepts
a string containing up to 26 unique alphabetical characters, and returns a
string containing the same characters in alphabetical order.
Examples:
sort_gift_code( 'abcdef' ) # 'abcdef'
sort_gift_code( 'pqksuvy' ) # 'kpqsuvy'
sort_gift_code( 'zyxwvutsrqponmlkjihgfedcba' ) # 'abcdefghijklmnopqrstuvwxyz'
''' |
bc42a3de125338c72051f85b2b6bb39c14548803 | Whiteshadow-hacker/white_shadow | /assesment/QUESTION_15.py | 225 | 4.28125 | 4 | str=input("enter the string:")
bit=list()
for i in str :
if i != '0' or i != '1':
bit.append(i)
if not bit:
print("the string contains only 0 or 1")
else:
print("the string does not contain only 0 or 1")
|
55305174539fbf71b3e67151b4f402548566130d | edbeeching/ProjectEuler | /myutils.py | 2,219 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 29 17:13:48 2017
@author: Edward
"""
class Figurate:
@staticmethod
def triagonal(n):
return int(n*(n+1)/2)
@staticmethod
def square(n):
return int(n**2)
@staticmethod
def pentagonal(n):
return int(n*(3*n-1)/2)
@staticmethod
def hexagonal(n):
return int(n*(2*n-1))
@staticmethod
def heptagonal(n):
return int(n*(5*n-3)/2)
@staticmethod
def octagonal(n):
return int(n*(3*n-2))
def test():
for n in range(1,6):
print(n, 'triagonal', Figurate.triagonal(n))
print(n, 'square', Figurate.square(n))
print(n, 'pentagonal', Figurate.pentagonal(n))
print(n, 'hexagonal', Figurate.hexagonal(n))
print(n, 'heptagonal', Figurate.heptagonal(n))
print(n, 'octagonal', Figurate.octagonal(n))
import math
def is_prime(number):
# Code taken for wikipedias entry on prime numbers, but fairly simple
if number <= 1:
return False
elif number <=3:
return True
elif number % 2 == 0 or number % 3 == 0:
return False
i=5
while i*i <= number:
if number % i == 0 or number % (i+2) == 0:
return False
i += 6
return True
def is_composite(n):
return not is_prime(n)
def get_divisors(num):
divs = set()
for i in range(1,int(math.sqrt(num))+1):
if num % i == 0:
divs.add(i)
divs.add(num//i)
return sorted(list(divs))
def is_pandigital(n, digits=9):
if len(str(n)) != 9:
return False
if len(set(str(n))) == len(str(n)):
return True
return False
def rotate(s,r):
return s[r:] + s[:r]
def get_prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
if __name__ == '__main__':
Figurate.test() |
d679639d7a197b21129fb24c6dd4b4d7ef89806e | liyanhe95/basic | /python/class_02/function_1208.py | 1,272 | 3.9375 | 4 | #函数的定义:实现某个指定的功能 重复使用
# type()
# len()
# range()
#函数有啥作用:可以提高代码的复用性
#函数的具体语法:关键字 def
#def 函数名(参数1,参数2,参数3):
#函数体:本函数要实现的功能
#return 表达式
#def 顶格写 表示这是一个函数
#函数名 小写 不同的字母与数字之间用下划线隔开 不能以数字开头
#参数的个数可以大于等于0
#函数体是函数的子代码 要有缩进 写自己想实现的功能即可
#return后面的表达式 >=0 个
#return 就是当你调用函数的时候 会返回return后面的表达式的值
#如果return后面没有表达式 写没写 没有区别
#如何调用函数 函数名(对应参数个数)
def radio_machine():
print('就是一个复读机,只会说:你好!!!')
return #隐式的添加一个return
res = radio_machine() #res 存储返回的值
print('函数的返回值是:{}'.format(res))
#函数里面return的表达式个数
#==1 返回你指定的数据类型
#>1 返回的是元组类型
#==0 返回None
def add():
result = 8 + 8
print(result)
return result
res1 = add()+ 20
print(res1)
#请你拿到add()运行的求和结果 再去加20 输出到控制台
|
6f120046dd15c7de5ea92cf4e1363c2224661412 | YOOOOONA/algorithm_study | /[프로그래머스]점프와순간이동.py | 649 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 00:52:46 2020
@author: 융
"""
#k칸 앞으로 이동 or 현재까지온거리*2만큼 순간이동 가능. k칸 이동은 k만큼 건전지 닳아.
#N거리에 가려고 해.최대한 순간이동 많이 해서
#사용해야되는 최소건전지양 리턴
def sol(n,answer):
if n==1 or n==2:
return answer#####
else:
if n%2==1:
return sol((n-1)//2,answer+1)######꼭 리턴을 써줘야지
else:
return sol(n//2,answer)#####
def solution(n):
answer=1
return sol(n,answer)
print(solution(5))
print(solution(6))
print(solution(5000)) |
b6dc5db297cc164f84079241cd564703ab6dc0d9 | moonimooni/get-random-test | /get_random.py | 712 | 3.828125 | 4 | import random
def get_zero_or_one():
return random.randint(0,1)
def get_random(max_num):
num = max_num - 1
# change decimal max num to binary
max_bin = ""
while num >= 1:
if num == 1:
max_bin = "1" + max_bin
break
num, left_num = num // 2, num % 2
max_bin = str(left_num) + max_bin
while True:
# fill list of max_binary length with 0, 1 by random
random_bin_elements = [get_zero_or_one() for _ in range(len(max_bin))]
# change binary to decimal and compare original max_num
decimal = 0
for i in range(len(random_bin_elements[::-1])):
if random_bin_elements[i] == 1:
decimal += (2**i)
if decimal <= max_num - 1:
return decimal |
e751a32549e3c35724dc0be273e7f135d5c14d56 | xuyoji/MLDC | /mldc.py | 4,435 | 3.515625 | 4 | #written by xu yongjie 12/24/2017
class graph():
class node():
def __init__(self, k):
#k is the sequence of the node
self.k = k
self.next = []
#contain the nodes node k point to and the weight between them
#[[1, 2], [4, 5]] for example
#means point to 1 and 4 with weights 2 and 5
self.former = []
#contain the former nodes and weights
def read_input(self):
def one_edge():
line = input()
u, v, w = line.split()
return int(u), int(v), float(w)
#the first line include num of arcs (m) and nodes (n)
m, n = [int(i) for i in input().split()]
#arcs from the first to the second with weight third num
arcs = [one_edge() for _ in range(m)]
return m, n, arcs
def __init__(self):
self.m, self.n, self.arcs = self.read_input()
self.nodes = [node(i) for i in range(1, self.n + 1)]
for arc in self.arcs:
self.nodes[arc[0] - 1].next.append(arc[1:])
self.nodes[arc[1] - 1].former.append([arc[0], arc[2]])
def MMC(self):
record = [[None for i in range(self.n + 1)] for j in range(self.n)]
paths = [[None for i in range(self.n + 1)] for j in range(self.n)]
def d(k, w):
if record[k][w - 1] is not None:
return record[k][w - 1]
if k == 0:
if w == 1:
return 0
else:
return float('inf')
point = self.node[w - 1]
choice = [d(k - 1, point.former[i][0]) + point.former[i][1] for i in range(len(point.former))]
opt = min(choice)
paths[k][w - 1] = point.former[choice.index(opt)]
return opt
for v in range(1, self.n +1):
for k in range(self.n + 1):
d(k, v)
def maximum(array):
m = max(array)
return (m, array.index(m))
def minimum(array):
m = min(array)
return (m, array.index(m))
u = min([maximum([(record[v][self.n] - record[v][k]) / (self.n - k) for k in range(self.n)]) for v in range(self.n)])
def get_path(k, w):
path = []
while True:
former = paths[k][w - 1]
path.append((former, w))
if w == 1 and k == 0:
break
return path
large_path = get_path(n, u[1] + 1)
little_path = get_path(u[0][1], u[1] + 1)
for l in large_path:
if l in little_path:
large_path.remove(l)
return large_path, u[0][0]
def MLC(self, s):
record =[None for i in range(self.n)]
buckets = [[] for k in range(1, len(self.w))]
ds = [float('inf') for i in range(n)]
ds[0] = 0
def get_path(w, s):
path = []
while True:
former = record[w - 1]
path.append((former, w))
if former == s:
break
return path
def get_arc(j, s):
for arc in self.arcs:
if arc[:1] == [j, s]:
for i in self.nodes1[j - 1].next:
if i[0] == s:
return i[1]
return float('inf')
def dis_update(i, s):
for j in self.nodes1[i - 1].next:
if ds[j[0] - 1] > ds[i - 1] + j[1]:
old = ds[j[0] - 1]
ds[j[0] - 1] = ds[i - 1] + j[1]
record[j - 1] = i
bucket_update(s, j, old)
def bucket_update(s, j, old):
k = int(ds(j - 1) / self.lmbd)
k_old = int(old / self.lmbd)
if ((k < len(self.w)- 1) and j not in buckets[k - 1]):
del buckets[old - 1][buckets[old - 1].index(j)]
buckets[k - 1].append(j)
dis_update(s, s)
while True:
for k in range(len(buckets)):
if buckets[k] != []:
j = buckets[k][0]
del buckets[k][0]
djs = get_arc(j, s)
if self.mldc > ds[j - 1] + djs:
self.mldc = ds[j - 1] + djs
self.w = get_path(w, s)
update(j, s)
if k == len(buckets) - 1:
break
def MLDC(self):
self.w, self.lmbd = self.MMC()
self.mldc = cw * len(self.w)
self.nodes0 = [node(i) for i in range(1, self.n + 1)]
for arc in self.arcs:
self.nodes0[arc[0] - 1].next.append([arc[1], arc[2] - self.lmbd])
self.nodes0[arc[1] - 1].former.append([arc[0], arc[2] - self.lmbd])
record = [None for i in range(self.n)]
def p(w):
if record[w - 1] is not None:
return record[w - 1]
if w == 1:
return 0
pw = min([p(i[0]) + i[1] for i in self.nodes0[w - 1].former])
record[w - 1] = pw
return pw
self.nodes1 = [node(i) for i in range(1, self.n + 1)]
for arc in self.arcs:
self.nodes1[arc[0] - 1].next.append([arc[1], arc[2] + record[arc[0] - 1] - record[arc[1] - 1]])
self.nodes1[arc[1] - 1].former.append([arc[0], arc[2] + record[arc[0] - 1] - record[arc[1] - 1]]) |
40c2eb86b3813110b80d5a84f78d6808af68faae | karsevar/Crash_Course_Python- | /CCpython_ch3_exer1.py | 1,330 | 4.3125 | 4 | ##3-1
friends = ["Ari Encombe", "Robert Grey", "Masanori", "Masa", "Kenji", "Jonny Phan", "Brian Miller"]
print(friends)
for friends in friends:
print(friends)# Is is way simpler than R programming. To make a comparible
#loop you need to write for(i in 1:friends){ print(friends[i])}
##3-2
friends = ["Ari Encombe", "Robert Grey", "Masanori", "Masa", "Kenji", "Jonny Phan", "Brian Miller"]
message = "How's everything going bro?"
for friends in friends:
print(friends + "!")
print(message)
#For loops have an odd characteristic where after the indexed list is used
#the list is over written by the last indexed object.
#I was forced to rewrite the friends list as a result.
##3-3
trans = ["Hudson Hornet", "trains", "planes", "city buses"]
for trans in trans:
messages = ["I would like to purchase a " + str(trans) + " once I become a data scientist.", "Interestingly enough " + trans + " don't make me sick.", "I hate riding in " + trans + " for long periods of time.", "I miss riding " + trans + " to the end of the line."]
print(messages)
#this wasn't what I had in mind. Will need to find a way to combine the
#index positions of messages with trans.
for messages in trans:
print(messages)
#This is somewhat better. The trans list objects were printed in the proper
#messages but in the end the letters of city buses were printed onto the console.
|
d08469af450ddfd3380ed4f98b625378e5fe9d65 | denemorhun/Python-Problems | /AlgoExperts/Arrays/validate_subsequence.py | 1,472 | 3.984375 | 4 | '''
Given an array of DISTINCT integers, Validate a second array is a subset
Main idea here is to check matches in only 1 direction
'''
# return the two numbers from array that equal to target
def isValidSubsequence(array, sequence):
isSub = False
pos = 0
# outer loop is the sequence
for i in range (len(sequence)):
isSub = False
# inner loop is the Main array
for j in range(pos, len(array)):
if sequence[i] == array[j]:
# once we hit a match set subSet to True
isSub = True
# move the position past last found match in main array
pos = j+1
break
else:
pos+=1
return isSub
if __name__ == '__main__':
# sorted array
print (f'Sorted array values are {isValidSubsequence([1, 3, 5, 6, 10],[3, 10])} ')
# non sorted array
print (f' Non - Sorted array values are {isValidSubsequence([1, 3, 6, 5, 10],[3, 10])} ')
# # array with negative values
# print (f' Negative array values are {isValidSubsequence([1, 3, -6, 5, 10],[3, 10])} ')
# # array with no succesful values - none
print (f' Unsuccesful array values are {isValidSubsequence([1, 3, -6, 5, 10],[3, 11])} ')
# # array that failed
print (f' Should be succesful array values are {isValidSubsequence([5, 1, 22, 25, 6, -1, 8, 10],[22, 25, 6])} ')
# # array with repetition number equaling targetSum i.e. 8 - none
|
8398decfeb72da5adc31498fa15a9f5dc2811a22 | omarSuarezRodriguez/Python | /Portafolio/programasConsola/indice.py | 2,596 | 3.625 | 4 | '''
1.
Imprimir “Hola mundo” por pantalla.
2.
Crear dos variables numéricas, sumarlas y mostrar el resultado
3.
Mostrar el precio del IVA de un producto con un valor de 100 y su precio final.
4.
De dos números, saber cual es el mayor.
5.
Crea una variable numérica y si esta entre 0 y 10, mostrar un mensaje indicándolo.
6.
Añadir al anterior ejercicio, que si esta entre 11 y 20, muestre otro mensaje
diferente y si esta entre 21 y 30 otro mensaje.
7.
Mostrar con un while los números del 1 al 100.
8.
Mostrar con un for los números del 1 al 100.
9.
Mostrar los caracteres de la cadena “Hola mundo”.
10.
Mostrar los números pares entre 1 al 100.
11.
Generar un rango entre 0 y 10
12.
Generar un número entre 5 y 10
13.
Generar un rango de 10 a 0.
14
Generar un rango de 0 a 10 y de 15 a 20, incluidos el 10 y 20
15.
Generar un rango desde 0 hasta la longitud de la cadena “Hola mundo”
16.
Pide dos cadenas por teclado, muestra ambas cadenas con un espacio
entre ellas y con los 2 primeros caracteres intercambiados. Por ejemplo,
Hola Mundo pasaría a Mula Hondo
17.
Pide una cadena e indica si es un palíndromo o no.
18.
Juguemos al juego de adivinar el numero, generaremos un número entre 1 y 100.
Nuestro objetivo es adivinar el número. Si fallamos nos dirán si es mayor o menor
que el número buscado. También poner el número de intentos requeridos.
19.
Lee dos valores por teclado, muestra por consola la suma, resta, multiplicación,
división y módulo.
20.
Haz una aplicación que calcule el área de un círculo(pi*R2). El radio se pedirá por
teclado (recuerda pasar de String a double con Double.parseDouble). Usa la constante
PI y el método pow de Math.
21
Lee un número por teclado y muestra por consola, el carácter al que pertenece en la
tabla ASCII. Por ejemplo: si introduzco un 97, me muestre una a.
22
Lee una letra por teclado y muestra por consola, el numero al que pertenece en la
tabla ASCII. Por ejemplo: si introduzco a, me muestre 97.
23
Realiza una aplicación que nos pida un número de ventas a introducir, después nos
pedirá tantas ventas por teclado como número de ventas se hayan indicado. Al final
mostrara la suma de todas las ventas. Piensa que es lo que se repite y lo que no.
'''
|
d4b8925bbf0644f086cc8d2a7f8ef0855bf4c483 | Alm3ida/resolucaoPythonCursoEmVideo | /desafio41.py | 583 | 4.15625 | 4 | """
A confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre
sua categoria, de acordo com a idade:
-Até 9 anos: MIRIM
-Até 14 anos: INFANTIL:
-Até 19 anos: JÚNIOR:
-Até 20 anos: SÊNIOR
-Acima: MASTER
"""
from datetime import date
year = int(input('Digite o ano de seu nascimento: '))
age = date.today().year - year
if age in range(0,10):
print('Categoria MIRIM')
elif age in range(10,15):
print('Categoria INFANTIL')
elif age in range(15,20):
print('Categoria JÚNIOR')
else:
print('Categoria MASTER')
|
90f61c0aa52efe8f8e0d9eeaadc0daa8247d2bfe | emmaryd/bioinformatics-course | /assignment3/main_chain.py | 3,613 | 3.890625 | 4 | #EMMA RYDHOLM
import numpy as np
import math
UPPER_DIST = 3.95
LOWER_DIST = 3.65
def read_file(filepath):
""" Reads the positions from file, assuming that the atom numbers starts at 1 and is aranged in order
Args:
filepath: string that contains the filepath
"""
positions = []
with open(filepath) as f:
lines = f.readlines()
for line in lines:
line = line.split()
atom_position = (float(line[1]),float(line[2]),float(line[3]),)
positions.append(atom_position)
return positions
def distance(pos_1,pos_2):
"""Calculate the distance between 2 points.
Args:
pos_1: describes the position 1 in 3 dimensions
pos_2: describes the position 2 in 3 dimensions
Returns:
distance is the euclidean distance between pos_1 and pos_2
"""
x_1,y_1,z_1 = pos_1
x_2,y_2,z_2 = pos_2
distance = ( (x_2 - x_1)**2 + (y_2 - y_1)**2 + (z_2 - z_1)**2 ) **0.5
return distance
def distance_between_all(positions):
"""Calculates the distances between all points given in positions
Args:
positions: an itetable containing the positions for each atom
Returns:
distances: an array with the distances between all atoms
"""
n_points = len(positions)
distances = np.zeros((n_points, n_points))
for i in range(n_points):
for j in range(n_points):
pos_1, pos_2 = positions[i], positions[j]
dist = distance(pos_1, pos_2)
distances[i][j] = dist
return distances
def find_path(distances):
"""Finds the best path that describes how the alpha-carbon atoms are arranged,
based on the assumption that all alpha-carbon atoms has distance at approximately 3.8Å of each other
Args:
distances: a matrix with the distances between the atom of interest
Returns:
path: The path represent to the most probable path of the atoms that makes the alpha-carbon chain
"""
path = []
for row in range(distances.shape[0]):
if np.sum(row) == 1:
current = row
path.append(row)
prev = None
break
end_of_sequence = False
while end_of_sequence == False:
potential_next = []
for i, dist in enumerate(distances[current]):
if dist > LOWER_DIST and dist < UPPER_DIST:
if i != current and i != prev:
potential_next.append(i)
if len(potential_next) == 1:
path.append(potential_next[0])
elif len(potential_next) > 1:
most_probable = None
least_deviation = 1
for j in potential_next:
deviation = np.absolute(distances[current][j] - 3.8)
if deviation < least_deviation:
most_probable = j
least_deviation = deviation
path.append(most_probable)
elif len(potential_next) == 0:
end_of_sequence = True # Set to true when the chain has no more connected atom
current = path[-1]
prev = path[-2]
path = [x + 1 for x in path] # add one to all indices, since in the file the indices starts at 1
print("Path:")
for i in path:
print(i)
print("Number of alpha-carbon atoms in main chain: ", len(path))
return path
#run
files = ['data_q1.txt', 'test_q1.txt']
for f in files:
print(f)
positions = read_file(f)
distances = distance_between_all(positions)
path = find_path(distances)
# How to run the program: python3 main_chain.py |
288bf39b8e205bbd42c2fbf8b66fef1368ca62e5 | MaazSc/python-basics | /sortList.py | 222 | 3.796875 | 4 | l=[1,2]
l.extend([3,4,5])
print(l)
l.pop()
print(l)
s="maaz"
abc=list(s)
print(abc)
s="".join(abc)
print(s)
lists=["abc","def","ghi","jkl"]
x="nn".join(lists)
print(x)
T=tuple(l)
print(T)
T=list(T)
print(T) |
2ca10e31cf48801d53b05c8d14a2f8f7764e170e | rafaelperazzo/programacao-web | /moodledata/vpl_data/97/usersdata/216/56558/submittedfiles/lecker.py | 784 | 3.515625 | 4 | # -*- coding: utf-8 -*-
n=int(input('Digite a quantidade de números na lista:'))
h=[]
b=[]
for i in range(0,n,1):
c=int(input('Digite um valor para lista h:'))
h.append(c)
for i in range(0,n,1):
d=int(input('Digite um valor para lista b:'))
b.append(d)
def lecker(a):
cont=0
for i in range(0,len(a),1):
if i==0
if (a[i])>(a[i+1]):
cont=cont+1
elif i==(len(a)-1):
if (a[i])>(a[len(a)-1]):
cont=cont+1
else:
if (a[i])>(a[i+1]) and (a[i])>(a[i-1]):
cont=cont+1
if cont==1
return True
else:
return False
if lecker(h):
print('S')
else:
print('N')
if lecker(b):
print('S')
else:
print('N')
print(b)
print(h) |
fe79f8b1591f8363ef861f69c195699a444fd970 | fzaman2258/In_Progress | /Games/Hangman.py | 2,870 | 4.25 | 4 | import random
def wrong(letter):
if letter not in word:
return True
return False
def print_curr_state(word, letter, letters_remaining, list_letters_remaining):
index = 0
for char in word:
if char == letter:
list_letters_remaining[index] = letter
letters_remaining -= 1
index += 1
return letters_remaining
# This part is just random list of words for the user to guess
list_of_words = ["appliances", "attic", "backyard", "barbecue", "baseboard", "basement", "bathroom", "bathtub",
"bedroom", "blinds", "broom", "bunk", "bed", "carpet", "car", "ceiling", "cellar", "chimney", "closet",
"clothes", "dryer", "washer", "concrete", "counter", "crib", "cupboard", "curtain", "rod"]
# Select a word from the list randomly doing math
r_num = random.randrange(0, len(list_of_words))
word = list_of_words[r_num]
letters_remaining = len(word) # Initially its length of word and decrements every right letter inputted
guesses = 0 # I will give 9 guesses for any word
won = False
list_letters_remaining = []
letters_input = []
# Make little visual in command line with underscores
for i in range(0, len(word)):
list_letters_remaining.append(" _ ")
# Start the actual game and print updated visuals depending on flow
while guesses < 9:
print()
print("".join(list_letters_remaining))
# Only way to win is to get all the letters
if letters_remaining == 0:
won = True
break
# Update user how many guesses left
remain = 9-guesses
print("You only have ", remain, " guesses remaining! ","Letters already inputted:a ", letters_input)
# Words are not case-sensitive to lower everything
letter = input("Enter your letter: ")
letter = letter.lower()
'''
Here is the logic of hangman:
1) Check if a letter has been already inputted
2) Check if input is even a letter
3) Check if letter is wrong via function
Once all goes well, update the number of letters remaining by subtracting every place a letter is now being shown
Update visual for user to see the current state
'''
if letter in letters_input:
print()
print("You have already entered this letter!")
elif letter.isalpha() is False:
print()
print("You can only enter letters!")
elif len(letter)>1 :
print()
print("Only one letter at a time!")
elif wrong(letter) is True:
guesses += 1
letters_input.append(letter)
else:
letters_remaining = print_curr_state(word, letter, letters_remaining, list_letters_remaining)
letters_input.append(letter)
if won:
print("GG YOU WON")
else:
print('GG YOU LOST')
|
6333a8ad89d31ec76fdb44d3cc256126050e0050 | wiiaam/filehost | /auths.py | 771 | 3.796875 | 4 | #!/usr/bin/env python3.3
import sys
import hashlib
def addPass(password):
with open("auths") as f:
passwords = [x.strip('\n') for x in f.readlines()]
hash = hashlib.sha256(password.encode('utf-8')).hexdigest()
if passwords.__contains__(hash) is False:
with open("auths","a") as f:
f.write(hash + "\n")
print("Password added")
if len(sys.argv) > 1:
if sys.argv[1] == "--addpass":
if len(sys.argv) > 2:
addPass(sys.argv[2])
else:
print("Please specify a password")
def chechPass(password):
with open("auths") as f:
passwords = [x.strip('\n') for x in f.readlines()]
hash = hashlib.sha256(password.encode('utf-8')).hexdigest()
return passwords.__contains__(hash)
|
49c029af3c4396ebc2498257c562b9b7d41e9fe4 | EachenKuang/LeetCode | /code/110#Balanced Binary Tree.py | 1,331 | 3.75 | 4 | # https://leetcode.com/problems/balanced-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# 1 使用104中的maxDepth
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# 1 用递归
if root == None:
return True;
flag = abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1
return flag and self.isBalanced(root.left) and self.isBalanced(root.right)
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
# 2 一个函数递归
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# 1 用递归
def dfs(root):
if root is None:
return 0
left = dfs(root.left)
right = dfs(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return dfs(root) != -1
|
8a63b2cd7cd7d780aa3336e191d9a0b04575dbc0 | gwcpdx/fall_term_backend | /Lesson4_listMethods/Lesson4_listMethods_livecode.py | 524 | 4.4375 | 4 | # Lesson 4 - List Methods living coding examples
cities = ["Portland", "Vancouver", "Eugene", "Seattle", "Boring", "Beaverton"]
# Add one item to the list
one_state = 'Alaska'
cities.append(one_state)
print cities
# Add a LIST to an existing list!
states_list = ["Oregon", "Washington", "California", "New York", "Georgia"]
cities.append(states_list)
print cities
# Concatenating lists
all_the_cities = ["NYC", "Nashville", "Austin", "San Francisco"]
many_many_cities = all_the_cities + cities
print many_many_cities
|
8d18ab90859dd5bf41d2a94bef862499d5ceb71a | tahadavari/ICPC | /Questions/Kth smallest element .py | 406 | 3.671875 | 4 | # link : https://practice.geeksforgeeks.org/problems/kth-smallest-element5635/1#
# sorting
class Solution:
def kthSmallest(self,arr, l, r, k):
'''
arr : given array
l : starting index of the array i.e 0
r : ending index of the array i.e size-1
k : find kth smallest element and return using this function
'''
arr.sort()
return arr[k-1] |
93c2a1d1f22f08e4fb076b4ea1ad57d8c2af8e80 | noelp2500/Principles-of-Computing-Part-1 | /2048(full).py | 6,217 | 3.859375 | 4 | # 2048 (full)
# Author - Noel Pereira
# Submission - http://www.codeskulptor.org/#user47_MqRFwhG2Vy_2.py
####################################################################
"""
Clone of 2048 game.
"""
import random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0), DOWN: (-1, 0), LEFT: (0, 1), RIGHT: (0, -1)}
def merge(line):
"""
Function that merges a single row or column in 2048.
:param line: array with elements
:return: new array of elements after the merge operation
"""
newline = shift(list(line))
for index in range(len(newline)):
if index + 1 < len(newline):
if newline[index] != 0 \
and newline[index] == newline[index + 1] != 0:
newline[index] *= 2
newline[index + 1] = 0
newline = shift(newline)
return newline
def shift(array):
"""
Function that remove the zeros from array after it append them at the end
:param array: elements list
:return: new array of elements after the shift
"""
total_zeros_counter = 0
while True:
zeros_counter = 0
for index in range(len(array)):
if array[index] == 0:
del array[index]
zeros_counter += 1
break
total_zeros_counter += zeros_counter
if zeros_counter == 0:
break
for index in range(total_zeros_counter):
array.append(0)
return array
def rotate_cw_matrix(matrix):
"""
Rotate matrix clockwise
:param matrix: input matrix
:return: rotated matrix
"""
aux = zip(*matrix[::-1])
return [list(row) for row in aux]
def rotate_ccw_matrix(matrix):
"""
Rotate matrix counter clockwise
:param matrix: input matrix
:return: rotated matrix
"""
aux = zip(*matrix)[::-1]
return [list(row) for row in aux]
class TwentyFortyEight:
"""
Class to run the game logic.
"""
def __init__(self, grid_height, grid_width):
self._height = grid_height
self._width = grid_width
self._grid = None
self.reset()
def reset(self):
"""
Reset the game so the _grid is empty except for two
initial tiles.
"""
self._grid = [[0] * self._width for _ in range(self._height)]
for row in range(self._height):
for col in range(self._width):
self._grid[row][col] = 0
self.new_tile()
self.new_tile()
def __str__(self):
"""
Return a string representation of the _grid for debugging.
"""
result = "["
for row in range(self._height):
if row == 0:
result += str(self._grid[row]) + "\n"
elif row == self._height - 1:
result += " " + str(self._grid[row]) + "]"
else:
result += " " + str(self._grid[row]) + "\n"
return result
def get_grid_height(self):
"""
Get the _height of the board.
"""
return self._height
def get_grid_width(self):
"""
Get the _width of the board.
"""
return self._width
def move(self, direction):
"""
Move all tiles in the given direction and add a new tile if any
tiles moved.
:param direction: direction of the move over the _grid
"""
initial_grid = list(self._grid)
if direction == UP:
rotated_grid = rotate_ccw_matrix(self._grid)
rotated_grid = [merge(row) for row in rotated_grid]
self._grid = rotate_cw_matrix(rotated_grid)
elif direction == DOWN:
rotated_grid = rotate_cw_matrix(self._grid)
rotated_grid = [merge(row) for row in rotated_grid]
self._grid = rotate_ccw_matrix(rotated_grid)
elif direction == LEFT:
self._grid = [merge(row) for row in self._grid]
elif direction == RIGHT:
self._grid = [merge(row[::-1])[::-1] for row in self._grid]
if initial_grid != self._grid:
self.new_tile()
def new_tile(self):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
if not self.is_grid_full():
random_num = random.randint(0, 10)
new_tile_value = 4 if random_num > 9 else 2
while True:
rand_column_idx = random.randrange(0, self._width)
rand_row_idx = random.randrange(0, self._height)
if self.get_tile(rand_row_idx, rand_column_idx) == 0:
self.set_tile(rand_row_idx, rand_column_idx, new_tile_value)
break
def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
:param value: tile value
:param col: column index
:param row: row index
"""
self._grid[row][col] = value
def get_tile(self, row, col):
"""
Return the value of the tile at position row, col.
:param col: column index
:param row: row index
"""
return self._grid[row][col]
def is_grid_full(self):
"""
Return if the grid has any empty (0) tile
"""
for row in range(self._height):
for col in range(self._width):
if self._grid[row][col] == 0:
return False
return True
# game = TwentyFortyEight(4, 4)
# print game
#
# print "\n\nUP"
# game.move(UP)
# print game
#
# print "\n\nDOWN"
# game.move(DOWN)
# print game
#
# print "\n\nRIGHT"
# game.move(RIGHT)
# print game
#
# print "\n\nLEFT"
# game.move(LEFT)
# print game
#
# poc_2048_gui.run_gui(TwentyFortyEight(4, 4)) |
a063a9933d3e40961211c64dbf4a7497a8feb10d | ThiagoMMonteiro/teste_vcx | /tests.py | 3,906 | 3.640625 | 4 | import queue
import stack
import unittest
#========================================
#------------ queue.py ------------------
#========================================
class Test_Class_Node_queue(unittest.TestCase):
def test__init__(self):
n1 = queue.Node(5)
self.assertEqual(n1.data, 5)
self.assertEqual(n1.next_node, None)
n2 = queue.Node("Thiago")
self.assertEqual(n2.data, "Thiago")
self.assertEqual(n2.next_node, None)
class Test_Class_Queue(unittest.TestCase):
def test__init__(self):
q = queue.Queue()
self.assertIsInstance(q, queue.Queue)
self.assertEqual(q.first, None)
self.assertEqual(q.last, None)
def test_add(self):
q = queue.Queue()
q.add(1)
self.assertEqual(str(q.first), '1 < None')
self.assertEqual(str(q.last), '1 < None')
q.add(2)
self.assertEqual(str(q.first), '1 < 2 < None')
self.assertEqual(str(q.last), '2 < None')
q.add("Thiago")
self.assertEqual(str(q.first), '1 < 2 < Thiago < None')
self.assertEqual(str(q.last), 'Thiago < None')
def test_rem(self):
q = queue.Queue()
for i in range (4):
q.add(i)
# '0 < 1 < 2 < 3 < None'
q.rem()
self.assertEqual(str(q.first), '1 < 2 < 3 < None')
self.assertEqual(str(q.last), '3 < None')
q.rem()
self.assertEqual(str(q.first), '2 < 3 < None')
self.assertEqual(str(q.last), '3 < None')
q.rem()
self.assertEqual(str(q.first), '3 < None')
self.assertEqual(str(q.last), '3 < None')
q.rem()
self.assertEqual(str(q.first), 'None')
self.assertEqual(str(q.last), 'None')
q.rem()
self.assertEqual(str(q.first), 'None')
self.assertEqual(str(q.last), 'None')
def test_is_empty(self):
q = queue.Queue()
self.assertEqual(q.is_empty(), True)
q.add(1)
self.assertEqual(q.is_empty(), False)
q.rem()
self.assertEqual(q.is_empty(), True)
class Test_Class_Person(unittest.TestCase):
def test__init__(self):
p = queue.Person("James", 50)
self.assertIsInstance(p, queue.Person)
self.assertEqual(p.name, "James")
self.assertEqual(p.age, 50)
#========================================
#------------ stack.py ------------------
#========================================
class Test_Class_Node_stack(unittest.TestCase):
def test__init__(self):
n1 = stack.Node(5)
self.assertEqual(n1.data, 5)
self.assertEqual(n1.next_node, None)
n2 = stack.Node("Thiago")
self.assertEqual(n2.data, "Thiago")
self.assertEqual(n2.next_node, None)
class Test_Class_Stack(unittest.TestCase):
def test__init__(self):
s = stack.Stack()
self.assertIsInstance(s, stack.Stack)
self.assertEqual(s.last, None)
def test_add(self):
s = stack.Stack()
s.add(1)
self.assertEqual(str(s.last), '1|')
s.add(2)
self.assertEqual(str(s.last), '2 < 1|')
s.add("Thiago")
self.assertEqual(str(s.last), 'Thiago < 2 < 1|')
def test_rem(self):
s = stack.Stack()
for i in range (4):
s.add(i)
# '3 < 2 < 1 < 0|'
s.rem()
self.assertEqual(str(s.last), '2 < 1 < 0|')
s.rem()
self.assertEqual(str(s.last), '1 < 0|')
s.rem()
self.assertEqual(str(s.last), '0|')
s.rem()
self.assertEqual(str(s.last), 'None')
s.rem()
self.assertEqual(str(s.last), 'None')
def test_is_empty(self):
s = stack.Stack()
self.assertEqual(s.is_empty(), True)
s.add(1)
self.assertEqual(s.is_empty(), False)
s.rem()
self.assertEqual(s.is_empty(), True)
if __name__ == '__main__':
unittest.main() |
d08535076ba3497aa243669b11c9855cc296626b | harshithreddyr/Company- | /home.py | 1,058 | 3.78125 | 4 | from company import Employee,Supervisor
print("welcome to company")
while True:
print("\n \n what would you like to see:\n1.salary\n2.disp_details\n3.check\n4.calc_tax\n5.Exit")
choice=int(input("enter your choice: "))
print(choice)
sup_id=[12,13,14,15,16,17]
emp_name=raw_input("enter the name: ")
emp_id=int(input("enter the id: "))
emp_age=int(input("enter the age: "))
emp_salary=int(input("enter the salary: "))
if emp_id in sup_id:
sup=Supervisor(emp_name,emp_id,emp_age,emp_salary)
else:
emp=Employee(emp_name ,emp_id,emp_age,emp_salary)
if choice==1:
months=int(input("enter number of months: "))
if emp_id in sup_id:
tot_salary=sup.salary(months)
print(tot_salary)
else:
tot_salary=emp.salary(months)
print(tot_salary)
elif choice==2:
if emp_id in sup_id:
sup.disp_details()
else:
emp.disp_details()
elif choice==3:
if emp_id in sup_id:
sup.check()
else:
emp.check()
elif choice==4:
if emp_id in sup_id:
sup.calc_tax()
else:
emp.calc_tax()
else:
break
|
79144aad681947a99d09b0ede9462f9d6e7f8232 | abhaysinh/Data-Camp | /Data Science for Everyone Track/09-Data Manipulation with Pandas/04- Creating and Visualizing DataFrames/06-Removing missing values.py | 782 | 4.4375 | 4 | '''
Removing missing values
Now that you know there are some missing values in your DataFrame, you have a few options to deal with them. One way is to remove them from the dataset completely. In this exercise, you'll remove missing values by removing all rows that contain missing values.
pandas has been imported as pd and avocados_2016 is available.
Instructions
100 XP
Remove the rows of avocados_2016 that contain missing values and store the remaining rows in avocados_complete.
Verify that all missing values have been removed from avocados_complete. Calculate each columns has any NAs, and print.
'''
# Remove rows with missing values
avocados_complete = avocados_2016.dropna()
# Check if any columns contain missing values
print(avocados_complete.isna().any()) |
d29ce00b99e86afa13fd1ee07124d5b5e401cf25 | Aasthaengg/IBMdataset | /Python_codes/p03852/s828525601.py | 146 | 3.828125 | 4 | c = input()
if ord(c) == 97 or ord(c) == 101 or ord(c) == 105 or ord(c) == 111 or ord(c) == 117:
print("vowel")
else:
print("consonant") |
d324a1e5851f787a636e9aa38d92b075c0f99208 | nikhil33333/python | /multiply.py | 123 | 4.03125 | 4 | def multiply_list(items):
i = 1
for x in items:
i *= x
return i
print(multiply_list([8,2,3,-1,7])) |
a862b366435a258da975ea281cb5956d21fc7522 | enkhtuvshinj/Facial-keypoints | /models.py | 3,149 | 3.625 | 4 | ## TODO: define the convolutional neural network architecture
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## it's suggested that you make this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
## After each convolutional layer, output size = (W-F)/S+1
# K - out_channels : the number of filters in the convolutional layer
# F - kernel_size
# S - the stride of the convolution (default=1)
# P - the padding
# W - the width/height (square) of the previous layer
# Every layer = Conv2d + Relu + Maxpool
# Assume that input size decreases by two times after maxpool
# input size = 224 x 224
# output size = (W-F)/S +1 = (224-5)/1 +1 = 220 x 220
self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 32, kernel_size = 5)
# input size = 110 x 110
# output size = (W-F)/S+1 = (110-3)/1+1 = 108
self.conv2 = nn.Conv2d(32, 64, 3)
# input size = 54 x 54
# output size = (W-F)/S+1 = (108-3)/1+1 = 52
self.conv3 = nn.Conv2d(64, 128, 3)
# input size = 26 x 26
# output size = (W-F)/S+1 = (26-3)/1+1 = 12
self.conv4 = nn.Conv2d(128, 256, 3)
# input size = 6 x 6
# output size = (W-F)/S+1 = (6-1)/1+1 = 6
self.conv5 = nn.Conv2d(256, 512, 1)
# maxpool layer
# pool with kernel_size=2, stride=2
# output size = (input size)/2
self.pool = nn.MaxPool2d(2, 2)
# Fully-connected (linear) layers
self.fc1 = nn.Linear(512*6*6, 1024)
self.fc2 = nn.Linear(1024, 512)
self.fc3 = nn.Linear(512, 68*2)
# Dropout
self.dropout = nn.Dropout(p=0.3)
def forward(self, x):
## TODO: Define the feedforward behavior of this model
## x is the input image and, as an example, here you may choose to include a pool/conv step:
## x = self.pool(F.relu(self.conv1(x)))
# 5 layers = conv + relu + pool
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = self.pool(F.relu(self.conv4(x)))
x = self.pool(F.relu(self.conv5(x)))
# Flatten = 512*6*6
x = x.view(x.size(0), -1)
# Fully-connected layer
x = F.relu(self.fc1(x))
# Dropout with 0.3
x = self.dropout(x)
# Fully-connected layer
x = F.relu(self.fc2(x))
# Dropout with 0.3
x = self.dropout(x)
# Fully-connected layer with output 136
x = self.fc3(x)
# final output
return x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.