blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
5eba380e4a6bae72ac7ad35d3670ca36a4fa517d | fabriciocovalesci/ListOfBrazilPythonExercises | /SequentialStructure/number_2.py | 348 | 4.34375 | 4 | """
[PT]
2. Faça um Programa que peça um número e então mostre a mensagem "O número informado foi [número]".
[EN]
2. Make a Program that asks for a number and then displays the message "The number entered was [number]".
"""
def enternumber() -> str:
number = input('\nEnter a number: ')
return f'\nThe number entered was {number}'
|
f43c0ca9c0eea197c4afe74656923bf5af674c2c | Faith-muroa/pre-bootcamp-coding-challenges | /task9.py | 205 | 3.953125 | 4 | multiples = []
b = 1
while b < 1000:
if b % 3 == 0 or b % 5 == 0:
multiples.append(b)
print(b)
b = b + 1
print(multiples)
sum = 0
for i in multiples:
sum = sum + i
print(sum)
|
a18ede81f8de3ec56fc6c75ad6a2758f719e4dc6 | Maheshwari2604/Competitive-Programming-linkedlist-and-Stack- | /linkdedlist/detect_loop.py | 892 | 3.984375 | 4 | class node:
def __init__(self, data):
self.data = data
self.next = None
class linkedlist:
def __init__(self):
self.head = None
def push(self, new_node):
new_node = node(new_node)
new_node.next = self.head
self.head = new_node
def detect_loop(self):
slow_p = self.head
fast_p = self.head
while(slow_p and fast_p and fast_p.next):
slow_p = slow_p.next
fast_p = fast_p.next.next
print(slow_p)
print(fast_p)
if slow_p == fast_p:
print('found')
return
else:
print("not found")
if __name__ == "__main__":
llist = linkedlist()
llist.push(2)
llist.push(9)
llist.push(3)
llist.push(9 )
llist.push(9)
llist.detect_loop()
|
b68d3a8c88a28fa0b2e14545f43fb2a1a7831886 | kangmin1012/Algorithm | /2020.01.13(MON)/2037_SMS.py | 2,949 | 3.5625 | 4 | button, rest = map(int,input().split()) # button = 입력 시간 , rest = 같은 숫자 연속입력 시 기다리는 시간
result = 0
check = 0
text = list(input())
al_dic = {
2 : ['A', 'B', 'C'],
3 : ['D', 'E', 'F'],
4 : ['G', 'H', 'I'],
5 : ['J', 'K', 'L'],
6 : ['M', 'N', 'O'],
7 : ['P', 'Q', 'R', 'S'],
8 : ['T', 'U', 'V'],
9 : ['W', 'X', 'Y', 'Z']}
# al_dic = {'A' : 1,'B' : 2, 'C' : 3 ,
# 'D' : 1, 'E' : 2, 'F' : 3,
# 'G' : 1 , 'H' : 2, 'I' : 3,
# 'J' : 1, 'K' : 2, 'L' : 3,
# 'M' : 1, 'N' : 2, 'O' : 3,
# 'P' : 1, 'Q' : 2, 'R' : 3, 'S' : 4,
# 'T' : 1, 'U' : 2, 'V' : 3,
# 'W' : 1, 'X' : 2, 'Y' : 3, 'Z' :4}
# for i in range(len(text)) :
# # A ~ C
# if text[i] >= 'A' and text[i] <= 'C' :
# result += button * al_dic[text[i]]
# if check == 1 :
# result += rest
# check = 1
#
# # D ~ F
# elif text[i] >= 'D' and text[i] <= 'F' :
# result += button * al_dic[text[i]]
# if check == 2 :
# result += rest
# check = 2
#
# # G ~ I
# elif text[i] >= 'G' and text[i] <= 'I' :
# result += button * al_dic[text[i]]
# if check == 3 :
# result += rest
# check = 3
#
# # J ~ L
# elif text[i] >= 'J' and text[i] <= 'L' :
# result += button * al_dic[text[i]]
# if check == 4 :
# result += rest
# check = 4
#
# # M ~ O
# elif text[i] >= 'M' and text[i] <= 'O' :
# result += button * al_dic[text[i]]
# if check == 5 :
# result += rest
# check = 5
#
# # P ~ S
# elif text[i] >= 'P' and text[i] <= 'S' :
# result += button * al_dic[text[i]]
# if check == 6 :
# result += rest
# check = 6
#
# # T ~ V
# elif text[i] >= 'T' and text[i] <= 'V' :
# result += button * al_dic[text[i]]
# if check == 7 :
# result += rest
# check = 7
#
# # W ~ Z
# elif text[i] >= 'W' and text[i] <= 'Z' :
# result += button * al_dic[text[i]]
# if check == 8 :
# result += rest
# check = 8
#
# else :
# result += button
# check = 0
for alpha in text :
count = [number for number, chars in al_dic.items() if alpha in chars] # 해당 문자가 있는 키 값 전달
if not count : # 공백일 경우
result += button
check = 0
else :
# 문자가 위치한 인덱스를 찾아 +1을 하면 그것이 곧 연속적으로 입력해야하는 횟수가 된다
t = [c for c in range(len(al_dic[count[0]])) if alpha == al_dic[count[0]][c]]
if check == count : # 이전 문자와 비교
result += rest + button*(t[0]+1)
else :
result += button*(t[0]+1)
check = count
print(result) |
bdc085c28c2ad50438bf7ac2a70ee0d8da4e4076 | rohaneden10/luminar_programs | /flow controls/decision/secondlargestnumber.py | 117 | 3.828125 | 4 | a=int(input("enter 1st no"))
b=int(input("enter 2nd no"))
c=int(input("enter 3rd number"))
if(a>b)&(a<c)
print(a) |
d65e8a7297b6e931d5fa9c219feb333cb046d9c8 | Niteesh3110/Algorithms | /selectionsort.py | 434 | 4.03125 | 4 | import random
# the function
def selection_sort(arr):
unsorted_arr = arr
sorted_arr = []
minimum_value = 0
for i in range(len(arr)):
minimum_value = min(arr)
sorted_arr.append(minimum_value)
arr.remove(minimum_value)
print(sorted_arr)
return sorted_arr
# array
arr = [-1,8,3,4,-5,9]
# Creating random number
# for i in range(1,10):
# random_number = random.randrange(1,20)
# arr.append(random_number)
selection_sort(arr) |
4bec55dcc2364dda99201e15efff14455077bdb8 | epasseto/pyprog | /UdacityProgrammingLanguage/Course/src/Final_LogicPuzzle.py | 2,333 | 3.734375 | 4 | #! /usr/bin/python
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="epasseto"
__date__ ="$28/05/2012 15:03:33$"
"""
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid,
one is Wilkes and the other is Hamming. ###PROBLEM
4. The writer is not Minsky.
5. Neither Knuth nor the person who bought the tablet is the manager. ###PROBLEM
6. Knuth arrived the day after Simon.
7. The person who arrived on Thursday is not the designer.
8. The person who arrived on Friday didn't buy the tablet.
9. The designer didn't buy the droid.
10. Knuth arrived the day after the manager.
11. Of the person who bought the laptop and Wilkes,
one arrived on Monday and the other is the writer. ##PROBLEM
12. Either the person who bought the iphone or the person who bought the tablet
arrived on Tuesday. ##PROBLEM
You will write the function logic_puzzle(), which should return a list of the
names of the people in the order in which they arrive. For example, if they
happen to arrive in alphabetical order, Hamming on Monday, Knuth on Tuesday, etc.,
then you would return: ['Hamming', 'Knuth', 'Minsky', 'Simon', 'Wilkes']
(You can assume that the days mentioned are all in the same week.)
"""
import itertools
def dayafter(d1,d2): #dayafter(Knuth,Simon) == True
return d1-d2 == 1
def logic_puzzle():
"Return a list of the names of the people, in the order they arrive."
days = Monday, Tuesday, Wednesday, Thursday, Friday = [1, 2, 3, 4, 5]
orderings = list(itertools.permutations(days))
#print 'days:', days
#print 'orderings:', orderings
return next([Hamming, Knuth, Minsky, Simon, Wilkes]
for (Hamming, Knuth, Minsky, Simon, Wilkes) in orderings
if dayafter(Knuth, Simon) #6
for (manager, writer, designer, programmer, undefined) in orderings
if programmer is not Wilkes #2
if designer is not Thursday#7
if writer is not Minsky #4
for (laptop, droid, droid, tablet, iphone) in orderings
if laptop is Wednesday#1
if tablet is Friday#8
if droid is not designer #9
)
print logic_puzzle()
|
5af62c56e4e41583bd35b85ff28f05d050caefc7 | gmoore803/Schedule-Planner-cs | /semester project.py | 2,930 | 3.765625 | 4 | print("-"*110)
print(' Jacksonville State University ')
print(' Fall Semester 2019 ')
print(' Grayson Moore ')
print(' CS230 ')
print('-'*110)
print(' Course Enrollment Simulation ')
print(' '*700)
print('-'*110)
print('----------------------------------- Jacksonville State University --------------------------------------------')
class courses:
def __init__(self,name,number):
self.name = name
self.number = number
def cname(self):
return '{} {}'.format(self.name,self.number)
crs_1 = courses('Math','100')
crs_2 = courses('EGH','101')
crs_3 = courses('Geo','104')
name,name2,stunumber = input('First name:'), input('last name:'), input('Student Number:')
print('Hi welcome to JSU schedule planner ' + name , name2 )
print('Majors offered')
x = "Computer Science","Business","Mathmatics","Nursing","Engineering","Education"
for e in x:
print(e)
print("\n")
print('Please enter the following information below ')
print("\n")
maj = input('Select major from offered Section: ')
print("\n")
print("\n")
print("---------------------Course selection--------------------")
print('EGH 101')
print('MS 101')
print('Math 131')
print('Math 142')
print('Math 105')
print('Geo 109')
print('Cell 107')
print('Lab 110')
print('FA 1190')
print('SPH 1170')
print('SCI 1201')
print('EG 201')
print('STATS 221')
print('BS 901')
print('FCS 301')
print('SCI 2101')
print("\n")
print("\n")
loops = int(input("How many classes will you be enrolling in this semester:"))
inputs = []
for x in range(loops):
inputs.append(input("Please enter desired course: "))
print("\n")
print("Thank you for completing your 2020 spring schedule")
print("You can view a text copy, GM9508.txt is the name of the file.")
with open('GM9508.txt', 'w') as f:
f.write(" Jacksonville State University")
f.write("\n")
f.write(" CS-230")
f.write("\n")
f.write(" Grayson Moore")
f.write("\n")
f.write("-"*150)
f.write("\n")
f.write("\n")
f.write("\n")
f.write(name)
f.write("\n")
f.write(maj)
f.write("\n")
f.write(stunumber)
f.write("\n")
f.write("\n")
for item in inputs:
f.write("%s\n" % item)
f.write("\n")
f.write("\n"*5)
f.write("\n")
f.write("-"*150)
f.write("\n")
f.write("-"*150)
f.write("\n")
f.write("Thank you for using my schedule planner simulation.")
f.close()
|
5828947810a17b820f6182c139cc1e9715a5e19a | sujilnt/UdacityCoursework | /Task0.py | 1,072 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# <h4>Task 0 </h4>
# <br/>
# <p><b>Print this message</b></p>
# <ol>
# <li>First record of texts, <b>incoming number</b> texts <b>answering number </b> at time <b>time</b></li>
# <li>Last record of calls, <b>incoming number</b> calls <b>answering number</b> at time <b>time.</b></li>
# </ol>
# In[2]:
import csv
# In[3]:
def read_csvFiles(filename, arguments):
with open(filename,'r') as f:
reader = csv.reader(f) # time O(n)
data = list(reader) # time O(n)
index = 0 if arguments == "first" else len(data)-1 # time O(1) or O(2)
return data[index] #time O(1)
# In[4]:
textsData = read_csvFiles("texts.csv", "first") # time O(2n)
callData= read_csvFiles("calls.csv", "last")[0] # time O(2n)
print("First record of texts, "+ textsData[0] + " texts " + textsData[1] + " at time " + textsData[2] + ".")# time O(4)
print("First record of calls, "+ callData[0] + " calls " + callData[1] + " at time " + callData[2] + ", lasting " + callData[3] + " seconds")# time O(4)
|
e614f9666dff56f2ad37f1bdda37e4d5cebce424 | vicuartas230/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 309 | 4.09375 | 4 | #!/usr/bin/python3
""" This program defines a function read_file """
def read_file(filename=""):
""" This function reads a text file (UTF8) and prints it to stdout """
with open(filename, 'r', encoding='utf-8') as new:
reading = new.read()
print(reading, end='')
new.close()
|
078431e1485665658fa4e04d530853ddb8670028 | chandrakala199/codeketa | /queue.py | 826 | 4.25 | 4 | print("queue implementation")
queue=[]
while True:
print("what operation would you like to perform?\n 1.enqueue 2.dequeue 3.size 4.empty 5.exit")
c=int(input())
if c==1:
print("Enter the element to be inserted:")
l=input()
queue.append(l)
print(" the element in the queue are",)
elif c==2:
if queue ==[]:
print("the queue is empty")
else:
queue.pop(0)
print("the element in the queue are",queue)
elif c==3:
print("the size of the queue is",len(queue))
print(" the element in the stack are",queue)
elif c==4:
if queue ==[1]:
print("the element is empty")
else:
print("the element in the queue are",queue)
elif c==5:
print("exit")
break
|
90db0739d7c33ffc775a4238975a127f1c702e64 | yazdejesus/FirstLessons-Python | /CursoEmVideo/070 - EstatisticaCompra.py | 899 | 3.78125 | 4 | #ler nome e preço de vários produtos. Perguntar se vai continuar
#total gasto na compra, nr de produtos acimia de 1000 e nome do mais barato
total = bem_caros = 0
compra = mais_barato = 0
while True:
nome = input("Introduza o nome do produto: ")
preco = float(input("Introduza o preco do produto: MZN_"))
continuar = input("\nDeseja continuar (y/n)? ").upper()
total += 1
compra += preco
if preco > 1000:
bem_caros += 1
if total == 1:
mais_barato = preco
nome_mais_barato = nome
print(nome_mais_barato, mais_barato)
else:
if mais_barato > preco:
mais_barato = preco
nome_mais_barato = nome
print(nome_mais_barato,mais_barato)
if continuar == "N":
break
print(f"\n\nCompra encerrada, vide o recibo:\nTotal de itens: {total}\nCusto Total: {compra:.2f}\nProdutos acima de 1000 MZN: {bem_caros}\nProduto mais barato: {nome_mais_barato} (custo {mais_barato})")
|
a8579e6d0c571b966f9e86e688d1684634b23178 | mateusfagundes/Exercicios-Python | /Estudos intermediários/Controle/while1.py | 636 | 3.96875 | 4 | x = 10
while x: # Conta do 10 ao 1 depois para o laço
print(x)
x -= 1
print('Fim')
x = 0
while x != -1: # Enquato não for digitado -1 o laço não para de rodar
x = float(input('Informe o numero ou -1 para sair: '))
print('Fim')
total = 0
qtde = 0
nota = 0
while nota != -1: # Soma as notas e depois divide quado digitado -1
nota = float(input('Informe a nota ou -1 para sair: '))
if nota != -1:
qtde += 1
total += nota
print(f'A média da turma é: {total / qtde}') # o print(f'uma string {variavel}') irá juntar o valor da variável após o texto uma string.
|
f315d5d12d89b03256a89395540ab34a3155ff3f | Crimson-Jacket/Ciphers | /letnumCipher.py | 972 | 4.09375 | 4 | def ltnc(text):
"""
Description:
A cipher that converts letters to its corresponding number (position in alphabet).
Doctests:
>>> ltnc("this is a test")
'20 8 9 19 9 19 1 20 5 19 20'
"""
return " ".join(format(ord(x) - 96, "d") if 97 <= ord(x) <= 122 else x for x in text.lower())
def ntlc(nums):
"""
Description:
A cipher converts valid numbers to its corresponding letter.
Doctests:
>>> ntlc()
"""
text = ""
last_not_space = True #Gets rid of extra spaces.
for x in nums.split(" "):
try:
if 0 < int(x) < 26:
text += str(chr(int(x) + 96))
last_not_space = True
else:
text += str(x)
except:
if last_not_space and x == "":
text += " "
last_not_space = False
else:
text += str(x)
last_not_space = True
return text |
d5397d1cda626f8f6bb194023f3ccd61504180e5 | Connor-Cahill/madlibs | /madlibs.py | 3,050 | 4.46875 | 4 | # Need to find set of 2-3 stories
#store stories in a list
#create function that gets inputs from user (NEED: Verb, Noun, Adjective, etc.)
#choose random index from list to pick story
##Format the list to inject the user_inputted values into the necessary spots
# make sure user input can only be letters
import random # imported for random.choice()
stories = ["Last summer, my mom and dad took me and {person} on a trip to {location}. The weather there is very {adj}! Northern {location} has many {plural_noun}, and they make {adj2} {plural_noun2} there. Many people also go to {location} to {verb} or see {noun1}. The people that live there love to eat {food} and are very proud of their big {noun2}.",
"Hi! This is {name}, speaking to you from the broadcasting {noun} at the {adj} forum. In case you {verb} in late, the score between the Los Angeles {noun2} and the Boston {noun3} is squeker, 141 to {number}. This has been the most {adj2} game these {noun4} eyes have seen in years. First, one team scores a {noun5}, then the other team comes right back. What an interesting {noun6} to watch!",]
story = ''
def selectStory(list):
"""Randomly selects one of the stories from the stories list and returns it as a variable """
story = random.choice(list)
return story
def madlibs():
"""Depending on story returned by selectStory() will ask user series of questions to fill out story """
print('Please answer the following to fill in blanks of the mad libs story!')
selectStory(stories)
if story == stories[0]:
person = str(input("Enter a person: "))
location = str(input('Enter a location: '))
adj = str(input('Enter in adjective: '))
plural_noun = str(input('Enter a plural noun: '))
adj2 = str(input('Enter another adjective: '))
plural_noun2 = str(input('Enter another plural noun: '))
verb = str(input('Enter a verb: '))
noun1 = str(input('Enter a noun: '))
food = str(input('Enter a food item: '))
noun2 = str(input('Enter another noun: '))
return print(stories[0].format(person = person, location = location, adj = adj, plural_noun = plural_noun,
adj2 = adj2, plural_noun2 = plural_noun2, verb = verb, noun1 = noun1, food = food, noun2 = noun2))
else:
name = str(input("Enter a person's name: "))
noun = str(input('Enter a noun: '))
adj = str(input('Enter a adjective: '))
verb = str(input('Enter a verb: '))
noun2 = str(input('Enter another noun: '))
noun3 = str(input('Enter another noun: '))
number = str(input('Enter a number: '))
adj2 = str(input('Enter another adjective: '))
noun4 = str(input('Enter another noun: '))
noun5 = str(input('Enter another noun: '))
noun6 = str(input('Enter another noun: '))
return print(stories[1].format(name = name, noun = noun, adj = adj, verb = verb, noun2 = noun2, noun3 = noun3,
number = number, adj2 = adj2, noun4 = noun4, noun5 = noun5, noun6 = noun6))
madlibs()
|
de2d68ad14d865306facd5e45c0bf4108a2e2ec0 | dale-nelson/IFT-101-Lab4 | /Lab04/Lab04P3.py | 811 | 4.09375 | 4 | def main():
print("This program will calculate the addition of natural numbers in sequence.")
userInput = validLoop()
posCheck = isPos(userInput)
print("The sum of all the natural numbers up to {0} is {1}".format(posCheck,naturalNumAdd(posCheck)))
return
def naturalNumAdd(i):
if i <= 1:
return i
if naturalNumAdd:
return i + naturalNumAdd(i - 1)
def validCheck():
try:
return int(float(input()))
except ValueError:
print("That value is not a number. Please try again.")
def validLoop():
inp = validCheck()
while inp is None:
inp = validCheck()
else:
return inp
def isPos(i):
while i < 0:
print("Negative numbers cannot be accepted. Please try again.")
i = validLoop()
else:
return i
main() |
052b40c6de09c05f01efeb115b4a1ae964836564 | bmk316/daniel_liang_python_solutions | /8.6.py | 321 | 3.953125 | 4 | def count(str1):
c = 0
for i in range(len(str1)):
if str1[i].isalpha() > 0:
c += 1
return c
def main():
string = input("Enter your string to be counted:").lower()
result = count(string)
print("The numbers of letters in the string is:", count(string))
main() |
ebb51b090fa28230fb6975c393d125ff8323b979 | Toby-Tan/tanjiahao | /python_ck/class/class_10day/class_10_global.py | 476 | 3.6875 | 4 | # 多线程全局变量
# 如果多个线程同时对一个全局变量操作,会出现资源竞争问题,从而会导致数据结果错误
import threading
import time
a = 100
def fun1():
global a
for i in range(1000000):
a += 1
print(a)
def fun2():
global a
for i in range(1000000):
a += 1
print(a)
t1 = threading.Thread(target=fun1)
t2 = threading.Thread(target=fun2)
t1.start()
t2.start()
t1.join()
t2.join()
print(a)
|
a4ac18fc264f6ef01ef8686200b23bb567cc5475 | yodeng/sw-algorithms | /python/binary_tree/symmetric_tree.py | 1,789 | 3.75 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: swensun
@github:https://github.com/yunshuipiao
@software: python
@file: symmetric_tree.py
@desc: 判断对称树
@hint: 比较对称位置,递归和非递归。也可以根据前面二叉树反转,来判断两棵树是不是一样。
"""
from binary_tree import BinaryTree
# 递归
def symmetric_tree(root):
if root is None:
return True
return is_symmetric_tree(root.left_child, root.right_child)
def is_symmetric_tree(left_child, right_child):
if left_child is None or right_child is None: # 有节点为空时判断
return left_child == right_child
return left_child.data == right_child.data and is_symmetric_tree(left_child.left_child, right_child.right_child) \
and is_symmetric_tree(left_child.right_child, right_child.left_child)
#非递归:参考前序遍历的思路,将需要对比的节点入栈比较。需要注意的是:都为空的情况
def symmetric_tree_two(root):
if root is None:
return True
node_list = []
node_list.append(root.left_child)
node_list.append(root.right_child)
while len(node_list) != 0:
node_one = node_list.pop()
node_two = node_list.pop()
if node_one == node_two is None:
continue
if node_one is None or node_two is None:
return False
if node_one.data != node_two.data:
return False
node_list.append(node_one.left_child)
node_list.append(node_two.right_child)
node_list.append(node_one.right_child)
node_list.append(node_two.left_child)
return True
if __name__ == '__main__':
tree = BinaryTree()
tree.create_symmetric_tree()
result = symmetric_tree_two(tree.root)
print(result)
|
bb2eee274ad8629f1c7f9a31c248b46a90f1e0ba | AmritaDeb/Automation_Repo | /PythonBasics/Prog_18_12_27/ReversedItemInListComprehension.py | 236 | 3.796875 | 4 | l1=['hi','hello','bye']
l2=[]
for i in range(len(l1)):
l2.append(l1[i][::-1])
print(l2)
revList=[l1[i][::-1] for i in range(len(l1))]
print(revList)
s="amrita"
s1=list(s)
print(s1)
# revStr=[s1[i][::-1] for i in s]
# print(revStr) |
88d21333e4a5eeeef9ef0def2f4c8f0c29081084 | devendra3583/Python | /D_Day10/10/2_class.py | 127 | 3.625 | 4 | class A:
c=10
def __init__(self,x,y):
self.x = x
self.y=y
def dis(self,x,y):
print x+y+self.c
a = A(5,8)
a.dis(1,2)
|
6b3352029c5d37b52f15400738807ad7a35b6c64 | riprap/dailies | /python/day003easy.py | 1,348 | 4.21875 | 4 | """Welcome to cipher day!
write a program that can encrypt texts with an alphabetical caesar cipher. This cipher can ignore numbers, symbols, and whitespace.
for extra credit, add a "decrypt" function to your program!"""
def crypt(user_string, caesar_shift):
letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
string_length = len(user_string)
encrypted_string = str("")
count = 0
while (count<string_length):
letter_count = 0
while (letter_count<len(letters)):
if (user_string[count] == letters[letter_count]):
new_letter_index = letter_count + caesar_shift
new_letter = letters[new_letter_index]
break;
letter_count+=1
encrypted_string+=new_letter
count+=1
return encrypted_string
while True:
user_string = str(raw_input("\nEnter a string to be ciphered: ")).lower()
shift_amount = int(raw_input("Enter a shift amount for the cipher: "))
#encrypt that shit homie
encrypted_string = crypt(user_string, shift_amount)
print("This is your encrypted string: ",encrypted_string)
#this gets negative value of integer
shift_amount = "-" + str(shift_amount)
shift_amount = int(shift_amount)
#decrypts the string back
decrypted_string = crypt(encrypted_string, shift_amount)
print("This is your encrypted string decrypted", decrypted_string) |
553fd317e297a110c115f1e2a32169da73cd7ba9 | AHKerrigan/Think-Python | /example6_3.py | 386 | 4.0625 | 4 | """ This is a solution to an example from
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
License: http://creativecommons.org/licenses/by/4.0/
Chapter 6 Example 3:
As an exercise, write a function is_between(x, y, z) that returns True if x ≤ y ≤ z
or False otherwise.
"""
def is_between(x, y, z):
return x <= y <= z
print(is_between(1,2,3)) |
68f1c5a3a491eb32d7244561d5e4990282550313 | fhylinjr/Scratch_Python | /final project.py | 2,209 | 3.765625 | 4 | import random
def Pshootout():
print('Hello there!, Welcome to the Penalty Shootout Game!')
diffmode=int(input('Select difficulty mode, Enter 1 for easy mode and 2 for hard mode: '))
print('There are several directions to place your kick.')
print('They are represented as TL-TopLeft, ML-MiddleLeft, BL-BottomLeft, TM-TopMiddle, M-Middle, BM-BottomMiddle, TR-TopRight, MR-MiddleRight, BR-BottomRight')
print('As you select your spot the computer(goalie) would randomly guess a spot to attempt a save')
print('Goodluck!!!')
print()
scored=0
saved=0
for n in range(5):
playerOption=['TL','ML','BL','TM','M','BM','TR','MR','BR']
goalie=random.choices(playerOption,k=6)
shot=input('Select where you would like to shoot (TL, ML, BL, TM, M, BM, TR, MR or BR): ')
if playerOption.count(shot)==0:
print('You entered wrong key. You shot wide away from goal.')
saved+=1
if diffmode==1:
if playerOption.count(shot)!=0:
if goalie[0]==shot or goalie[1]==shot or goalie[2]==shot:
print('Goalie stopped your shot. Too Bad')
saved+=1
elif goalie[0]!=shot and goalie[1]!=shot and goalie[2]!=shot:
print('You scored! Nice Try!')
scored+=1
print('Your score is: ',scored,'-',saved)
if diffmode==2:
if playerOption.count(shot)!=0:
if goalie[0]==shot or goalie[1]==shot or goalie[2]==shot or goalie[3]==shot or goalie[4]==shot or goalie[5]==shot:
print('Goalie stopped your shot. Too Bad')
saved+=1
elif goalie[0]!=shot and goalie[1]!=shot and goalie[2]!=shot and goalie[3]!=shot and goalie[4]!=shot and goalie[5]!=shot:
print('You scored! Nice Try!')
scored+=1
print('Your score is: ',scored,'-',saved)
if scored>saved:
print('You won the shootout. Congrats!')
elif scored<saved:
print('You lost the shootout. Better luck')
|
dd8cccd0bbb8219504411f0ad8f4821da3d86faa | uli-rizki/mona | /mona.py | 193 | 3.515625 | 4 | #!/usr/bin/python
flag = True
while flag == True :
sentence = raw_input("User : ")
if sentence == "quit" :
exit()
else :
response = sentence.lower()
print "Mona :", response |
da7b5ced97d00c30b2cf6df1b83faa9dbcc1a64d | danielhamc/PythonInformationInfrastructure | /number_sum.py | 245 | 4.125 | 4 | # Daniel Ham
# Number Sum
num_list = []
while True:
num = input("Please enter a number or STOP: ")
if num.upper() == 'STOP':
break
num_list.append(int(num))
print("The total sum is", sum(num_list))
|
e0d49e0f4a3aee383900ad1e79aacbf9a4993032 | ash/amazing_python3 | /147-ternary2.py | 231 | 4.3125 | 4 | # Let's see another paradigm
# you can use with conditional
# statements
for i in range(1, 5):
# is i odd or even?
# oe = 'odd' if i % 2 else 'even'
print('odd') if i % 2 else print('even')
# print(f'{i} is {oe}')
|
3783d216789d7a76c90e140e4f261a93bd90bfff | vmirisas/Python_Lessons | /lesson7/part6/set.comprehensions.py | 648 | 3.859375 | 4 | my_set = {number for number in range(3)}
my_set1 = {number for number in range(10) if number % 2 == 0}
my_set2 = {number if number % 2 == 0 else number / 2 for number in range(10)}
"""
my_set3 = set()
for i in range(2):
for j in range(3):
my_set3.add(i,j)
"""
my_set3 = {(i, j) for i in range(2)
for j in range(3)}
"""
my_set3 = set()
for i in range(6):
if i%2==0:
for j in range(6,10):
if j%2 ==1:
my_set4.add(i,j)
"""
my_set4 = {(i, j) for i in range(6) if i % 2 == 0
for j in range(6, 10) if j % 2 == 1}
print(my_set)
print(my_set1)
print(my_set2)
print(my_set3)
print(my_set4)
|
95d801a6b9ed2faba40644ae2ade8998f61457c9 | nptit/checkio | /numbers_factory.py | 819 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
def checkio(data):
result = []
while data > 9:
is_found = False
for i in range(9, 1, -1):
if data % i == 0:
is_found = True
result.append(i)
data = data // i
break
if not is_found:
return 0
result.append(data)
return int(''.join([str(i) for i in sorted(result)]))
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(20) == 45, "1st example"
assert checkio(21) == 37, "2nd example"
assert checkio(17) == 0, "3rd example"
assert checkio(33) == 0, "4th example"
assert checkio(3125) == 55555, "5th example"
assert checkio(9973) == 0, "6th example"
|
3b36890ae8beddfda384d4d4348f091555e11d5a | tisTrashBoat/FrankPalafox | /Assign 3.py | 539 | 4.125 | 4 | grades=int(input("How many grades would you like to input?"))
grade_list= []
grade_average = 0
for i in range(grades):
print ("What was your grade?")
entered_vari=int(input())
grade_list.append(entered_vari)
grade_average = grade_average + entered_vari
print grade_list
a= grade_average
a = a/grades
print a
if a >=90:
print ("You have an A")
elif a>=80 and a<90:
print "You have a B"
elif a>=70 and a<80:
print "You have a C"
elif a>=60 and a<70:
print "You have a D"
else:
print "!!You Are Failing!!"
|
b030babafd64f76f06cd4944bf5ac4ea12dcd2c2 | NishaUSK/pythontraining | /ex8.py | 356 | 4.15625 | 4 | #using methods(join,split,replace)
pen = "Students have different types of pens to write"
print(" ".join(pen))
print("-------------------------------------")
print(" ".join(reversed(pen)))
print("-------------------------------------")
print(pen.split("e"))
print("-------------------------------------")
print(pen.replace("write","practice"))
|
dcff8ce33c9db3902be0bcdcb6cdb207d1af9562 | sds1994/Text-Documents-Repo | /Python/Divisors.py | 125 | 3.828125 | 4 | n = int(input('Enter any number : '))
list=[]
for i in range(1,n+1):
if(n%i == 0):
list.append(i)
print(list)
|
17a7b7787aa47f1fe4d8c269a41cf3c61cb12765 | tahsinalamin/leetcode_problems | /leetcode-my-solutions/404_sum_of_left_leaves.py | 688 | 3.640625 | 4 | """
Author: Sikder Tahsin Al Amin
Problem:
Find the sum of all left leaves in a given binary tree.
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
self.sum = 0
return self.helper(root,0)
def helper(self,root,flag):
if root== None:
return 0
if root.left == None and root.right == None and flag==1:
self.sum = self.sum + root.val
return self.sum
left = self.helper(root.left,1)
right = self.helper(root.right,0)
return self.sum
|
5023416228842b7fd6c7ec685b77c9b27082f67b | esl4m/python-design-patterns2 | /02_Command_Pattern/switch.py | 2,115 | 3.546875 | 4 | class Switch:
""" The INVOKER class"""
def __init__(self, flipUpCmd, flipDownCmd):
self.__flipUpCommand = flipUpCmd
self.__flipDownCommand = flipDownCmd
def flip_up(self):
self.__flipUpCommand.execute()
def flip_down(self):
self.__flipDownCommand.execute()
class Light:
"""The RECEIVER Class"""
def turn_on(self):
print("The light is on")
def turn_off(self):
print("The light is off")
class Command:
"""The Command Abstract class"""
def __init__(self):
pass
#Make changes
def execute(self):
#OVERRIDE
pass
class FlipUpCommand(Command):
"""The Command class for turning on the light"""
def __init__(self,light):
self.__light = light
def execute(self):
self.__light.turn_on()
class FlipDownCommand(Command):
"""The Command class for turning off the light"""
def __init__(self,light):
Command.__init__(self)
self.__light = light
def execute(self):
self.__light.turn_off()
class LightSwitch:
""" The Client Class"""
def __init__(self):
self.__lamp = Light()
self.__switchUp = FlipUpCommand(self.__lamp)
self.__switchDown = FlipDownCommand(self.__lamp)
self.__switch = Switch(self.__switchUp, self.__switchDown)
def switch(self, cmd):
cmd = cmd.strip().upper()
try:
if cmd == "ON":
self.__switch.flip_up()
elif cmd == "OFF":
self.__switch.flip_down()
else:
print("Argument \"ON\" or \"OFF\" is required.")
except ValueError:
print("Exception occurred")
# except Exception, msg:
# print("Exception occurred: %s" % msg)
# Execute if this file is run as a script and not imported as a module
if __name__ == "__main__":
lightSwitch = LightSwitch()
print("Switch ON test.")
lightSwitch.switch("ON")
print("Switch OFF test")
lightSwitch.switch("OFF")
print("Invalid Command test")
lightSwitch.switch("****")
|
22efdf4543362f81adb8010a40466ed3810629cd | algebra-det/Python | /DataStructures/Selection_Sort.py | 831 | 4.21875 | 4 | # In Bubble_Sort we consume to much cpu power and memeory and time because
# we have to iterate through every element upto last value and then iterate again
# upto last second value and so on
# In SELECTION SORTING, we take the max or min value from the list and then swap it with the first
# then second than so one which do not use such extensive cpu power or memory and time
A = [64, 25, 12, 22, 11, 65, 23, 27, 63, 85]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element with
# the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Driver code to test above
print("Sorted array")
print(A) |
86b5b7e68a3fc41223699d8350e7282d711a3c3f | krother/advanced_python | /error_handling/get_traceback.py | 644 | 3.53125 | 4 | """
Example:
Print the state of all variables when an Exception occurs.
"""
import sys, traceback
def print_exc():
tb = sys.exc_info()[2]
while tb.tb_next:
# jump through execution frames
tb = tb.tb_next
frame = tb.tb_frame
code = frame.f_code
print("Frame %s in %s at line %s"%\
(code.co_name,
code.co_filename,
frame.f_lineno))
# print local variables
for k, v in frame.f_locals.items():
print("%20s = %s"%(k,str(v)))
try:
a = 3
b = "Carrots"
c = a / 0
except ZeroDivisionError:
print_exc()
|
a5d557caf0ebc2d6fbcf935b768d883704e8be8f | mumarkhan999/python_practice_files | /Lists/13_using_lists_as_queue.py | 238 | 4.0625 | 4 | # using lists as queue
l1 = []
for i in range(1,11):
l1.insert(0, i)
print("Adding ",i)
print("After inserting values l1 is ", l1)
while len(l1) > 0:
print("Removing ", l1.pop())
print("After removing values l1 is ", l1)
|
a154ba1563502288d74e8633dd35f0675784208b | pruvi007/PBFT_Consensus | /shortestPath.py | 1,974 | 3.5625 | 4 |
from heapq import heappop, heappush, heapify
class shortestPath():
def __init__(self,graph,source,destination):
self.source = source
self.destination = destination
self.G = graph
self.X,self.Y,self.W = [],[],[]
self.edge = []
def getPath(self):
# heap contains element of the form -> [ distance,node ]
heap = [ [0,self.source] ]
heapify(heap)
adj = self.G.adjList
INF = 10**10
dist = [ INF for i in range(self.G.N+1) ]
dist[self.source] = 0
parent = [-1 for i in range(self.G.N+1)]
while len(heap)>0:
x = heappop(heap)
node, d = x[1], x[0]
# update the distances from popped node (min)
v = adj[node]
for i in range(len(v)):
cur = v[i][0]
wt = v[i][1]
if dist[cur] > dist[node]+wt:
dist[cur] = dist[node]+wt
parent[cur] = node
heappush(heap, [dist[cur],cur] )
path = self.tracePath(parent,self.destination)
return dist[self.destination], path
def tracePath(self,parent,j):
path = []
while parent[j]!=-1:
path.append(j)
j = parent[j]
path = path[::-1]
path = [self.source] + path
# print(path)
# convert this path to set of edges with weights (for plotting)
for i in range(1,len(path)):
x,y = path[i-1],path[i]
w = self.searchForWeight(x,y)
self.edge.append([x,y])
self.X.append(x)
self.Y.append(y)
self.W.append(w)
return path
def searchForWeight(self,x,y):
edge = self.G.edge
w = self.G.W
for i in range(len(edge)):
if (edge[i][0]==x and edge[i][1]==y) or (edge[i][1]==x and edge[i][0]==y):
return w[i]
return 0
|
f37f83d7ab9c9e0e8dd5c777833e51d2ee4d8712 | Bobby981229/Computer-Vision-Based-Vehicle-Integrated-Information-Collection-System | /labelme/rename.py | 275 | 3.515625 | 4 | # 为数据集重命名 -- 用数字命名
import os
path = '../labelme/pictures'
files = os.listdir(path)
for i, file in enumerate(files):
NewFileName = os.path.join(path, str(i)+'.jpg')
OldFileName = os.path.join(path, file)
os.rename(OldFileName, NewFileName)
|
c0911e4dd418627f8f9e8fed72da90d0a49df584 | claudiordgz/coding-challenges | /algorithms/hardcore.py | 1,776 | 3.890625 | 4 | class node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
""" Insert new node from data
"""
if self.data:
if data < self.data:
if self.left is None:
self.left = node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = node(data)
else:
self.right.insert(data)
else:
self.data = data
def get_ancestor(root, node1, node2):
if not root:
return
if root.data < node1 and root.data < node2:
return get_ancestor(root.right, node1, node2)
elif root.data > node1 and root.data > node2:
return get_ancestor(root.left, node1, node2)
else:
return root
def bstDistance(values, n, node1, node2):
root = node(values[0])
for n in values[1:]:
root.insert(n)
common_root = get_ancestor(root, node1, node2)
if not common_root:
return
left = common_root
right = common_root
l, r = 0, 0
while left:
if left.data > node1:
left = left.left
l += 1
elif left.data < node1:
left = left.right
l += 1
else:
break
while right:
if right.data > node2:
right = right.left
r += 1
elif right.data < node2:
right = right.right
r += 1
else:
break
return l+r
if __name__ == '__main__':
bstDistance([9,7,5,3,1], 5, 7, 20) |
abdcdf9e11c63b6903b9d418af90973150cce069 | meretciel/backtesting_platform | /initialize_platform.py | 2,200 | 3.578125 | 4 | """
Script: initialize_platform.py
This script will initialize the platform when it is download from the Github. User can modify the parameters defined
in this script. Please find more details in the comments.
To initialize the platform, please run this script in python.
"""
import os
from os import path
import pandas as pd
import script.download_stock_price_data as download_stock_price_data
import script.download_stock_fundamental_data as download_stock_fundamental_data
DATA_DIR = 'data_2016_06_07'
BASIC_DATA_CENTER = 'data_2016_06_07/data_center'
# Specify the start and end date of the simulation period.
# The system will prepare the data between this range
START_DATE = pd.datetime(2009, 1, 1)
END_DATE = pd.datetime(2013,06,30)
# Specify stocks of interests.
# If it is set None, the system will use the default value.
LIST_STOCKS = ['aapl','msft','mmm','ibm','jpm','wmt','yhoo','gps','ge','f']
if __name__ == '__main__':
# create data directory.
# The data directory will contain the data necessary for the simulation.
curr_dir = os.path.abspath(os.path.dirname(__file__))
data_dir = path.join(curr_dir, DATA_DIR)
if path.exists(data_dir):
print('Data directory exists. No data directory created.')
else:
os.mkdir(data_dir)
print('Create: {}'.format(data_dir))
# download and pre-processing the data
# download data from yahoo finance. This is the stock price data
print("Downloading stock price data from Yahoo finance")
index = download_stock_price_data.download(start_date=START_DATE, end_date=END_DATE, list_stock=LIST_STOCKS, output_path=data_dir)
# download data from stockpup.com. This is fundamental data of the stocks
print("Downloading fundamental data of stocks from Stockpup.com")
df = download_stock_fundamental_data.download(output_path=path.join(data_dir, 'fundamental_data_of_stocks.csv'))
print("Preparing the fundamental variables.")
download_stock_fundamental_data.prepare_and_save_data(df, index=index, output_path=data_dir)
print("\n")
print("************************")
print("Initialization complete.")
print("************************")
|
9697f7a36b82150f7272024294fe92bde7712ab1 | krissmile31/documents | /Term 1/SE/PycharmProjects/pythonProject/huh/Adaptive Huffman.py | 5,255 | 3.828125 | 4 | import heapq
import os
import sys
import time
class Tree:
# Initialize an empty tree: 1 root, 1 empty node
def __init__(self, character, frequency):
self.char = character
self.freq = frequency
self.left = None
self.right = None
def less_than(self, other):
return other.freq > self.freq
def equal(self, other):
return self.freq == other.freq
class Huffman:
# initialise array & dictionary
def __init__(self, path):
self.path = path
self.heap = []
self.codes = {}
self.reverse_mapping = {}
# make_frequency_dict: sorted value( low - high )
def freq_dict(self, text):
# initialise a empty dictionary
freq = {}
for char in text:
if not char in freq:
freq[char] = 0
freq[char] += 1
return freq
# make_heap_queue from node
def heap_node(self, frequency):
for key in frequency:
node = self.Tree(key, frequency[key])
self.heap.append(node)
# build Tree: merge nodes
def merge(self):
while len(self.heap) > 1:
node1 = heapq.heappop(self.heap)
node2 = heapq.heappop(self.heap)
merge_node = self.Tree(None, node1.freq + node2.freq)
merge_node.left = node1
merge_node.right = node2
heapq.heappush(self.heap, merge_node)
def encode_helper(self, root, current_code):
if root is None:
return
if root.char is not None:
self.codes[root.char] = current_code
self.reverse_mapping[current_code] = root.char
return
self.encode_helper(root.left, current_code + "0")
self.encode_helper(root.right, current_code + "1")
def encode(self):
root = heapq.heappop(self.heap)
current_code = ""
self.encode_helper(root, current_code)
def encode_text(self, text):
encodedText = ""
for char in text:
encodedText += self.codes[char]
return encodedText
def get_padding(self, encoded_text):
# get the extra padding of encode_text
exPad = 8 - len(encoded_text) % 8 # 8 bits
for i in range(exPad):
encoded_text += "0"
# merge informal information of exPad in "string/bits" with encode_text --> truncate
bin = '{0:08b}'
pad_info = bin.format(exPad)
return pad_info + encoded_text
def byte_array(self, pad_encoded_text):
if len(pad_encoded_text) % 8 != 0:
print('Encoded text is not padded properly!')
exit(0)
byteArray = bytearray()
# loop 8 characters once time
for i in range(0, len(pad_encoded_text), 8):
byte = pad_encoded_text[i: i + 8]
byteArray.append(int(byte, 2)) # base 2
return byteArray
def compress(self):
start = time.time()
file, file_extension = os.path.splitext(self.path)
output_path = file + '.bin'
with open(self.path, 'r+') as f, open(output_path) as output:
text = f.read()
text = text.rstrip()
frequency = self.freq_dict(text)
self.heap_node(frequency)
self.merge()
self.encode()
encoded_text = self.encode_text(text)
pad_encoded_text = self.get_padding(encoded_text)
byteArray = self.byte_array(pad_encoded_text)
output.write(bytes(byteArray))
print('Compression done!')
return output_path
# "Decompression"
def remove_padding(self, pad_encoded_text):
pad_info = pad_encoded_text[:8]
exPad = int(pad_info, 2)
pad_encoded_text = pad_encoded_text[8:]
return pad_encoded_text[:-exPad]
def decode_text(self, encoded_text):
current_code = ""
decoded_text = ""
for bit in encoded_text:
current_code += bit
for current_code in self.reverse_mapping:
character = self.reverse_mapping[current_code]
decoded_text += character
current_code = ""
return decoded_text
def decompress(self, input_path):
file, file_extension = os.path.splitext(self.path)
output_path = file + "_decompress.txt"
with open(input_path, 'rb') as f, open(output_path, 'w') as output:
bit_string = ""
byte = f.read(1)
while len(byte)>0:
byte = ord(byte)
bits = bin(byte)[2:].rjust(8, '0')
bit_string += bits
byte = f.read(1)
encoded_text = self.remove_padding(bit_string)
decompressed_text = self.decode_text(encoded_text)
output.write(decompressed_text)
print('Decompression done!')
return output_path
if __name__ == '__main__':
# input file path
path = 'Question.txt'
huffman = Huffman(path)
if sys.argv[1] == 'compress':
huffman.compress(sys.argv[2])
elif sys.argv[1] == 'decompress':
huffman.decompress(sys.argv[2])
else:
print('Command not found!')
exit(0)
|
95fb114c5f4d0d760b4dd1577a32921b9051695a | erjan/coding_exercises | /partition_array_such_that_maximum_difference_is_k.py | 1,718 | 3.640625 | 4 | '''
You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.
Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
'''
def partitionArray(self, A, k):
A.sort()
res, j = 1, 0
for i in range(len(A)):
if A[i] - A[j] > k:
res += 1
j = i
return res
------------------------------------------------------------------------------------------
def partitionArray(self, A, k):
A.sort()
res = 1
mn = mx = A[0]
for a in A:
mn = min(mn, a)
mx = max(mx, a)
if mx - mn > k:
res += 1
mn = mx = a
return res
-----------------------------------------------------------------------------------------------------------------
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
ans = 1
# To keep track of starting element of each subsequence
start = nums[0]
for i in range(1, len(nums)):
diff = nums[i] - start
if diff > k:
# If difference of starting and current element of subsequence is greater
# than K, then only start new subsequence
ans += 1
start = nums[i]
return ans
|
bf89461701da5f64af91050f7e3de8d8762f5041 | forwardslash333/PythonPractice | /11. Calender.py | 270 | 3.90625 | 4 | import calendar #This module contains functions for calender
year = int(input('Enter the year')) #Input values
month = int(input('Enter the month'))
print(calendar.month(year,month))
print(calendar.__doc__) #Print |
18abc44012ee42dfae1e2121882b99de05c8b06d | ferasezzaldeen/data-structures-and-algorithms | /python/code_challenges/tree_intersection/intersection.py | 781 | 4.0625 | 4 | from trees import *
def tree_intersection(first: Binary_Tree,second: Binary_Tree):
if(first.root and second.root):
list1=first.pre_order()
list2=second.pre_order()
sol=[]
for x in list1:
for i in list2:
if x==i:
sol.append(x)
if sol:
return sol
else:
return 'there is no intersection'
else:
return 'there is an empty tree'
if __name__ == '__main__':
test1 = Binary_Tree()
test1.root = Node(90)
test1.root.right = Node(80)
test1.root.left = Node(100)
test2 = Binary_Tree()
test2.root = Node(20)
test2.root.right = Node(10)
test2.root.left = Node(100)
print(tree_intersection(test1,test2)) |
5f5b6bdd251bf68fcc573997e47313685c7b153b | MechZombie/Python-Basico | /Tuplas.py | 327 | 3.734375 | 4 | # -*- coding: utf-8 -*-
#Tuplas são similáres a um vetor, exceto pelo fato de serem imutpaveis
words = ("spam","eggs","sausages")
# words[0] = "cheese" vai dar erro.
#Outra forma de criar tuplas.
tuplas = "primeiro","segundo"
print(tuplas[0])
#É possível atribuir valores dessa forma.
tupla = (1,(1,2,3))
print(tupla[1]) |
4b47ad848c10580d68c84de9ecc468b532706797 | BlackTimber-Labs/DemoPullRequest | /Python/palin.py | 133 | 3.96875 | 4 | def palindrome(s):
s=s.replace(" ",'')
reverse=s[::-1]
if s==reverse:
return True
else:
return False
|
1d566d0135acbb09e669fb144abf3614542cffd0 | yansenkeler/pyApp | /DoubleBasePalindromes.py | 844 | 3.75 | 4 | # The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
# Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
# (Please note that the palindromic number, in either base, may not include leading zeros.)
import math, time
def is_palindromes(num):
l = list(str(num))
l.reverse()
reversed_num = int(''.join(l))
if num == reversed_num:
return True
return False
def decimal_to_binary(dec):
return int(str(bin(dec))[2:])
startTime = time.time()
sum_num = 0
for y in range(1, 1000000):
if is_palindromes(y) and is_palindromes(decimal_to_binary(y)):
print(y, decimal_to_binary(y))
sum_num += y
print('total sum is: ', sum_num)
# print(is_palindromes(decimal_to_binary(585)))
print('total time: ', time.time() - startTime, 'ms') |
9cb7eec5ed3870d3c307d1b025f246f61f14aed5 | Huijuan2015/leetcode_Python_2019 | /314. Binary Tree Vertical Order Traversal.py | 3,051 | 3.796875 | 4 | # 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):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return
mp = collections.defaultdict(list)
q = collections.deque()
q.append((root, 0))
res = []
while q:
node, depth = q.popleft()
mp[depth].append(node.val)
if node.left:
q.append((node.left, depth-1))
if node.right:
q.append((node.right, depth+1))
for k in sorted(mp.keys()):
res.append(mp[k])
return res
# 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):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
from collections import defaultdict
self.mp = defaultdict(list)
self.leftmost, self.rightmost = 0, 0
self.dfs(root, 0, 0)
res = []
for i in range(self.leftmost+1, self.rightmost):
res.append([pair[0] for pair in sorted(self.mp[i], key= lambda x: x[1])])
return res
def dfs(self, root, width, count):
self.leftmost = min(self.leftmost, width)
self.rightmost = max(self.rightmost, width)
if not root:
return
self.mp[width].append((root.val, count))
self.dfs(root.left, width-1, count+1)
self.dfs(root.right, width+1, count+1)
BFS, level traversal, keep leftmost, rightmost and mp for width:node.val
# 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):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
from collections import defaultdict
if not root:
return
level = [(root, 0)]
res = []
leftmost, rightmost = 0, 0
mp = defaultdict(list)
while level:
nextLevel = []
for pair in level:
node, width = pair
leftmost = min(leftmost, width)
rightmost = max(rightmost, width)
mp[width].append(node.val)
if node.left:
nextLevel.append((node.left, width-1))
if node.right:
nextLevel.append((node.right, width+1))
level = nextLevel
# for i in range(leftmost, rightmost+1):
res = [mp[i] for i in range(leftmost, rightmost+1)]
return res
|
81d1f14eb8ba54ee5875c0227daee187d4d4ec2f | ReaseySereiNeath/Share-Python | /reasey.sereineath19/week01/c11_hello_loop.py | 85 | 3.9375 | 4 | num = int(input("Enter a number: "))
for i in range (num):
print("Hello World!") |
9df5be8e57c5219b6ca4da5ebca7b14d74600293 | sufailps/erp_project | /empfunc.py | 4,285 | 4.0625 | 4 | print("employee management")
emp=[]
empdict={}
groups={}
def manage_all_group_menu():
print("\t 1 for create group")
print("\t 2 for display group")
print("\t 3 for manage group")
print("\t 4 for delete group")
print("\t 5 for Exit")
def create_group():
gname=input("Enter group name")
groups[gname] = []
def delete_group():
group_name = input("\tEnter group name ")
if group_name in groups.keys():
del groups[group_name]
print("\tDeleted the group")
else:
print("\tWrong group name")
def display_group():
for key,value in groups.items():
name_string = ""
for i in value:
name_string = name_string + "|" + empdict[i]["name"]
print(f"{key} => {name_string}")
def manage_group_menu():
print("\t\t1.Add Member")
print("\t\t2.Delete Member")
print("\t\t3.List Members")
# print("\t\t4.Exit")
def manage_group():
group_name = input("\t\tEnter group name ")
manage_group_menu()
ch = int(input("\t\t Enter your Choice "))
if ch == 1:
#Add member
add_member(group_name)
elif ch == 2:
#Delete member
delete_member(group_name)
elif ch == 3:
#List member
list_member(group_name)
else:
print("\tInvalid choice")
def add_member(group_name):
# display_student()
print(empdict)
serial_no = int(input("\t\tEnter the serial no of employee "))
if serial_no in empdict.keys():
groups[group_name].append(serial_no)
else:
print("\t\tWrong serial No.")
def list_member(group_name):
name_string=""
for i in groups[group_name]:
name_string = name_string +"|"+i+"."+empdict[i]["name"]
print(f"{name_string}")
def delete_member(group_name):
list_member(group_name)
serial_no = input("\t\tEnter serial no from list")
if serial_no in groups[group_name]:
groups[group_name].remove(serial_no)
else:
print("\t\tWrong serial No.")
def manage_all_groups():
while True:
manage_all_group_menu()
c= int(input("\t Enter choice"))
if c == 1:
create_group()
elif c == 2:
display_group()
elif c == 3:
manage_group()
elif c == 4:
delete_group()
elif c == 5:
break;
else:
print("invalid entry")
while True:
print("Enter 1 for add employee ")
print("Enter 2 for delete employee")
print("Enter 3 for search employee")
print("Enter 4 for channge employee data")
print("Enter 5 for display employees")
print("Enter 6 for Manage Teams")
print("Enter 7 for quite")
choice=int(input())
if (choice == 1):
addid=int(input("Enter Id\t"))
if addid not in empdict.keys():
addname=input("Enter name\t")
addage=int(input("Enter age\t"))
addgender=input("Gender\t\t")
addplace=input("Enter place\t")
addsalary=input("Enter salary\t")
addpcompany=input("Enter previous company\t")
addjdate=input("Enter joining data dd/mm/yyyy\t")
empdict[addid]={
"name":addname,
"age":addage,
"gender":addgender,
"place":addplace,
"salary":addsalary,
"pcompany":addpcompany
}
#empdict[addid] = temp
else:
print("ID is already in data")
# emp.append(addname)
elif (choice == 2):
print(empdict)
did=int(input("Enter Id\t"))
del empdict[did]
print("deleted",empdict)
elif (choice == 3):
sname=input("Enter employee name\t")
for i in empdict.values():
if i["name"] == sname:
print(sname,"is found")
else:
print(sname, "not in data")
elif (choice == 4):
cid=int(input("enter id of employee"))
if cid in empdict.keys():
ch=int(input("1 for change name \n 2 for age \n 3 for gender \n 4 for salary"))
if (ch == 1):
cname=input("enter new name")
empdict[cid]['name']=cname
print(empdict)
elif (ch == 2):
cage=input("Enter new age")
empdict[cid]['age']=cage
print(empdict)
elif (ch == 3):
cgender("Enter gender")
empdict[cid]['gender']=cgender
print(empdict)
elif (ch == 4):
csalary("Enter salary")
empdict[cid]['salary']=csalary
print(empdict)
else:
print("invalid entry")
#cname=input()
#i=emp.index(cname)
#print("enter new name")
#nname=input()
#emp[i]=nname
#print(emp)
elif (choice == 5):
print(empdict)
#a=1
#for j in emp:
# print(str(a) + "." + j)
# a+=1
# aaa=j
#ind=emp.index[aaa]
elif (choice == 6):
manage_all_groups()
elif (choice == 7):
break;
else:
print("invalid entry")
#emp.append("suf")
#print(emp[0])
|
e7028a1e4ce2ca77b268585a0b8d9dc351f6885e | chryswoods/siremol.org | /chryswoods.com/intro_to_mc/software/2/metropolis.py | 7,802 | 3.671875 | 4 |
import random
import math
import copy
# Set the number of atoms in the box
n_atoms = 25
# Set the number of Monte Carlo moves to perform
num_moves = 5000
# Set the size of the box (in Angstroms)
box_size = [ 15.0, 15.0, 15.0 ]
# The maximum amount that the atom can be translated by
max_translate = 0.5 # angstroms
# The maximum amount to change the volume - the
# best value is 10% of the number of atoms
max_volume_change = 0.1 * n_atoms # angstroms**3
# Simulation temperature
temperature = 298.15 # kelvin
# Simulation pressure
pressure = 1 # atmospheres
# Convert pressure to internal units (kcal mol-1 A-3)
pressure = pressure * 1.458397506863647E-005
# Give the Lennard Jones parameters for the atoms
# (these are the OPLS parameters for Krypton)
sigma = 3.624 # angstroms
epsilon = 0.317 # kcal mol-1
# Create an array to hold the coordinates of the atoms
coords = []
# Randomly generate the coordinates of the atoms in the box
for i in range(0,n_atoms):
# Note "random.uniform(x,y)" would generate a random number
# between x and y
coords.append( [random.uniform(0,box_size[0]), \
random.uniform(0,box_size[1]), \
random.uniform(0,box_size[2]) ] )
def make_periodic(x, box):
"""Subroutine to apply periodic boundaries"""
while (x < -0.5*box):
x += box
while (x > 0.5*box):
x -= box
return x
def wrap_into_box(x, box):
"""Subroutine to wrap the coordinates into a box"""
while (x > box):
x -= box
while (x < 0):
x += box
return x
def print_pdb(move):
"""Print a PDB for the specified move"""
filename = "output%000006d.pdb" % move
FILE = open(filename, "w")
FILE.write("CRYST1 %8.3f %8.3f %8.3f 90.00 90.00 90.00\n" % \
(box_size[0], box_size[1], box_size[2]))
for i in range(0,n_atoms):
FILE.write("ATOM %5d Kr Kr 1 %8.3f%8.3f%8.3f 1.00 0.00 Kr\n" % \
(i+1, coords[i][0], coords[i][1], coords[i][2]))
FILE.write("TER\n")
FILE.close()
# Subroutine that calculates the energies of the atoms
def calculate_energy():
"""Calculate the energy of the passed atoms (assuming all atoms
have the same LJ sigma and epsilon values)"""
# Loop over all pairs of atoms and calculate
# the LJ energy
total_energy = 0
for i in range(0,n_atoms-1):
for j in range(i+1, n_atoms):
delta_x = coords[j][0] - coords[i][0]
delta_y = coords[j][1] - coords[i][1]
delta_z = coords[j][2] - coords[i][2]
# Apply periodic boundaries
delta_x = make_periodic(delta_x, box_size[0])
delta_y = make_periodic(delta_y, box_size[1])
delta_z = make_periodic(delta_z, box_size[2])
# Calculate the distance between the atoms
r = math.sqrt( (delta_x*delta_x) + (delta_y*delta_y) +
(delta_z*delta_z) )
# E_LJ = 4*epsilon[ (sigma/r)^12 - (sigma/r)^6 ]
e_lj = 4.0 * epsilon * ( (sigma/r)**12 - (sigma/r)**6 )
total_energy += e_lj
# return the total energy of the atoms
return total_energy
# calculate kT
k_boltz = 1.987206504191549E-003 # kcal mol-1 K-1
kT = k_boltz * temperature
# The total number of accepted moves
naccept = 0
# The total number of rejected moves
nreject = 0
# Print the initial PDB file
print_pdb(0)
# Now perform all of the moves
for move in range(1,num_moves+1):
# calculate the old energy
old_energy = calculate_energy()
# calculate the old volume of the box
V_old = box_size[0] * box_size[1] * box_size[2]
# Pick a random atom (random.randint(x,y) picks a random
# integer between x and y, including x and y)
atom = random.randint(0, n_atoms-1)
# save the old coordinates
old_coords = copy.deepcopy(coords)
# save the old box dimensions
old_box_size = copy.deepcopy(box_size)
# Decide if we are performing an atom move, or a volume move
if random.uniform(0.0,1.0) <= (1.0 / n_atoms):
# 1 in n_atoms chance of being here. Perform a volume move
# by changing the volume for a random amount
delta_vol = random.uniform(-max_volume_change, max_volume_change)
# calculate the new volume
V_new = V_old + delta_vol
# The new box length is the cube root of the volume
box_side = V_new**(1.0/3.0)
# The amount to scale each atom from the center is
# the cube root of the ratio of the new and old volumes
scale_ratio = ( V_new / V_old )**(1.0/3.0)
# now translate every atom so that it is scaled from the center
# of the box
for i in range(0,n_atoms):
dx = coords[i][0] - (0.5*box_size[0])
dy = coords[i][1] - (0.5*box_size[1])
dz = coords[i][2] - (0.5*box_size[2])
length = math.sqrt(dx*dx + dy*dy + dz*dz)
if length > 0.01: # don't scale atoms already near the center
dx /= length
dy /= length
dz /= length
# now scale the distance from the atom to the box center
# by 'scale_ratio'
length *= scale_ratio
# move the atom to its new location
coords[i][0] = (0.5*box_size[0]) + dx*length
coords[i][1] = (0.5*box_size[1]) + dy*length
coords[i][2] = (0.5*box_size[2]) + dz*length
box_size[0] = box_side
box_size[1] = box_side
box_size[2] = box_side
else:
# Make the move - translate by a delta in each dimension
delta_x = random.uniform( -max_translate, max_translate )
delta_y = random.uniform( -max_translate, max_translate )
delta_z = random.uniform( -max_translate, max_translate )
coords[atom][0] += delta_x
coords[atom][1] += delta_y
coords[atom][2] += delta_z
# wrap the coordinates back into the box
coords[atom][0] = wrap_into_box(coords[atom][0], box_size[0])
coords[atom][1] = wrap_into_box(coords[atom][1], box_size[1])
coords[atom][2] = wrap_into_box(coords[atom][2], box_size[2])
# calculate the new energy
new_energy = calculate_energy()
# calculate the new volume of the box
V_new = box_size[0] * box_size[1] * box_size[2]
accept = False
# Automatically accept if the energy goes down
if (new_energy <= old_energy):
accept = True
else:
# Now apply the Monte Carlo test - compare
# exp( -(E_new - E_old + P(V_new - V_old)) / kT
# + N ln (V_new - V_old) ) >= rand(0,1)
x = math.exp( (-(new_energy - old_energy + pressure * (V_new - V_old)) / kT)
+ (n_atoms * (math.log(V_new) - math.log(V_old)) ) )
if (x >= random.uniform(0.0,1.0)):
accept = True
else:
accept = False
if accept:
# accept the move
naccept += 1
total_energy = new_energy
else:
# reject the move - restore the old coordinates
nreject += 1
# restore the old conformation
coords = copy.deepcopy(old_coords)
box_size = copy.deepcopy(old_box_size)
total_energy = old_energy
# print the energy every 10 moves
if move % 10 == 0:
print("%s %s %s %s" % (move, total_energy, naccept, nreject))
print(" Box size = %sx%sx%s. Volume = %s A^3" % \
(box_size[0], box_size[1], box_size[2],
box_size[0]*box_size[1]*box_size[2]))
# print the coordinates every 100 moves
if move % 100 == 0:
print_pdb(move)
|
833727497f0946ba150a72bc2bdc4122f19368fb | rubinpar/Code-Connects | /hw/hw7.py | 3,311 | 4.15625 | 4 | # 1. write a function
# 2520 is the smallest number that can be divided
# by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly
# divisible by all of the numbers from 1 to 20?
def divisible_by_n(i, n):
"""
i is divisible by n without a remainder
"""
return i % n == 0
def divisible_1_thru_10():
for i in range(1, 1000000):
if i % 1 == 0:
if i % 2 == 0:
if i % 3 == 0:
if i % 4 == 0:
if i % 5 == 0:
if i % 6 == 0:
if i % 7 == 0:
if i % 8 == 0:
if i % 9 == 0:
if i % 10 == 0:
return i
print(divisible_1_thru_10())
def smallest_divisible_1_thru_x(x=20, max_number=1E8):
number = 1
while number < max_number:
if all([divisible_by_n(number, i) for i in range(1, x+1)]):
return number
number += 1
print("Smallest number is ", smallest_divisible_1_thru_x(x=5))
# print(smallest_divisible_1_thru_x())
# 2. write another function
# Book Inventory
# Write a function called print_book that will print out the details of a book in
# a book stores inventory.
# Input Format
#
# The input parameters to your function should be the book title, author, num-
# ber of copies of the book, and price of the book.
#
# Constraints
# All the print statements need to happen inside the function. You should use
# the str() function to turn a number into a string.
# Output Format
# Print the book details in the format below. Also output the store revenue if
# they sell all the books in the inventory.
#
#
# EXAMPLE:
# Sample Input
# printBook("I Know Why the Caged Bird Sings", "Maya Angelou", 100, 20)
# Sample Output
# Title: I Know Why the Caged Bird Sing
# Author: Maya Angelou
# Number of Copies: 100
# Price per Copy: $20
# Revenue: $2000
#
# Explanation
# We print out out the title, author, number of copies, price per copy, and
# revenue on separate lines. The revenue is the number of copies multiplied by
# the price per copy, which is 2000.
# Name: print_book
# Inputs: name of the book [title], author, number of copies, price per copy
# Doing: calculate the revenue
# Outputs: No return, print stuff
def print_book(title, author, num_copies, price_copy):
revenue = num_copies * price_copy
print("Title: ", title)
print("Author: ", author)
print("Number of Copies ", num_copies)
print("Price per Copy ", price_copy)
print("Revenue: ", revenue)
print_book("I Know Why the Caged Bird Sings", "Maya Angelou", 100, 20)
# FizzBuzz game expert
# input: number to count up to
# outputs: Nothing, prints
# Example:
# FizzBuzz(15)
# Output:
# 1
# 2
# Fizz
# 4
# Buzz
# Fizz
# 7
# 8
# Fizz
# Buzz
# 11
# Fizz
# 13
# 14
# Fizz buzz
def fizz_buzz(x):
for i in range(1, x+1):
if i % 3 == 0 and i % 5 == 0:
print("Fizz buzz")
elif i % 3 == 0: # NOT divisible by both 3 by 5
print("Fizz")
elif i % 5 == 0: # NOT divisible by 3
print("Buzz")
else:
print(i)
fizz_buzz(15)
# 3. think about a project
|
6f5ad9be7d104570d2b7e60e25fd0affb08e5269 | arnab-sen/practice_projects | /python/chess/chess_v1.0.py | 20,652 | 4 | 4 | """
A text-based chess game
"""
import copy
import random
import time
def initialise_board():
# Initialise the 8x8 board matrix
# Extra top layer to make it same in dimension to the display board
# doing board = [["_"] * 8] * 9 creates 9 sets of the same list,
# so altering any element changes that element for each list;
# need board = [["_"] * 8 for i in range(9)] so that each of those
# 9 lists are independent
board = [["_"] * 8 for i in range(9)]
pieces = [[], []]
pieces[0] = ["Rb", "Kb", "Bb", "Qb", "+b", "Bb", "Kb", "Rb", "Pb"]
pieces[1] = ["Rw", "Kw", "Bw", "Qw", "+w", "Bw", "Kw", "Rw", "Pw"]
# Black side (top)
board[1] = pieces[0][:-1]
board[2] = [pieces[0][-1]] * 8
# White side (bottom)
board[8] = pieces[1][:-1]
board[7] = [pieces[1][-1]] * 8
#print(board[0])
#print(board[1])
#print(board[2])
#print(board[6])
#print(board[7])
return board
def display_board_old(board_):
# This version has the original notation for
# the pieces (e.g. white pawn = Pw)
board = copy.deepcopy(board_)
board[0] = [" ____"] * 8
for i in range(1, 9):
for j in range(8):
if board[i][j].find("b") == -1 and \
board[i][j].find("w") == -1:
board[i][j] = "|____"
elif board[i][j].find("b") != -1:
s = board[i][j]
if len(s) == 2:
board[i][j] = "|_" + s + "_"
else:
board[i][j] = "|_" + s[s.find("b") - 1: s.find("b") + 1]
elif board[i][j].find("w") != -1:
s = board[i][j]
if len(s) == 2:
board[i][j] = "|_" + s + "_"
else:
board[i][j] = "|_" + s[s.find("w") - 1: s.find("w") + 1]
board[i][7] += "|"
print(" ", end = "")
for i in range(8): print(board[0][i], end = "")
print()
for i in range(1, 9):
print(9 - i, " ", end = "")
for j in range(8):
print(board[i][j], end = "")
print()
print(" a b c d e f g h")
print()
def get_piece_image(piece):
# Return a fancy unicode version of
# a piece
# e.g. "Kb" --> "♞" (black knight)
new_piece = "!"
if piece[0] == "P":
if piece[1] == "w": return "♙"
elif piece[1] == "b": return "♟"
if piece[0] == "R":
if piece[1] == "w": return "♖"
elif piece[1] == "b": return "♜"
if piece[0] == "K":
if piece[1] == "w": return "♘"
elif piece[1] == "b": return "♞"
if piece[0] == "B":
if piece[1] == "w": return "♗"
elif piece[1] == "b": return "♝"
if piece[0] == "Q":
if piece[1] == "w": return "♕"
elif piece[1] == "b": return "♛"
if piece[0] == "+":
if piece[1] == "w": return "♔"
elif piece[1] == "b": return "♚"
return new_piece
def display_board(board_):
# This version has the new unicode versions
# of the pieces (e.g. white pawn = ♙)
board = copy.deepcopy(board_)
board[0] = ["____"] * 7 + ["___"]
for i in range(1, 9):
for j in range(8):
if board[i][j].find("b") == -1 and \
board[i][j].find("w") == -1:
board[i][j] = "|___"
else:
s = get_piece_image(board[i][j])
if j <= 2: board[i][j] = "|_" + s
elif j >= 5: board[i][j] = "|" + s + "_"
else: board[i][j] = "|_" + s + "_"
board[i][7] += "|"
print(" ", end = "")
for i in range(8): print(board[0][i], end = "")
print()
for i in range(1, 9):
print(9 - i, "", end = "")
for j in range(8):
print(board[i][j], end = "")
print()
print(" a b c d e f g h")
print()
def get_cpu_move(board, player):
cpu = True
position = ["", "", "", ""]
position[0] = random.randrange(1, 9)
position[1] = random.randrange(8)
position[2] = random.randrange(1, 9)
position[3] = random.randrange(8)
while not(move_is_valid(board, position, player, cpu)):
position[0] = random.randrange(1, 9)
position[1] = random.randrange(8)
position[2] = random.randrange(1, 9)
position[3] = random.randrange(8)
#print(position)
return position
def get_move(board, player):
print("Move example: a2 to a4")
letters = "abcdefgh"
move = input("Enter move (-1 to exit): ")
move = move.split()
if move[0] == "-1": return [-1]
position = ["row 1", "col 1", "row 2", "col 2"]
# Rows are numbers (9 - i), cols are letters (a - h)
position[0] = 9 - int(move[0][1])
position[1] = letters.find(move[0][0])
position[2] = 9 - int(move[2][1])
position[3] = letters.find(move[2][0])
while not(move_is_valid(board, position, player, False)):
print("Invalid move")
move = input("Enter move (-1 to exit): ")
move = move.split()
if move[0] == "-1": return [-1]
position = ["row 1", "col 1", "row 2", "col 2"]
# Rows are numbers (9 - i), cols are letters (a - h)
position[0] = 9 - int(move[0][1])
position[1] = letters.find(move[0][0])
position[2] = 9 - int(move[2][1])
position[3] = letters.find(move[2][0])
#print(position)
return position
def move_piece(board, move):
board[move[2]][move[3]] = board[move[0]][move[1]]
board[move[0]][move[1]] = "_"
return board
def print_board_matrix(board):
for i in range(9):
print(board[i])
def remove_overlap(board, move):
# move current piece to "graveyard"
# replace current piece with new piece
# (so long as the move was valid)
pass
def get_forward_movement(piece, move):
# Forward movement of a white piece is
# the reverse of a black piece, but
# horizontal movement is the same
# i.e. forward: b 1 -> 8/ w 8 -> 1,
# horizontal: b 0 -> 7/ w 0 -> 7
# right_movement > 0 means pos_f is to
# the right of pos_i, and
# right_movement < 0 means pos_f is to
# the left of pos_i
pos_i = move[0:2]
pos_f = move[2:4]
forward_movement = 0
if piece[1] == "w":
forward_movement = pos_i[0] - pos_f[0]
elif piece[1] == "b":
forward_movement = pos_f[0] - pos_i[0]
return forward_movement
def get_right_movement(piece, move):
pos_i = move[0:2]
pos_f = move[2:4]
right_movement = 0
if piece[1] == "w" or piece[1] == "b":
right_movement = pos_f[1] - pos_i[1]
return right_movement
def valid_movement_pattern(board, piece, move):
pos_i = move[0:2]
pos_f = move[2:4]
forward_movement = get_forward_movement(piece, move)
right_movement= get_right_movement(piece, move)
# - Check piece patterns in the order:
# pawn, rook, knight, bishop, queen, king
# - Remember that moving forward is 1 -> 8
# for black pieces and 8 -> 1 for white
# pieces
if piece[0] == "P":
if pos_f[1] != pos_i[1]:
# Diagonal movement only allowed
# if taking an opponent's piece
if not(overlap_with_enemy(board, move)): return False
if forward_movement == 0: return False
if forward_movement == 1 and abs(right_movement) > 1: return False
if forward_movement == -1 and abs(right_movement) > 0: return False
if forward_movement > 2: return False
if forward_movement < -1: return False
# - Two steps forward is only valid if the
# pawn is currently in its initial position
if forward_movement == 2:
if piece[1] == "w" and pos_i[0] != 7: return False
if piece[1] == "b" and pos_i[0] != 2: return False
elif piece[0] == "R":
# Invalid if it moves diagonally
if forward_movement * right_movement != 0: return False
elif piece[0] == "K":
# Can only move in an L shape variant,
# i.e. vertically 2, horizontally 1 or
# vertically 1, horizontally 2
if not(abs(forward_movement) * abs(right_movement) == 2):
return False
elif piece[0] == "B":
# Invalid if it moves vertically
# without moving horizontally an
# equal amount
if abs(forward_movement) != abs(right_movement):
return False
elif piece[0] == "Q":
# The queen can either move like a rook
# or like a bishop, but not both
if forward_movement * right_movement != 0:
if abs(forward_movement) != abs(right_movement):
return False
elif piece[0] == "+":
# Moves exactly like a queen except
# neither its vertical nor horizontal
# movement can exceed one square
if abs(forward_movement) > 1 or abs(right_movement) > 1:
return False
return True
def moving_opponent_piece(board, move, player):
b = board
m = move
piece = b[m[0]][m[1]]
if player == 1:
if piece[1] == "b": return True
if player == 2:
if piece[1] == "w": return True
return False
def move_is_valid(board, move, player, cpu):
b = board
m = move
piece = b[m[0]][m[1]]
# Invalid when:
# - Out of bounds
if out_of_bounds(m):
if not(cpu): print("Out of bounds")
return False
# - No piece chosen
if piece == "_":
if not(cpu): print("No piece chosen")
return False
# - Player is trying to move
# the opponent's piece
if moving_opponent_piece(board, move, player):
if not(cpu): print("You cannot move an opponent's piece!")
return False
# - Piece movement doesn't match
# piece movement pattern (e.g.
# a rook moving diagonally is
# invalid)
if not(valid_movement_pattern(b, piece, m)):
if not(cpu): print("Invalid movement pattern")
return False
# - The destination contains a
# piece from the same team
if overlap_with_team(b, m):
if not(cpu): print("One of your pieces is already in that position")
return False
# - The pattern is obstructed by
# another piece (exceptions:
# knight, king + castle swap
# (castling))
if path_obstructed(b, m):
if not(cpu): print("Path obstructed")
return False
return True
def path_obstructed(board, move):
# - This returns True if there is a piece
# in the path of the piece's movement;
# this excludes the destination and
# the movement of knights
# - This assumes that the movement pattern
# of the piece is valid (which should be
# checked prior to this call in
# move_is_valid())
b = board
m = move
piece = b[m[0]][m[1]]
destination = b[m[2]][m[3]]
forward_movement = get_forward_movement(piece, move)
right_movement = get_right_movement(piece, move)
if piece[0] == "P":
if right_movement == 0:
if destination != "_": return True
if abs(forward_movement) == 2:
if piece[1] == "w":
if b[m[2] + 1][m[3]] != "_": return True
elif piece[1] == "b":
if b[m[2] - 1][m[3]] != "_": return True
if piece[0] == "R":
if forward_movement != 0:
if piece[1] == "w":
for i in range(1, abs(forward_movement) + 1):
if b[8 - i][m[3]] != "_": return True
elif piece[1] == "b":
for i in range(m[0] + 1, m[0] + abs(forward_movement)):
if b[i][m[3]] != "_": return True
elif right_movement != 0:
if right_movement > 0:
for i in range(m[1] + 1, m[1] + right_movement):
if b[m[2]][i] != "_": return True
if right_movement < 0:
for i in range(abs(right_movement)):
if b[m[2]][7 - i] != "_": return True
if piece[0] == "B":
# Use m[0 or 1] + 1 as the starting check position
# so that it doesn't check itself and see an
# obstruction
# Moving right: right_check > 0
# Moving left: right_check < 0
# Moving up and right
if piece[1] == "w": forward_check = forward_movement > 0
if piece[1] == "b": forward_check = forward_movement < 0
right_check = right_movement > 0
if forward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving up and right")
if b[m[0] - i][m[1] + i] != "_": return True
# Moving up and left
if piece[1] == "w": forward_check = forward_movement > 0
if piece[1] == "b": forward_check = forward_movement < 0
right_check = right_movement < 0
if forward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving up and left")
if b[m[0] - i][m[1] - i] != "_": return True
# Moving down and right
if piece[1] == "w": downward_check = forward_movement < 0
if piece[1] == "b": downward_check = forward_movement > 0
right_check = right_movement > 0
if downward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving down and right")
if b[m[0] + i][m[1] + i] != "_": return True
# Moving down and left
if piece[1] == "w": downward_check = forward_movement < 0
if piece[1] == "b": downward_check = forward_movement > 0
right_check = right_movement < 0
if downward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving down and left")
if b[m[0] + i][m[1] - i] != "_": return True
if piece[0] == "Q":
# Behaves as a rook if the movement is in one dimension,
# and as a rook otherwise
if forward_movement * right_movement == 0:
# Rook
if forward_movement != 0:
if piece[1] == "w":
for i in range(1, abs(forward_movement) + 1):
if b[8 - i][m[3]] != "_": return True
elif piece[1] == "b":
for i in range(m[0] + 1, m[0] + abs(forward_movement)):
if b[i][m[3]] != "_": return True
elif right_movement != 0:
if right_movement > 0:
for i in range(m[1] + 1, m[1] + right_movement):
if b[m[2]][i] != "_": return True
if right_movement < 0:
for i in range(abs(right_movement)):
if b[m[2]][7 - i] != "_": return True
else:
# Bishop
# Moving up and right
if piece[1] == "w": forward_check = forward_movement > 0
if piece[1] == "b": forward_check = forward_movement < 0
right_check = right_movement > 0
if forward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving up and right")
if b[m[0] - i][m[1] + i] != "_": return True
# Moving up and left
if piece[1] == "w": forward_check = forward_movement > 0
if piece[1] == "b": forward_check = forward_movement < 0
right_check = right_movement < 0
if forward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving up and left")
if b[m[0] - i][m[1] - i] != "_": return True
# Moving down and right
if piece[1] == "w": downward_check = forward_movement < 0
if piece[1] == "b": downward_check = forward_movement > 0
right_check = right_movement > 0
if downward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving down and right")
if b[m[0] + i][m[1] + i] != "_": return True
# Moving down and left
if piece[1] == "w": downward_check = forward_movement < 0
if piece[1] == "b": downward_check = forward_movement > 0
right_check = right_movement < 0
if downward_check and right_check:
for i in range(1, abs(forward_movement)):
#print("Moving down and left")
if b[m[0] + i][m[1] - i] != "_": return True
return False
def overlap_with_team(board, move):
b = board
m = move
piece = b[m[0]][m[1]]
destination = b[m[2]][m[3]]
if destination == "_": return False
if piece[1] == destination[1]: return True
else: return False
def overlap_with_enemy(board, move):
b = board
m = move
piece = b[m[0]][m[1]]
destination = b[m[2]][m[3]]
if destination == "_": return False
if piece[1] != destination[1]: return True
else: return False
def out_of_bounds(move):
if move[0] < 1 or move[0] > 8: return True
if move[1] < 0 or move[1] > 7: return True
if move[2] < 1 or move[0] > 8: return True
if move[3] < 0 or move[1] > 7: return True
return False
def clear_screen():
print("\n" * 50)
def get_removed_pieces(board, move):
pass
def check_game_state(board):
# Check if either king is not in play,
# in which case the player with a king
# in play wins
white_wins = False
black_wins = False
for i in range(len(board)):
for piece in board[i]:
if piece == "+w": white_wins = True
if piece == "+b": black_wins = True
if white_wins and not(black_wins): return "Player 1 wins!"
elif black_wins and not(white_wins): return "Player 2 wins!"
else: return ""
def display_menu():
print("Welcome to chess!")
print("1. Player 1 vs Player 2 (CPU)")
print("2. Player 1 vs Player 2 (Human)")
print("3. Exit")
choice = input("Enter your choice: ")
return choice
def play_vs_cpu(board):
turn = 1
while(1):
if turn % 2 == 1: player = 1
elif turn % 2 == 0: player = 2
else: break
clear_screen()
display_board(board)
game_over = check_game_state(board)
if game_over != "":
print(game_over)
break
if player == 2:
print("Turn", turn)
print("The computer is thinking...")
time.sleep(2)
print("Player " + str(player) + "'s turn")
print("Turn", turn)
if player == 1:
move = get_move(board, player)
else: move = get_cpu_move(board, player)
if move[0] == -1: break
board = move_piece(board, move)
turn += 1
def play_vs_player_2(board):
turn = 1
while(1):
if turn % 2 == 1: player = 1
elif turn % 2 == 0: player = 2
else: break
clear_screen()
display_board(board)
game_over = check_game_state(board)
if game_over != "":
print(game_over)
break
print("Player " + str(player) + "'s turn")
print("Turn", turn)
move = get_move(board, player)
if move[0] == -1: break
board = move_piece(board, move)
turn += 1
def play_debug(board):
while(1):
player = 1
clear_screen()
display_board(board)
game_over = check_game_state(board)
if game_over != "":
print(game_over)
break
move = get_move(board, player)
if move[0] == -1: break
board = move_piece(board, move)
def main():
# TODO:
# - Tidy up positional comparisons
# with helper functions,
# e.g. is_diagonal_to() instead of
# comparing coordinates
clear_screen()
board = initialise_board()
choice = display_menu()
if choice == "1": play_vs_cpu(board)
elif choice == "2": play_vs_player_2(board)
elif choice == "debug": play_debug(board)
print("Exiting...")
main()
"""
ISSUES:
- Queen path obstructed when moving up
even though nothing is in its way;
there is a pawn to its right and
a pawn below it
- Queen could not remove enemy pawn
(pawn stayed in place and queen was
instead removed)
"""
|
a1c63aff1b5221900c2e4d498e622e3f446d411b | myles/five-little-monkeys | /five-little-monkeys.py | 696 | 4.28125 | 4 | NUMBERS = {
5: 'Five',
4: 'Four',
3: 'Three',
2: 'Two',
1: 'One',
}
def main():
for key, value in reversed(NUMBERS.items()):
if key == 1:
print("%s little monkey jumping on the bed" % value)
print("They fell off and bumped their head")
else:
print("%s little monkeys jumping on the bed" % value)
print("One fell off and bumped their head")
print("Mama called the doctor,")
print("And the doctor said")
if key == 1:
print("Put those monkeys right to bed\n")
else:
print("No more monkeys jumping on the bed\n")
if __name__ == "__main__":
main()
|
2a98ffb520d3ba6e11428f187ecebcd36f43c884 | AjayKumar2916/magicwords | /magic_word_1.py | 1,264 | 3.890625 | 4 | #!/usr/bin/env python
import sys, getopt
# Defining Python Command Line Arguments
def main(argv):
jumbled_word = ''
proper_word = ''
# Getting command line argument
try:
opts, args = getopt.getopt(argv,"hj:p:",["jword=","pword="])
except getopt.GetoptError:
print 'usage : python %s -j <jumbled word> -p <proper word>'%(__file__)
sys.exit(2)
# Iterating command line argument
for opt, arg in opts:
# Help Text
if opt == '-h':
print 'usage : python %s -j <jumbled word> -p <proper word>'%(__file__)
sys.exit()
# Jumbled Word Text
elif opt in ("-j", "--jword"):
jumbled_word = arg
# Proper Word Text
elif opt in ("-p", "--pword"):
proper_word = arg
if jumbled_word == "" or proper_word == "":
print 'usage : python %s -j <jumbled word> -p <proper word>'%(__file__)
sys.exit()
else:
print 'Jumbled Word:', jumbled_word
print 'Proper Word:', proper_word
print magic(jumbled_word, proper_word)
# Defining Magic Function
from collections import Counter
def magic(jumbled_word, proper_word):
if not Counter(proper_word) - Counter(jumbled_word):
msg = "Yes, '%s' can be created."%(proper_word)
else:
msg = "No, '%s' can not be created."%(proper_word)
return msg
if __name__ == "__main__":
main(sys.argv[1:]) |
81fc1142c4238003083f5d7bc117017890948ec0 | binaythapamagar/insights-workshop-assignment | /py-assignment-I/functions/8uniquelist.py | 229 | 3.640625 | 4 | def manupulate(words):
for i in range(len(words)):
if i < (len(words)-1) and words[i] == words[i+1] :
del words[i]
return words
print(manupulate([1,2,3,3,3,3,4,5])) |
664221d33396310aa9df1cd067e69bbf65c9c9fc | xiaohao890809/Thread_Python | /Queue.py | 787 | 3.546875 | 4 | # author: xiaohao
# time: 2018.01.30 23:28
from multiprocessing import Process,Queue
import time,random
# 写入进程
def write(q):
for value in ['A','B','C']:
print('put %s to queue...' % value)
q.put(value)
time.sleep(random.random())
# 读取进程
def read(q):
while True:
value = q.get(True)
print('Get %s from queue.' % value)
if __name__ == '__main__':
# 父进程创建Queue,并传给子线程
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子线程pw,写入
pw.start()
# 启动子线程pr,读取
pr.start()
# 等待pw结束
pw.join()
# pr里进程是死循环,无法等待其结束,智能强行终止
pr.terminate()
|
1307f43512c72b49a350b9077f36fe0c6c52e562 | JenZhen/LC | /lc_ladder/company/gg/Open_The_Lock.py | 2,861 | 4.125 | 4 | #! /usr/local/bin/python3
# https://leetcode.com/problems/open-the-lock/submissions/
# Example
# You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'.
# The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'.
# Each move consists of turning one wheel one slot.
# The lock initially starts at '0000', a string representing the state of the 4 wheels.
#
# You are given a list of deadends dead ends, meaning if the lock displays any of these codes,
# the wheels of the lock will stop turning and you will be unable to open it.
# Given a target representing the value of the wheels that will unlock the lock,
# return the minimum total number of turns required to open the lock, or -1 if it is impossible.
#
# Example 1:
# Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
# Output: 6
# Explanation:
# A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
# Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
# because the wheels of the lock become stuck after the display becomes the dead end "0102".
# Example 2:
# Input: deadends = ["8888"], target = "0009"
# Output: 1
# Explanation:
# We can turn the last wheel in reverse to move from "0000" -> "0009".
# Example 3:
# Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
# Output: -1
# Explanation:
# We can't reach the target without getting stuck.
# Example 4:
# Input: deadends = ["0000"], target = "8888"
# Output: -1
# Note:
# The length of deadends will be in the range [1, 500].
# target will not be in the list deadends.
# Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'.
"""
Algo: BFS
D.S.:
Solution:
classical BFS
Time: O(10 ^ 4)
Space: O(10 ^ 4)
Corner cases:
"""
from collections import deque
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
deadends = set(deadends)
q = deque([('0000', 0)])
visited = set(['0000'])
while q:
cur, dist = q.popleft()
if cur == target:
return dist
if cur in deadends:
continue
for nei in self.neighbors(cur):
if nei not in visited:
visited.add(nei)
q.append((nei, dist + 1))
return -1
def neighbors(self, node):
res = []
for i in range(4):
x = int(node[i])
for d in (-1, 1):
nx = (x + d) % 10
res.append(node[:i] + str(nx) + node[i + 1:])
return res
# Test Cases
if __name__ == "__main__":
solution = Solution()
|
a94352b76efb0c58cdac5c58685aa8a65e341bc3 | RichieSong/algorithm | /算法/二叉树/二叉树最大深度.py | 1,026 | 3.765625 | 4 | # coding:utf-8
'''
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
解题思路:
1、递归
2、
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
递归
"""
if not root: return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def maxDepth1(self, root):
"""
:type root: TreeNode
:rtype: int
非递归 没想出来。。。。。。。。。。。。
"""
if not root: return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
|
af2b932d97d7bd688cf253f1c4c7072768c53efb | dip4k/Competitive-Programming | /HackerRank/Data Structures/PrintLinkedListInReverse.py | 1,257 | 4.15625 | 4 | '''
Problem Statement
You are given the pointer to the head node of a linked list and you need to print all its elements in reverse order from tail to head, one element per line. The head pointer may be null meaning that the list is empty - in that case, do not print anything!
Input Format
You have to complete the void ReversePrint(Node* head) method which takes one argument - the head of the linked list. You should NOT read any input from stdin/console.
Output Format
Print the elements of the linked list in reverse order to stdout/console (using printf or cout) , one per line.
Sample Input
1 --> 2 --> NULL
2 --> 1 --> 4 --> 5 --> NULL
Sample Output
2
1
5
4
1
2
Explanation
1. First list is printed from tail to head hence 2,1
2. Similarly second list is also printed from tail to head.
'''
"""
Print elements of a linked list in reverse order as standard output
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
"""
def ReversePrint(head):
a = []
while head!=None:
a.append(head.data)
head = head.next
a.reverse()
for i in xrange(len(a)):
print a[i] |
6bc65c29164b2ff2e7bba134477ece79396f54f8 | LYU-Zhe/Codewars | /Did_I_Finish_my_Sudoku.py | 2,066 | 4.28125 | 4 | """
Write a function done_or_not/DoneOrNot passing a board (list[list_lines]) as parameter. If the board is valid return 'Finished!', otherwise return 'Try again!'
Sudoku rules:
Complete the Sudoku puzzle so that each and every row, column, and region contains the numbers one through nine only once.
Rows:
There are 9 rows in a traditional Sudoku puzzle. Every row must contain the numbers 1, 2, 3, 4, 5, 6, 7, 8, and 9. There may not be any duplicate numbers in any row. In other words, there can not be any rows that are identical.
In the illustration the numbers 5, 3, 1, and 2 are the "givens". They can not be changed. The remaining numbers in black are the numbers that you fill in to complete the row.
Columns:
There are 9 columns in a traditional Sudoku puzzle. Like the Sudoku rule for rows, every column must also contain the numbers 1, 2, 3, 4, 5, 6, 7, 8, and 9. Again, there may not be any duplicate numbers in any column. Each column will be unique as a result.
In the illustration the numbers 7, 2, and 6 are the "givens". They can not be changed. You fill in the remaining numbers as shown in black to complete the column.
Regions
A region is a 3x3 box like the one shown to the left. There are 9 regions in a traditional Sudoku puzzle.
Like the Sudoku requirements for rows and columns, every region must also contain the numbers 1, 2, 3, 4, 5, 6, 7, 8, and 9. Duplicate numbers are not permitted in any region. Each region will differ from the other regions.
In the illustration the numbers 1, 2, and 8 are the "givens". They can not be changed. Fill in the remaining numbers as shown in black to complete the region.
Valid board example:
"""
def done_or_not(board): #board[i][j]
rows = board
cols = [map(lambda x: x[i], board) for i in range(9)]
regions = [board[i][j:j+3]+board[i+1][j:j+3]+board[i+2][j:j+3] for i in range(0,9,3) for j in range(0,9,3)]
for clusters in (rows, cols, regions):
for cluster in clusters:
if len(set(cluster))!=9:
return "Try again!"
return "Finished!"
|
3334a058053fb40f80c608d1e5de684d2fb5a3e0 | mukultaneja/TaskDistributionSystem | /com/itt/tds/thread/threads.py | 1,125 | 4.3125 | 4 |
"""Threading Example in Python"""
# importing modules
from threading import Thread
from _thread import allocate_lock
class ThreadExample(Thread):
"""ThreadExample class inherits Thread module to
make custom threads"""
counter = 0
lock = allocate_lock()
def __init__(self):
"""ThreadExample object Initialization"""
super().__init__(target=None, args=())
def run(self):
"""Override the default Thread's run method"""
ThreadExample.lock.acquire() # acquiring lock over critical section
ThreadExample.counter += 1
f = open(__file__, "r")
for line in f:
print(line)
print(ThreadExample.counter)
ThreadExample.lock.release() # releasing lock over critical section
threads = []
t1 = ThreadExample()
t2 = ThreadExample()
t3 = ThreadExample()
threads.append(t1)
threads.append(t2)
threads.append(t3)
t1.start() # start the overridden run method of ThreadExample
t2.start()
t3.start()
for x in threads:
"""join method makes sure that main thread will
wait to terminate all the threads"""
x.join()
|
1e9d409805f8751f4e66cbaf09ece83e20dbee72 | lauragmz/proyecto-intro-ciencia-de-datos | /transform_data.py | 2,488 | 3.828125 | 4 | # Definición de la función tranformar_minusculas que recibe como argumento un dataframe, convierte a minúsculas la información contenida en cada una de las columnas y devuelve el dataframe con esta modificación.
def transformar_minusculas(df,columnas):
return df.apply(lambda x: x.astype(str).str.lower() if x.name in columnas else x)
# Definición de la función eliminar_signos que recibe como argumento un dataframe con información en minúsculas y aplica las siguientes transformaciones:
# 1. Eliminación de acentos
# 2. Reemplazo de espacios por guiones bajo
# 3. Eliminación de comas, puntos, punto y coma, signos de mas
# 4. Transformación de los "nan" a "NaN"
# y devuelve un dataframe con todas estas modificaciones.
def eliminar_signos(df,columnas):
return df.apply(lambda x: x.astype(str).str.replace('á','a').
str.replace('é','e').
str.replace('í','i').
str.replace('ó','o').
str.replace('ú','u').
str.replace(' ','_').
str.replace(',','').
str.replace('.','').
str.replace(';','').
str.replace('+','').
str.replace('nan','NaN') if x.name in columnas else x)
# Definición de la función estandarizar_datos que recibe como argumento un dataframe, utiliza las dos funciones anteriores para estandarizar (convertir a minúsculas, reemplazar espacios por guiones bajo y eliminar ciertos caracteres) la información de dicho dataframe y deveuelve un nuevo dataframe en formato estandar.
def estandarizar_datos(df):
df_minusculas = transformar_minusculas(df,df.columns)
df_estandar = eliminar_signos(df_minusculas,df_minusculas.columns)
return df_estandar
# Definición de la función eliminar_variables que recibe como argumento una dataframe y una lista con el nombre de las columnas a eliminar; y devuelve el dataframe con las columnas reducidas
def eliminar_variables(df,lista_columnas):
df_reducido =df.drop(lista_columnas, axis =1)
return df_reducido
# Definición de la función convertir_variable que recibe como argumento un dataframe, la columna que quiere transfomarse y el tipo de variable al que desea transformarse; y devuelve un nuevo dataframe con las variables ya transformadas
def convertir_variable(df,columna,tipo_variable):
df_convertido = df.astype({columna:tipo_variable})
return df_convertido |
11ab3d8ba7f6f6c74d020c744b520ec9329bd89d | bopopescu/education | /chapter 2_lists/list2.py | 150 | 4 | 4 | #заставляем списки работать
bobb = ['s','f','a']
www = "sofa"
for letter in www:
if letter in bobb:
print(letter) |
c0a4b16a1d9a2d072892909a4a50def04dc9cb68 | masterzht/note | /other/python/code/2_list.py | 709 | 4.3125 | 4 | # this is the code of list
word=['a','b','c','d','e','f','g']
a=word[2]
print " a is : " +a
b=word[1:3]
print b # index 1 and 2 elements of word.
c=word[:2]
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is "
print d # All elements of word.
e=word[:2]+word[2:]
print "e is :"
print e # All elements of word.
f=word[-1]
print "f is :"
print f # the last elements of word.
g=word[-4:-2]
print " g is :"
print g # index 3 and 4 elements of word.
h=word[-2:]
print " h is :"
print h # the last two elements
i=word[:-2]
print "i is :"
print i # Everything except the last two characters
l=len(word)
print "Length of word is :" + str(l)
print " Adds new element ... "
word.append('h')
print word
|
3b52bf6f3d759b675a594b161f060d42fd0589bd | pisskidney/graphs | /graph.py | 2,868 | 3.53125 | 4 | #!/usr/bin/python
class Vertex():
def __init__(self, identifier):
self.identifier = identifier
self.out = list()
self.inn = list()
@property
def in_deg(self):
return len(self.inn)
@property
def out_deg(self):
return len(self.out)
def __str__(self):
return self.identifier
def out_as_str(self):
return ', '.join([str(e.dest.identifier) for e in self.out])
def in_as_str(self):
return ', '.join([str(e.source.identifier) for e in self.inn])
def __eq__(self, v):
return self.identifier == v.identifier
def __hash__(self):
return hash(self.identifier)
class Edge():
def __init__(self, source, dest, weight=0):
self.source = source
self.dest = dest
self.weight = weight
def __eq__(self, edge):
return (
self.source == edge.source and
self.dest == edge.dest
and self.weight == edge.weight
)
class Graph():
def __init__(self, directed=False):
self.directed = directed
self.vertices = dict()
@classmethod
def from_file(cls, filename, directed=False):
''' If the graph is undirected, it will create a source->dest and
a dest->source edge for the same edge defining pair.
'''
new = cls(directed=directed)
f = open(filename, 'r')
nr_vertices = int(f.readline())
for i in range(1, nr_vertices+1):
new.vertices[i] = Vertex(i)
for line in f:
source, dest = line.split(' ')
source, dest = int(source), int(dest)
e = Edge(new.vertices[source], new.vertices[dest])
new.vertices[source].out.append(e)
new.vertices[dest].inn.append(e)
if not directed:
e2 = Edge(new.vertices[dest], new.vertices[source])
new.vertices[dest].out.append(e2)
new.vertices[source].inn.append(e2)
return new
def as_str(self, redundancy=True):
''' The redundancy param dictates if we need to print both the in and
out going edges in an undirected graph.
'''
output = ''
for k, v in self.vertices.iteritems():
output += '\n(%s)\n' % str(k)
output += 'out: %s\n' % v.out_as_str()
if redundancy or self.directed:
output += 'in: %s\n' % v.in_as_str()
return output
def get_edge(self, v1, v2):
e = Edge(v1, v2)
for edge in self.vertices[v1.identifier].out:
if edge == e:
return edge
return None
def main():
g = Graph.from_file('graph.txt', directed=False)
print g.as_str()
print bool(g.get_edge(Vertex(2), Vertex(1)))
print g.vertices[2].in_deg
if __name__ == "__main__":
main()
|
f802eee1d89a2c901503a5f1056257ec8a044be6 | LeeTann/python-algorithms-practice | /write_numbers_in_expanded_form.py | 610 | 4.46875 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
# NOTE: All numbers will be whole numbers greater than 0.
def expanded_form(num):
result = []
divider = 10
while divider < num:
temp = num % divider
if temp != 0:
result.insert(0, str(temp))
num -= temp
divider *= 10
result.insert(0, str(num))
return "+".join(result)
print(expanded_form(12)) |
8f0951b84980dfa4c09a20e4eb968981dded6185 | plediii/stuff | /js-for-python-programmers/classes.py | 665 | 3.71875 | 4 |
class Foo(object):
def __init__(self, bar):
print 'Creating a new Foo'
self.bar = bar
def zoop(self):
print 'Foo.zoop invoked: bar = ' + self.bar
def zap(self):
print 'Foo.zap invoked: bar = ' + self.bar
class Quux(Foo):
def __init__(self, bar):
print 'Creating a new Quux'
Foo.__init__(self, bar)
def zoop(self):
print 'Quux.zoop invoked. Invoking Foo.zoop...'
Foo.zoop(self)
if __name__ == '__main__':
print 'Starting a python program.'
foo = Foo('baz')
foo.zoop()
foo.zap()
quux = Quux('quuxBaz')
quux.zoop()
quux.zap()
|
c3f775501d56ef9945ea6171e8bdbc82f6117bbe | IngridDilaise/programacao-orientada-a-objetos | /listas/lista-de-exercicio-07/questao08.py | 1,110 | 3.625 | 4 | class Tamagotchi:
def __init__(self,nome):
self.nome=nome
self.fome=10
self.saude=10
self.idade=0
def alterar_nome(self,novo_nome):
self.nome=novo_nome
def retornar_fome(self):
return self.fome
def retornar_saude(self):
return self.saude
def retornar_idade(self):
return self.idade
def comer(self):
if self.fome==10:
self.fome-=1
print("sua fome apos comer é: ",self.fome)
else:
print(self.fome)
def tomar_injecao(self):
if self.saude<21:
self.saude+=1
print("Sua saude apos tomar injecao é: ",self.saude)
else:
print(self.saude)
def envelhecer(self):
if self.saude>0:
self.saude-=1
print("a sua saude apos envelhecer é: ",self.saude)
else:
print(self.saude)
if self.idade==0:
self.idade+=1
print(self.saude)
else:
print(self.idade)
def imprimir(self):
print(f"nome:{self.nome},fome:{self.fome},saude:{self.saude},idade:{self.idade}")
tamagotchi1=Tamagotchi("isae")
tamagotchi1.imprimir()
tamagotchi1.comer()
tamagotchi1.tomar_injecao()
tamagotchi1.envelhecer()
|
8fe1b50f9fe5406858d8c25a6f4100db04d88c05 | WGJBV/data-structures-and-algorithms | /largest-product-array.py | 203 | 3.609375 | 4 | def largest_product_array():
product = 0
array = [[1,2][3,4][5,6][7,8]]
for i in len(array):
if array[i][0] * array[i][0] > product:
product = array[i][0] * array[i][0]
return product
|
9e157e9a168555d23b84d6cf0ee14df2d54c907d | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4175/codes/1716_2506.py | 208 | 3.671875 | 4 | x = float(input("x: "))
y = float(input("y: "))
w = float(input("w: "))
t = 0
y = y/100
while 0<x<12000:
a = x*y
x = a + x
x = x - w
t += 1
if x <= 0:
print("EXTINCAO")
else:
print("LIMITE")
print(t) |
f6b458de517ee80a20f3e3f4d36b6ea1bcb47a83 | larsx2/devz-ctci-challenge | /python/chapter_01/03_permutation.py | 547 | 3.734375 | 4 | import unittest
import random
def randomize(s, as_list=False):
l = list(s)
random.shuffle(l)
return l if as_list else ''.join(l)
class TestPermutation(unittest.TestCase):
def test_solution(self):
s = "abcdeff"
for _ in xrange(100):
self.assertTrue(is_permutation(s, randomize(s)))
for _ in xrange(100):
l = randomize(s, as_list=True)
l.pop()
self.assertFalse(is_permutation(s, ''.join(l)))
def is_permutation(a, b):
return sorted(a) == sorted(b)
|
512414eceefa7c4ef977442cd619fd857265cea9 | Lyc1103/Aritificial-Intelligence_Path-Finding-of-Maze | /mazeMaker.py | 1,165 | 3.625 | 4 | import numpy as np
import sys
# Global Variable
# np.random.seed(1)
# needs to small than 1000 x 1000
hight = 10
width = 10
maze = [[0] * width for i in range(hight)]
def PrintMaze(m):
for i in range(hight):
for j in range(width):
print(m[i][j] + " ", end='')
print()
# end func PeintMaze
def MazeMaker(maze, h, w):
for i in range(h):
for j in range(w):
if i == 0 or j == 0 or i == h-1 or j == w-1:
maze[i][j] = '*'
# Set no solution statement
# elif (i == h - 3 and j == w-2) or (i == h - 2 and j == w-3):
# maze[i][j] = '*'
else:
tmp = int(np.random.random()*12)
if tmp >= 10:
maze[i][j] = '*'
else:
maze[i][j] = str(tmp)
# end func MazeRandCreate
if __name__ == '__main__':
MazeMaker(maze, hight, width)
print("The maze is :")
PrintMaze(maze)
with open("input.txt", mode="w") as file:
for i in range(hight):
for j in range(width):
file.write(str(maze[i][j]))
file.write('\n')
|
014928cfac8d3c498b72c5c24f4b1af587217b2e | ToshineeBhasin/Python-Programs | /numbrGuessing.py | 1,218 | 4.03125 | 4 | import random
import math#taking inputs
lower = int(input("Enter lower limit : "))
upper = int(input("Enter upper limit : "))
x = random.randint(lower,upper)
print("\n \tYou have only ",round(math.log(upper - lower +1, 2 )), "Chances to guess the integer !\n")
#initializing no of guess
count = 0
#minimum no of guess depend upon range
while count < math.log(upper - lower +1,2):
count += 1
#taling guessing number as input
guess = int(input("Guess a number : "))
#condition testing
if x == guess:
print("Congralutions you did it in ",count," try ")
break
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You guessed too high!")
#if guesses is more the required guesses
if count >= math.log(upper - lower + 1, 2):
print("\nThe number is %d " % x)
print("\tBetter Luck Next Time!")
'''
Enter lower limit : 2
Enter upper limit : 20
You have only 4 Chances to guess the integer !
Guess a number : 6
You guessed too small!
Guess a number : 10
You guessed too small!
Guess a number : 15
You guessed too small!
Guess a number : 20
Congralutions you did it in 4 try
''' |
61dfc770812a67011c0759d602d4edcca5f104e7 | mohanrajanr/CodePrep | /lhs.py | 629 | 3.53125 | 4 | from typing import List
def findLHS(nums: List[int]) -> int:
currValue = 0
longestValue = 0
minv = maxv = nums[0]
for i in range(1, len(nums)):
minv = maxv = nums[i]
currValue = 0
for j in range(i-1, -1, -1):
minv = min(minv, nums[j])
maxv = max(maxv, nums[j])
if maxv - minv == 1:
currValue += i - j
print(nums[j], nums[i], minv, maxv, currValue)
longestValue = max(longestValue, currValue)
return longestValue
print(findLHS([1,3,2,2,5,2,3,7]))
# print(findLHS([1,2,3,4]))
# print(findLHS([1,1,1,1]))
|
d13c919d2a04998ec1b85fb62731ca2ea171e7d5 | sanislav/homework | /coursera/algorithms_2/01/p_01_02/greedy.py | 2,549 | 4 | 4 | """In this programming problem and the next you'll code up the greedy algorithms
from lecture for minimizing the weighted sum of completion times.. Download
the text file here. This file describes a set of jobs with positive and
integral weights and lengths. It has the format
[number_of_jobs]
[job_1_weight] [job_1_length]
[job_2_weight] [job_2_length]
...
For example, the third line of the file is "74 59", indicating that the second
job has weight 74 and length 59. You should NOT assume that edge weights or
lengths are distinct.
1. Your task in this problem is to run the greedy algorithm that schedules jobs in
decreasing order of the difference (weight - length). Recall from lecture that
this algorithm is not always optimal. IMPORTANT: if two jobs have equal
difference (weight - length), you should schedule the job with higher weight
first. Beware: if you break ties in a different way, you are likely to get the
wrong answer.
2.For this problem, use the same data set as in the previous problem. Your task
now is to run the greedy algorithm that schedules jobs (optimally) in decreasing
order of the ratio (weight/length). In this algorithm, it does not matter how you
break ties.
"""
# Create a list of tuples (weight, length)
def create_weights_and_lengths_lists():
jobs = []
count = 0
for line in open('jobs.txt', 'r'):
if(count > 0):
vals = line.split()
jobs.append((int(vals[0]), int(vals[1])))
count += 1
return jobs
# Sort list of tuples
def schedule_jobs(jobs, greedy_rule, handle_ties):
jobs.sort(key = handle_ties)
jobs.sort(key = greedy_rule)
return jobs
def sum_of_weighted_completion_times( jobs ):
time = 0
sum = 0
for w, l in jobs:
time += l
sum += w * time
return sum
def main():
# parse the file and create a list of tuples [(w1,l1)...]
jobs = create_weights_and_lengths_lists()
# order by weight - length in decending order.
# will not be optimal and should yeld a > reult than greedy_2
greedy_1 = lambda tuple: -(tuple[0] - tuple[1])
# sort by w / l in descending order
greedy_2 = lambda tuple: -float(tuple[0])/tuple[1] # always correct
# for ties sort by weight in descending order
handle_ties = lambda tuple: -tuple[0]
# sort jobs
jobs = schedule_jobs( jobs, greedy_1, handle_ties )
print 'Greedy w - l: %i' % sum_of_weighted_completion_times(jobs)
jobs = schedule_jobs( jobs, greedy_2, handle_ties )
print 'Greedy w / l: %i' % sum_of_weighted_completion_times(jobs)
if __name__ == '__main__':
main()
|
76db04758225da604537a3159bd02159bd774f6f | yuueuni/algorithm | /WarmUp/PlusMinus.py | 569 | 3.828125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr, n):
plus, minus, zero = 0, 0, 0
for i in range(n):
if arr[i] > 0:
plus += 1
elif arr[i] < 0:
minus += 1
else:
zero += 1
answer = str(round(plus/n, 6)) + "\n" + str(round(minus/n, 6)) + "\n" + str(round(zero/n, 6))
print(answer)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
|
778d77ac7fbd580f9eb9cc0264b5f17ebb10e87a | wolima/python | /exercicios/ex.py | 1,469 | 3.796875 | 4 | #Exercicio 1#
x = input()
for i in x:
print(str(i).lower())
#Exercicio 2#
lista = []
for i in range(3):
lista.append(input())
print(max(lista))
print(min(lista))
theSum = 0
for i in lista:
theSum = theSum + int(i)
print(theSum)
#Exercicio 3#
for i in range(10,100):
if i%5 == 0:
print(i)
#Exercicio 4#
def fun(numero,expoente=2):
temp = 1
for i in range(expoente):
temp *= numero
return temp
print(fun(2))
print(fun(10))
print(fun(2,9))
#Exercicio 5#
def fun(*numeros):
lista = []
for x in numeros:
lista.append(x*x)
return lista
print(fun(10,5,8,4))
#FLOWERS PROBLEMA DA AULA 2 #
class Flower(object):
def __init__(self, ide,sepal_length_cm,sepal_width_cm,petal_length_cm,petal_width_cm,species):
self.ide = ide
self.sepal_length_cm = sepal_length_cm
self.sepal_width_cm = sepal_width_cm
self.petal_length_cm = petal_length_cm
self.petal_width_cm = petal_width_cm
self.species = species
def __str__(self):
return "Especie: " + str(self.species)+"\n"+"Sepal Lenght: " + str(self.sepal_length_cm)+"\n"+"Sepal Width: " + str(self.sepal_width_cm)+"\n"+"Petal Lenght: " + str(self.petal_length_cm)+"\n"+"Petal Width: " + str(self.petal_width_cm)+"\n"
if __name__ == '__main__':
flowers = []
linhas = open('iris.data');
array = []
i = 0;
for line in linhas:
x = line.replace("\n","")
x = x.split(",")
if(len(x) > 4):
flowers.append(Flower(i,x[0],x[1],x[2],x[3],x[4]))
i = i+1
for a in flowers:
print(a)
|
63f87417ca5a09c5a40839ee1697e34fe98b1a53 | fanyuan1/Project-E | /problem_12.py | 565 | 3.53125 | 4 | from math import sqrt
from functools import reduce
def factorize(n):
for i in range(2,int(sqrt(n)+1)):
if (n%i == 0):
if i in factors:
factors[i] += 1
else:
factors[i] = 1
return factorize(n//i)
if n in factors:
factors[n] += 1
else:
factors[n] = 1
i = 0
j = 0
while 1:
j += 1
i += j
factors = {}
factorize(i)
if(reduce(lambda x, y: x * (y+1), list(factors.values()),1)>500):
print(i)
break |
d7e7e790517d35167b597d78a9b460e2e4f19303 | scuate/MOOC | /data_wrangle/src/parse_csv.py | 864 | 3.734375 | 4 | ##parse csv file, store all the data in a list
import csv
import os
DATADIR = ""
DATAFILE = "745090.csv"
# csv.reader creates an iterable object, "for" loop calls next() function every time and a list is created for each row
def parse_file(datafile):
name = ""
data = []
counter = 1
with open(datafile,'rb') as f:
datareader = csv.reader(f)
for line in datareader:
if counter == 1:
name = line[1]
elif counter > 2:
data.append(line)
counter += 1
return (name, data)
def test():
datafile = os.path.join(DATADIR, DATAFILE)
name, data = parse_file(datafile)
assert name == "MOUNTAIN VIEW MOFFETT FLD NAS"
assert data[0][1] == "01:00"
assert data[2][0] == "01/01/2005"
assert data[2][5] == "2"
if __name__ == "__main__":
test()
|
9aea83b6c76f185fc9ef6f571b3b29e86d54f055 | JavaGoodDay/Projects | /First.py | 284 | 3.96875 | 4 | Maths =80
Chemistry=100
Physics=100
Total=Maths+Chemistry+Physics
Per=Total*100/450
print()
print()
print("the chemistry result is",Chemistry)
print("the maths result is",Maths)
print("the physics result is",Physics)
print()
print("Percentage",Per)
print("the total result is",Total) |
bf2a31dca1de2438463c19bb03cabf6ef4c2fe8d | tinmaker/ekf | /thread.py | 887 | 3.53125 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
a=100
lock = threading.Lock()
def print_time1( threadName, delay):
global a
while 1:
time.sleep(1)
lock.acquire()
a +=1
lock.release()
print "%s: %s" % (threadName, time.ctime(time.time()) )
def print_time2( threadName, delay):
global a
while 1:
time.sleep(1)
lock.acquire()
print "%d, %s: %s" % (a, threadName, time.ctime(time.time()) )
lock.release()
def main():
try:
t1 = threading.Thread(target=print_time1, name='LoopThread', args=('LoopThread1',1,))
t2 = threading.Thread(target=print_time2, name='LoopThread', args=('LoopThread2', 1,))
except:
print "Error: unable to start thread"
t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
t2.start()
# t2.join()
count = 0
while 1:
time.sleep(1)
count +=1
if count>10:
break
if __name__ == '__main__':
main()
|
a8c8f5d3c3f6334cd3dba7a9a08a8284d1b9dcef | hoodielive/pythonnerd | /algorithms/array-lessons/list-array.py | 639 | 4.3125 | 4 | # one-dimensional
one_dimensional_array = [1,2,3,4,5]
print(one_dimensional_array[0]) # O(1) -> if you specify index
# two-dimensional
two_dimensional_array = [1, 2, 300, 3, 4, 5]
# for loop O(n)
for num in two_dimensional_array:
print(num);
# insert O(n)
two_dimensional_array[1] = "Insert"
# for loop O(n)
for i in range(len(two_dimensional_array)):
print(two_dimensional_array[i])
# print first 2 indices O(1)
print(two_dimensional_array[0:2])
# Linear search maximum O(n)
maximum = numbers[0]
for num in two_dimensional_array:
if num > maximum:
maximum = num
print(maximum)
print(one_dimensional_array)
|
53fecb2c72c3714efc1f886d8be1419590390dcf | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_xke_C.py | 3,642 | 3.65625 | 4 | import math
inputfile = open('C-large.in')
outputfile = open('C-large.out.txt', 'w')
# returns 0 if a prime number
# returns a divisor otherwise
# adaptation of
# https://www.daniweb.com/programming/software-development/code/216880/check-if-a-number-is-a-prime-number-python
def is_non_prime_get_divisor(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return False
# all other even numbers are not primes
if not n & 1:
return 2
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return x
return False
# intBase would be from 2 to 10, inclusive
def get_base_result(strCoin, intBase):
return int(strCoin, intBase) # easy python way :) though below will work
#lenCoin = len(strCoin)
#listCoin = list(strCoin)
#baseResult = 0
#for i in range(lenCoin):
# baseResult = baseResult + (int(listCoin[lenCoin-1-i]) * (intBase ** i))
#return baseResult
def is_jamcoin_get_proof(strCoin):
lenCoin = len(strCoin)
if len(strCoin) < 2:
return False # jamcoin too short
listCoin = list(strCoin)
if listCoin[0] != '1' or listCoin[lenCoin-1] != '1':
return False # jamcoin not both 1's at end
for i in range(lenCoin):
if listCoin[i]!='1' and listCoin[i]!='0':
return False
# now, just need to check the prime-ness
proofString = strCoin
for b in range(2, 11): # 2 to 10 inclusive
baseResult = get_base_result(strCoin, b)
divisor = is_non_prime_get_divisor(baseResult)
if divisor == False:
return False # it's prime; non-jamcoin
else:
proofString = proofString + " " + str(divisor)
return proofString
# Function for coming up w jamcoins. Criteria:
# - Every digit is either 0 or 1.
# - The first digit is 1 and the last digit is 1.
# - If you interpret the string in any base between 2 and 10, inclusive, the resulting number is not prime.
def output_jamcoins(N, J):
#N = int length of Jamcoin string, >=2
#J = int number of Jamcoins to print. Guaranteed to exist for N.
# method: come up with variations of length N, and then see if it's a Jamcoin
# variations must start w 1 and end with 1, which leaves N-2 variable chars
variationChars = N-2
numVariations = 2 ** (N-2)
variationInt = 0 # this will turn into a string
variationFormatter = "{0:0" + str(variationChars)+"b}"
numJamcoins = 0
strOutput = ""
while numJamcoins < J:
strCoin = "1" + variationFormatter.format(variationInt) + "1"
#print strCoin
#raw_input("Press Enter to continue...")
variationInt = variationInt + 1 # keep varying until J jamcoins found!
proof = is_jamcoin_get_proof(strCoin)
if proof==False:
#print "-"
continue
else:
#print "-"
strOutput = strOutput + proof + "\n"
numJamcoins = numJamcoins + 1
return strOutput
# --------------------------------------------
#skip first line
#next(inputfile)
#read first line:
num_cases = int(inputfile.readline())
for i in range(0, num_cases):
line = inputfile.readline()
# parse line: N J
numbers = line.split()
N = int(numbers[0])
J = int(numbers[1])
output_line = "Case #" + str(i+1) + ":\n" + output_jamcoins(N, J)
print output_line
outputfile.writelines(output_line)
inputfile.close()
outputfile.close()
|
9b6540d151fb36a2bfb4deddc9e66ea6e01e2f5f | kishan3/leetcode_solutions | /72.py | 925 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 2 16:29:34 2019
@author: kishan
"""
def edit_distance_between_two_strings(str1, str2):
len1 = len(str1)
len2 = len(str2)
if len1 == 0 or len2 == 0:
return len1 + len2
dist = [[0 for _ in range(len2 + 1)] for _ in range(len1 + 1)]
for i in range(len1 + 1):
dist[i][0] = i
for j in range(len2 + 1):
dist[0][j] = j
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
up = dist[i - 1][j]
left = dist[i][j - 1]
up_left = dist[i - 1][j - 1]
if str1[i - 1] == str2[j - 1]:
dist[i][j] = min(left, up, up_left)
else:
dist[i][j] = min(left, up, up_left) + 1
return dist[len1][len2]
edit_distance_between_two_strings("horse", "rose")
edit_distance_between_two_strings("intention", "execution")
|
ea270252970ef3d515771c66af14aeaba32f225e | pomegranate66/coderLife | /September/左旋转字符串.py | 1,043 | 3.71875 | 4 | class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
'''
s : 输入的字符串
n : 从第几位开始旋转
例子:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
分析:
1、拆分成为两个字符串,然后再把这两个字符串做一个拼接
算法流程:
1、找到需要拆分的地方,用索引拆分
2、将两个字符串倒序拼接,使用''.join()
'''
# 将str拆分开,然后合并成新的列表并转化字符串
# part_1 = s[:n]
# part_2 = s[n:]
# result = []
# for i in part_2:
# result.append(i)
# for i in part_1:
# result.append(i)
# return ''.join(result)
# 将str拆分开,然后每部分各自转化成字符串,最后字符串拼接
return str(s[n:])+str(s[:n]) |
fbe548294c7c9806ca42f34cbdd19f7d28ffb5c0 | michalfoc/python | /python/ex20.py | 1,328 | 4.40625 | 4 | # Ex20. Functions and files
# a program using functions to work on files
from sys import argv
script, input_file = argv
# define few functions
# def, function name, (function arguments), COLON!!!
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline(), end= '')
# now a variable to store file contents
current_file = open(input_file)
print("First, let's print the whole file:")
# call a function on the file which content is stored in a variable
print_all(current_file)
print("Now, lets rewind the file, kind of like a tape.")
# now, call rewind function on the file, so read position is back at the beginning (0-byte)
rewind(current_file)
print("Let's print 3 lines:")
# assign a value to a variable, that will be displayed before the line's content
current_line = 1
# now call a function using the variable and .readline() command, which reads only one line from read position.
print_a_line(current_line, current_file)
current_line += 1
# '+=' is used when we wwant to increment left side with right side and assign the result to the left side as it's new values
# essentially, it is equivalent to "current_line = current_line + 1"
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
|
f3f5b1c5fd3e21258f3eec7f58fa771e17cc7ce3 | RasmusBuntzen/Python-for-data-science | /Projekter/Øvelser/String Øvelse 1+2.py | 443 | 3.609375 | 4 | #Øvelse 1
First_name = "Rasmus"
Last_name = "Buntzen"
Age = 22
print("Name: " + First_name + " " + Last_name + "\nAge: "+ str(Age))
#Øvelse 2
DNA = "AAGCAGAATGCTTAGGACTAGTTAC"
RNA = DNA.replace("T","U")
print("DNA sekvensen :"+DNA)
print("RNA sekvensen :"+RNA)
print("Længden af RNA sekvensen er: "+ str(len(RNA)) + "\nDen miderste base er: " +RNA[len(RNA)//2]) #I use // because the length is uneven and therefore return a float
print("") |
6ea70a3ff2989b81cbbc078fb04876b4133cf07c | acrip/PythonMisionTIC | /Clase9_19MAY21/listasCompuestas.py | 1,672 | 3.984375 | 4 | #listaCompuesta = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
#print(listaCompuesta)
#print(listaCompuesta[0])
#print(listaCompuesta[0][0])
#print(listaCompuesta[2][2])
#print()
#for i in range(len(listaCompuesta[0])):
# print(listaCompuesta[0][i])
#for i in range(len(listaCompuesta)):
# for j in range(len(listaCompuesta[i])):
# print(listaCompuesta[i][j])
# print()
# 1. Crear una lista con 2 elementos, cada elemento será una lista de 5 enteros,
# calcular y mostrar la suma de los elementos
#listaEnteros = [[1,2,3,4,5],[6,7,8,9,10]]
#suma = 0
#for i in range(len(listaEnteros)):
# for j in range(len(listaEnteros[i])):
# suma += listaEnteros[i][j]
#
#print(suma)
# 2. Definir 2 listas de 3 elementos (Todos los valores ingresados por teclado)
# - En la primera lista cada elemento tendrá como sublista, el nombre del padre y la madre de una familia.
# - La segunda lista tendrá sublistas con nombres de los hijos de cada familia, pueden haber familias sin hijos.
# - Imprimir los nombres del padre, la madre y sus hijos.
listaPadres = []
listaHijos = []
for i in range(3):
listaPadres.append([input("Ingrese el nombre del padre de la familia " + str(i + 1))], [input("Ingrese el nombre de la madre de la familia " + str(i))])
cantidadHijos = input("Ingrese la cantidad de hijos de la familia " + str(i + 1))
for j in range(cantidadHijos):
listaHijos[i].append(input("Ingrese el hijo "+ str(j + 1)+" para la familia" + str(i + 1)))
print(listaPadres)
print(listaHijos)
#listaPadres = [["juan", "maria"], ["carlos", "sandra"], ["felipe", "isabela"]]
#listaHijos = [["Sebastian, Camila"], [], ["Cristian"]] |
a9888e0784807ff05149ddd4871ecfb9af53ba1c | Karamba278/DZP1 | /max_number.py | 396 | 3.640625 | 4 | n= int(input('Введите целое положительное число '))
n_hist=n
if n < 10:
print ('Вы ввели число с единственной цифрой')
else:
n2 = n % 10
n = n // 10
while n > 0:
if n % 10 > n2:
n2 = n % 10
n = n // 10
print('Максимальная цифра в числе ', n_hist, '- ', n2)
|
30089834599c0c9d1b82641f4608d2dfde20ba66 | tcano2003/ucsc-python-for-programmers | /code/lab_04_Sequences/lab04_2(3)_TC.py | 631 | 4.15625 | 4 | #!/usr/bin/env python3
""" Ask the user for exactly 5 words, one at a time. After
each word is collected from the user, print it only if it
is not a duplicate of a word already collected.
"""
def AskForAndPrintUniqueWords(number_of_words):
words = []
for loop in range(number_of_words): #range is the number of words specified when the function is called
new_word = input("Word please: ")
if not new_word:
break
if not new_word in words:
print(new_word)
words += [new_word] # can also words.append[new_word]
def main():
AskForAndPrintUniqueWords(5)
main()
|
6eaeb4be50a3d4b59cfa8cc547e0d4c0f532348a | ridwanrahman/datastructures | /Arrays/problems/permutation.py | 344 | 3.9375 | 4 | # Q: Permutation
def permutation(list1, list2):
if len(list1) != len(list2):
return False
list1.sort()
list2.sort()
if list1 == list2:
return True
return False
def main():
list1 = [1,2,3]
list2 = [3,2,2]
print(permutation(list1, list2))
if __name__ == "__main__":
main()
|
918462d60e20c1c31fa6931dd74eddb6a00ef497 | NoneNgai/Codium-Test | /leapyear.py | 510 | 4.28125 | 4 | #2. Write a program that determine whether or not an integer input is a leap year.
def leap(year):
if(year % 400 == 0):
print(str(year) + " -> true")
elif(year % 4 == 0 and year % 100 != 0):
print(str(year) + " -> true")
else:
print(str(year) + " -> false")
while(1):
x = int(input("Check leap year : "))
if(x>=0):
leap(x)
elif(x==-1):
break;
else:
x = int(input("Leap year cannot be negative, please enter new leap year : "))
|
6e3ffc6001fecb75a9e22462f859fd9e030c9b81 | 2001052820/Actividades-de-Python | /funciones2.py | 396 | 4.03125 | 4 | def conversacion(mensaje):
print("Hola")
print("Cómo estás")
print(mensaje)
print("Adios")
opcion = int(input("Elige una opción (1,2,3): "))
if opcion == 1:
conversacion("Elegiste la opcion 1")
elif opcion ==2:
conversacion("Elegiste la opcion 2")
elif opcion ==3:
conversacion("Elegiste la opcion 3")
else:
print("Escribe la opción correcta")
|
42d7d4c4015d52a11a9a63514976507b8633926c | vitorbarros/byu-cse110 | /w13/13_prove_assignment.py | 690 | 4.09375 | 4 | def wind_chill(temperature, wind_speed):
return 35.74 + (0.6215 * temperature) - 35.75 * (wind_speed ** 0.16) + 0.4275 * temperature * (wind_speed ** 0.16)
def convert_to_fahrenheit(value):
return value * (9 / 5) + 32
def wind_speed_loop():
return
temp_input = int(input('What is the temperature? '))
unit_input = input('Fahrenheit or Celsius (F/C)? ')
temp = 0
times = 12
for t in range(12):
step = (t + 1) * 5
if unit_input.lower() == 'c':
temp = convert_to_fahrenheit(temp_input)
else:
temp = temp_input
wind = wind_chill(temp, step)
print(f'At temperature {temp:.2f}F, and wind speed {step} mph, the windchill is: {wind:.2f}F')
|
140252035a9196c8a4a60f2fe23d874069447b7a | TypMitSchnurrbart/DACH_TEST | /scripts/files/get_data.py | 4,676 | 3.59375 | 4 | #!/usr/bin/python3
#!-*- coding: utf-8 -*-
from files.const import DATA_HANDLE
#-----------------------------------------------------------------------------------------------------------------------------------
def get_user_data(activ_uid, string1, string2 = None, string3 = None):
"""
Function to ask user data from the Database easily
param: {int} activ_uid; input data
param: {string} string1; requested column name
param: {string} string2; OPTIONAL
param: {string} string3; OPTIONAL
return: {string/int/date} Requested Data in requested order
"""
#TODO Use this Code for the get user info for App
if string2 is None and string3 is None:
DATA_HANDLE[0].execute(f"SELECT {string1} FROM user WHERE user.uid = {activ_uid}")
result = DATA_HANDLE[0].fetchall()
return result[0][0]
elif string3 is None:
DATA_HANDLE[0].execute(f"SELECT {string1}, {string2} FROM user WHERE user.uid = {activ_uid}")
result = DATA_HANDLE[0].fetchall()
return result[0][0], result[0][1]
else:
DATA_HANDLE[0].execute(f"SELECT {string1}, {string2}, {string3} FROM user WHERE user.uid = {activ_uid}")
result = DATA_HANDLE[0].fetchall()
return result[0][0], result[0][1], result[0][2]
#-----------------------------------------------------------------------------------------------------------------------------------
def get_user_id(data_array):
"""
Getting the uid to email/ident from data_array
param: {array} data_array; input from http
return: {int} uid; user id in DB
"""
for i in range(0, len(data_array)):
if data_array[i][0] == "email":
given_email = data_array[i][1]
break
elif data_array[i][0] == "ident":
#TODO This will have to be changed; ident will be hash value of the email! Different Case if ident is our hash value!!
given_email = data_array[i][1]
break
DATA_HANDLE[0].execute(f"SELECT uid FROM user WHERE user.email LIKE '{given_email}'")
result = DATA_HANDLE[0].fetchall()
return result[0][0]
#-----------------------------------------------------------------------------------------------------------------------------------
def get_last_room(activ_uid, from_json = False):
"""
Getting the Last visited Room of a Person
param: {int} activ_uid user_id of current user
return: {string} last_room last visited room of user
"""
#TODO try/except with error codes!
#Getting last visited room_id
DATA_HANDLE[0].execute(f"SELECT room FROM movement WHERE person = {activ_uid} ORDER BY move_id DESC LIMIT 1;")
result = DATA_HANDLE[0].fetchall()
#Translate room_id to room description as string, can be empty set
if result != []:
DATA_HANDLE[0].execute(f"SELECT description FROM room WHERE room_id = {result[0][0]}")
result = DATA_HANDLE[0].fetchall()
return result[0][0]
else:
if from_json is False:
return " - "
else:
return "$false$"
#-----------------------------------------------------------------------------------------------------------------------------------
def get_visited_rooms(activ_uid, from_json = False):
"""
Get the five last visited rooms with date and times
param: {int} activ_uid uid from activ user
return: {array} visited_rooms array with all visited rooms, can have index in range 0, 4! According output
"""
#TODO try/excepts
#Get last visited rooms; max. amount = 5
DATA_HANDLE[0].execute(f"""SELECT description, DATE_FORMAT(date, '%d.%m.%Y'), TIME_FORMAT(begin, '%H:%i'), TIME_FORMAT(end, '%H:%i') FROM movement JOIN room ON movement.room = room.room_id
WHERE person = {activ_uid} AND end IS NOT NULL ORDER BY move_id DESC LIMIT 5""")
result = DATA_HANDLE[0].fetchall()
if result != []:
return result
elif from_json is True and result == []:
mock_array = [["$false$", "$false$", "$false$", "$false$"]]
return mock_array
elif from_json is False and result == []:
mock_array = [[" - ", " - ", " - ", " - "]]
return mock_array
#-----------------------------------------------------------------------------------------------------------------------------------
def get_number_of_users():
"""
Get the number of registered users from DACH
return: {int} Number of registered users
"""
DATA_HANDLE[0].execute(f"SELECT count(uid) FROM user")
result = DATA_HANDLE[0].fetchall()
return result[0][0] |
1364daed164faeb07a25230cdef379f91a4e1aa9 | Damnstein/conversor-monetario | /conversor_dol.py | 208 | 3.796875 | 4 | dolars = input("How many dolars you have?: ")
dolars = float(dolars)
peso_value = 74
pesos = dolars * peso_value
pesos = round(pesos, 2)
pesos = str(pesos)
print("You have " + pesos + " pesos from Argentina") |
f4fe4897397f64aa99f5266cf457800c8126983b | Prashast07/Python-Projects | /merge2arrInDescOrder.py | 510 | 3.953125 | 4 | # n = size of array1
# m = size of array2
def merge(array1, array2, n, m):
x = 0
y = 0
result = []
k = 0
while (x < n) and (y < m):
if array1[x] > array2[y]:
result.append(array1[x])
x += 1
else:
result.append(array2[y])
y += 1
while x < n:
result.append(array1[x])
x += 1
while y < m:
result.append(array2[y])
y += 1
for i in result:
print (i, end=" ")
print("") |
bd5d7f44925eedea757b39054a595ee2a9f0fb4f | lookfiresu123/Interacive_python | /calculator.py | 1,322 | 3.84375 | 4 | # Application : Calculator
# Data: Store, Operand
# Print, Swap, Add, Subtract, Multiple, Divide
# calculator layout
# left: Control area
# right: Canvas
# import modules
import simpleguitk as simplegui
# initalize globals
store = 0
operand = 0
# define functions that manipulate store and operand: a helper function
def output():
print "Store = ", store
print "Operand = ", operand
print ""
# define a function that swap between store and operand: an event handler
def swap():
global store, operand
store, operand = operand, store
output()
def add():
global store, operand
store += operand
output()
def sub():
global store, operand
store -= operand
output()
def mul():
global store, operand
store *= operand
output()
def div():
global store, operand
store /= operand
output()
def enter(input):
global operand
operand = float(input)
output()
# create frame
frame = simplegui.create_frame("calculator", 300, 300)
# register events into frame
frame.add_button("Print", output, 100)
frame.add_button("Swap", swap, 100)
frame.add_button("Add", add, 100)
frame.add_button("Sub", sub, 100)
frame.add_button("Mul", mul, 100)
frame.add_button("Div", div, 100)
frame.add_input("Enter operand", enter, 100)
# start frame
frame.start()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.