blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
fb29118b8e9297a336ec14c4af2aaea9e491cf12
|
blogart/Python
|
/archivos externos/manejo_archivos.py
| 1,745 | 3.65625 | 4 |
#Primero que hay que hacer es importar el modulo io que nos permite manejar los archivos externos
from io import open #se está importando solo el método open
#argumentos(nombre del archivo, w de white para abrirlo en modo escritura )
archivo_texto=open("archivo.txt", "w") #se está creando un archivo desde aquí
frase="No veas loco que flama esto del python \nflamón"
archivo_texto.write(frase)#manipulación del archivo
archivo_texto.close() #una vez de manipula hay que cerrar el archivo abierto en memoria desde python
archivo_texto=open("archivo.txt", "r")
#para leer la infor que hay en el archivo se puede crear una variable para almacenar lo que se leer
leer=archivo_texto.read()
archivo_texto.close()
print(leer)
archivo_texto=open("archivo.txt", "r")
lineas_texto=archivo_texto.readlines() #conviertes el archivo de texto en una lista manipulable.
#cada línea de texto en un elemento de la lista.
archivo_texto.close()
print(lineas_texto) #te imprime una lista
print(lineas_texto[0])
archivo_texto=open("archivo.txt", "a") #modo append para añadir una nueva línea.
archivo_texto.write("\ncon el append este añades cosas al archivo asi por arte de magia")
archivo_texto.close()
archivo_texto=open("archivo.txt", "r")
print(archivo_texto.read())
#Modificar la posición de un puntero dentro del texto con el método seek(número de caracter donde se situa)
#Desplaza nuevamente el puntero a la posición que le digas en este caso a la 5
archivo_texto.seek(15)
print(" ")
print(archivo_texto.read())#si incluyes en read() un parámetro se detiene en la posición que le digas
archivo_texto.seek(0)
archivo_texto.seek(len(archivo_texto.read())/2)# Devuelve la mitad del texto
print(archivo_texto.read())
|
dcbcee9ea8da62dffea2d0a316f0ed71dd91568f
|
PrakashPrabhu-M/pythonProgramsGuvi
|
/positionOfLast_1.py
| 329 | 3.984375 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 05:11:52 2019
@author: Hp
"""
'''
Print the position of first 1 from right to left, in binary representation of an Integer.
Sample Testcase :
INPUT
18
OUTPUT
2
'''
a="{:b}".format(int(input()))
print(a)
b=a[::-1]
i=b.index("1")+1
#print(len(a)-i)
print(i)
|
dbcc71d3785c5806c649906f4f2026094cae1cef
|
kldxz123/Leetcode
|
/31/nextPermutation.py
| 775 | 3.5 | 4 |
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 1
while i > 0 and nums[i-1] >= nums[i]:
i -= 1
print(i)
if i == 0:
nums.reverse()
else:
j = len(nums) - 1
while j >= i and nums[j] <= nums[i-1]:
j -= 1
print(i,j)
tmp = nums[i - 1]
nums[i-1] = nums[j]
nums[j] = tmp
x = nums[i:len(nums)]
x.reverse()
print(x)
for k in range(i,len(nums)):
nums[k] = x[k - i]
print(nums)
sol = Solution()
sol.nextPermutation([5,1,1])
|
2554fbce7c3bc71399bf0e8efa7d564ab48a36dc
|
aceiii/advent-of-code-2016
|
/day2b.py
| 1,040 | 3.671875 | 4 |
#!/usr/bin/env python
import sys
def add(p, m):
return (p[0] + m[0], p[1] + m[1])
def code_to_dir(code):
if code == "U":
return (0, -1)
elif code == "D":
return (0, 1)
elif code == "L":
return (-1, 0)
elif code == "R":
return (1, 0)
def solve_bathroom_code(lines):
buttons = {
(2, 0): '1',
(1, 1): '2', (2, 1): '3', (3, 1): '4',
(0, 2): '5', (1, 2): '6', (2, 2): '7', (3, 2): '8', (4, 2): '9',
(1, 3): 'A', (2, 3): 'B', (3, 3): 'C',
(2, 4): 'D',
}
pos = (1, 1)
instr = []
for line in lines:
line = line.strip()
if line == "":
break
for c in list(line):
move_dir = code_to_dir(c)
next_pos = add(pos, move_dir)
if next_pos in buttons:
pos = next_pos
instr.append(buttons[pos])
return "".join(map(str, instr))
def main():
print(solve_bathroom_code(sys.stdin.readlines()))
if __name__ == "__main__":
main()
|
e8b9d6c5f566b4b9f1d684e20382a1a4956a7c00
|
shelcia/InterviewQuestionPython
|
/Patterns/rowNumberInvertedPyramid.py
| 289 | 3.953125 | 4 |
# Write a code to generate a half pyramid pattern using numbers.
# Sample Input :
# 5
# Sample Output :
# 5
# Sample Output :
# 55555
# 4444
# 333
# 22
# 1
N = int(input(''))
for index in range(0, N):
for secondIndex in range(0, N-index):
print(N-index, end='')
print('')
|
1e3a3062449379ff72220365c6b09ca71f63be8f
|
Hituls07/SampleCodes
|
/Stack_Queue.py
| 2,429 | 4.21875 | 4 |
"""
Stacks, like the name suggests, follow the Last-in-First-Out (LIFO) principle.
As if stacking coins one on top of the other,
the last coin we put on the top is the one that is the first to be removed from the stack later
"""
class Stack:
def __init__(self):
self.stack = []
def push(self, element):
self.stack.append(element)
def pop(self):
if len(self.stack) < 1:
return None
return self.stack.pop()
def size(self):
return len(self.stack)
def display(self):
return self.stack
'''
One of the example of stack is undo feature in word files.
We can record every action the user takes by pushing it to the stack.
When the user wants to undo an action they'll pop it from the stack.
We can quickly simulate the feature like this:
'''
document_actions = Stack()
document_actions.push('action: enter; text-id: 1, text: This is my favourite document')
print(document_actions.display())
document_actions.push('action; format; text_id: 1, alignment: center')
print(document_actions.display())
document_actions.pop()
print(document_actions.display())
"""
Queues, like the name suggests, follow the First-in-First-Out (FIFO) principle.
As if waiting in a queue for the movie tickets,
the first one to stand in line is the first one to buy a ticket and enjoy the movie.
"""
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, element):
self.queue.append(element)
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def size(self):
return len(self.queue)
def display(self):
return self.queue
'''
Queues have widespread uses in programming as well.
Think of games like Street Fighter or Super Smash Brothers.
Players in those games can perform special moves by pressing a combination of buttons.
These button combinations can be stored in a queue.
We can enqueue all input events as they come in. This way it doesn't matter if input events come with little time between them,
they'll all be stored and available for processing.
When we're processing the moves we can dequeue them.
'''
input_queue = Queue()
input_queue.enqueue('DOWN')
input_queue.enqueue('UP')
input_queue.enqueue('RIGHT')
print(input_queue.display())
print(input_queue.dequeue())
print(input_queue.dequeue())
print(input_queue.dequeue())
|
b494ea8a208f8367d03856455cabc076fd0ab8ef
|
Ayetony/python-parallel-training
|
/basic/consumer_producer.py
| 1,697 | 3.703125 | 4 |
import time
from threading import Thread, Condition
items = []
condition = Condition()
"""
Condition() instance
method ,condition.acquire - fetch the resource
condition.wait() jsut hold on ,wait
condition.notify() notify other threads.
condition.release() , let it go, you are finished.
"""
class Consumer(Thread):
def __init__(self):
Thread.__init__(self)
def consume(self):
global condition
global items
condition.acquire()
if len(items) == 0:
condition.wait()
print("Consumer notify: no items to consume")
items.pop()
print("Consumer notify: consumed 1")
print("Consumer notify: items to consume are %s" % len(items))
condition.notify()
condition.release()
def run(self):
for i in range(0, 30):
time.sleep(2)
self.consume()
class Producer(Thread):
def __init__(self):
Thread.__init__(self)
def produce(self):
global condition
global items
condition.acquire()
if len(items) == 10:
condition.wait()
print("Producer notify: items produced are %s" % len(items))
print("Producer notify: stop the production")
items.append(1)
print("Producer notify: total items produced are %s" % len(items))
condition.notify()
condition.release()
def run(self):
for i in range(0, 20):
time.sleep(2)
self.produce()
if __name__ == '__main__':
consumer = Consumer()
producer = Producer()
consumer.start()
producer.start()
producer.join()
consumer.join()
|
7b82ec4c8e2528bbae34ef09b02e8253958d575a
|
aled1027/real_gc
|
/main.py
| 783 | 3.90625 | 4 |
from pprint import pprint
import csv
def csv_to_bits(fnin, fnout):
"""
fnin is filename of csv file to be read.
fnout is filename of txt file to be written to.
Takes data in csv file and prints bit representation to fnout
"""
def my_str(x):
# x is a binary representation
# returns string version of x without the '0b'
return str(x)[2:]
data = []
with open(fnin) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for line in reader:
data.append(line[0])
txt_data = ''.join(list(map(my_str, map(bin, map(int, data)))))
with open(fnout, 'w') as txt_file:
txt_file.write(txt_data)
def go():
csv_to_bits('data.csv', 'data.txt')
if __name__ == '__main__':
go()
|
1db19285714164a7b5a91f319ba6043e95155a85
|
Jonathan-Challenger/PythonSkills
|
/Arrays/Validate subsequence.py
| 356 | 3.53125 | 4 |
array = [5, 1, 22, 25, 6, -1, 8, 10]
sequence = [1, 6, -1, 10]
def isValidSubsequence(arr1, seq):
arrInd = 0
seqInd = 0
while arrInd < len(arr1) and seqInd < len(seq):
if arr1[arrInd] == seq[seqInd]:
seqInd += 1
arrInd += 1
return seqInd == len(seq)
print(isValidSubsequence(array, sequence))
|
a050615f9895ab2c78e8ddb159be0ef9c828a105
|
liushuai0606/Python_First
|
/ython-Py.py
| 48 | 3.53125 | 4 |
word = "Python"
print(word[1:]+'-'+word[0]+'y')
|
464e811f22534fa21a739a416ff69a3ac2854c4c
|
JISU-JEONG/algorithm-
|
/20190826/coin.py
| 420 | 3.71875 | 4 |
coin = [1, 4, 6]
def coinChange(n, choice):
global Min
if sum(choice) > n or len(choice) >= Min:
return
if sum(choice) == n:
Min = min(Min, len(choice))
print(*choice)
return
else:
for i in range(2, -1, -1):
choice.append(coin[i])
coinChange(n, choice)
choice.pop()
Min = 0xffffffff
coinChange(8, [])
print('결과 :', Min)
|
0057fcbabdb16014af391e87bb698a7c683b4c18
|
Aasthaengg/IBMdataset
|
/Python_codes/p03068/s042941288.py
| 233 | 3.734375 | 4 |
# -*- coding: utf-8 -*-
#----------
N = int(input().strip())
S = input().strip()
K = int(input().strip())
#----------
new_S=""
for word in S:
if word != S[K-1]:
new_S += "*"
else:
new_S += word
print(new_S)
|
1436c86ca442afa8c42ecafcb78071d1e9ed8d79
|
nguyenthetung1806/C4T_Mentor
|
/Exercise/Part 3.py
| 1,789 | 3.96875 | 4 |
import random
count_played = 0
if count_played == 0:
choice_taking = True
while choice_taking:
start_input = input('Start Game ???? (y/n)').lower()
if start_input in ['y', 'n']:
choice_taking = False
else:
print('command Invalid !!!')
if start_input == 'y':
start = True
else:
start = False
while start:
print('Try answering the following questions:')
run = True
point = 0
while run:
print('point: {}'.format(point))
a = random.randint(1, 10)
b = random.randint(1, 10)
if random.random() <= 0.5:
correct_result = a + b
sign = '+'
else:
correct_result = a - b
sign = '-'
if random.random() <= 0.5:
to_show_result = correct_result
state = 'r'
else:
to_show_result = correct_result + random.randint(-3, 3)
state = 'w'
print('{0} {1} {2} = {3}'.format(a, sign , b, to_show_result))
choice_taking = True
while choice_taking:
choice = input('Right or Wrong (r/w) ??????').lower()
if choice in ['r', 'w']:
choice_taking = False
else:
print('command Invalid !!!')
if choice == state:
point += 1
print('Correct !!')
else:
print('Incorrect !! You lose')
run = False
choice_taking = True
while choice_taking:
play_again = input('Play Again? (y/n)').lower()
if play_again in ['y', 'n']:
choice_taking = False
else:
print('command Invalid !!!')
print('')
if play_again == 'n':
start = False
count_played = 1
|
bfbe384a49e51269b3d1f07cab86f732201dd152
|
pandeysaurabhofficial/Core-python
|
/Untitled4.py
| 2,828 | 4 | 4 |
# coding: utf-8
# # Dictionaries in python
# In[1]:
#{key:value}pairs
# In[2]:
my_dict = {'Sam':25,'Bob':26,'John':29}
# In[3]:
my_dict
# In[4]:
#dict have to be enclosed in curly braces and key in '' and value after :
# In[6]:
my_dict = {'Sam':{'Age':25,'Weight':'55 kg'},
'Bob':{'Age':26,'Weight':'68 kg'},
'John':{'Age':29,'Weight':'82 kg'}}
# In[7]:
my_dict
# In[8]:
#keys in a dictionary should be unique
# In[9]:
#if not it will get lost
# In[10]:
my_dict = {'a':1,'b':2,'c':3,'a':5}
# In[11]:
my_dict
# In[15]:
my_dict = {'a':1,'b':2,'c':3,'A':5}#case sensitive
# In[16]:
my_dict
# In[19]:
my_dict = {"a":1, 12:2, True: 3, 5.0:[1,23]} #keys can have different data types
# In[20]:
my_dict
# In[21]:
my_dict = {}
# In[22]:
my_dict
# In[24]:
my_dict = dict()
my_dict
# In[25]:
#create dict using nested lists
# In[26]:
my_dict = dict([[1,'a'],[2,'b'],[3,'b']])
# In[27]:
my_dict
# In[28]:
my_dict = {}
# In[29]:
my_dict
# In[30]:
my_dict[0] = 'a'
# In[32]:
my_dict #adding value in dict
# In[34]:
del my_dict[0]
my_dict
# In[35]:
#loop through all the keys in a dict
# In[36]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[37]:
for key in my_dict:
print(key)
# In[38]:
for key in my_dict:
print(my_dict[key])
# In[39]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[40]:
for key in my_dict.keys():
print(key)
# In[44]:
for value in my_dict.values():
print(value)
# In[45]:
for key,value in my_dict.items():
print('key :', str(key),'value :', str(value))
# In[46]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[47]:
if 2 in my_dict:
print('present')
# In[48]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[49]:
if 5 in my_dict:
print('present')
else:
print('absent')
# In[50]:
#Deep copy
# In[52]:
my_dict = {1:['a','b'],2:['c','d']}
my_dict
# In[54]:
import copy
# In[55]:
my_dict_copy = copy.deepcopy(my_dict)
my_dict_copy
# In[56]:
my_dict[2][0] = 'g'
my_dict
# In[57]:
my_dict_copy #proper way of copying not shallow copy
# In[58]:
# Built-in functions in Dict:
# In[59]:
my_dict = {1:'a',2:'b'}
my_dict
# In[60]:
my_dict.clear()
# In[61]:
my_dict
# In[62]:
#get funtion/method
# In[63]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[64]:
value_of_2 = my_dict.get(2)
value_of_2
# In[65]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[67]:
my_dict.popitem() #return type is tuple
# In[68]:
my_dict
# In[69]:
my_dict = {1:'a',2:'b',3:'c'}
my_dict
# In[71]:
my_dict.pop(2)
# In[72]:
my_dict
# In[73]:
#update function
# In[74]:
my_dict = {'a':1,'b':2,}
my_dict
# In[75]:
my_dict.update({'a':50,'c':7})
# In[76]:
my_dict
# In[77]:
len(my_dict)
|
9712c924165bccd83592e21f82804e75e3b26bd0
|
bastolatanuja/lab1
|
/lab exercise/question number 8.py
| 229 | 4.5 | 4 |
#write a python program which accepts the radius of a circle from the user and compute the area.
# (area of circle=pi*r**2)
radius=int(input("enter the radius: "))
pi=3.14
area=pi*(radius**2)
print(f"the area of circle is{area}")
|
5d509e583c2e77823549d9f03e160dcebd8de9d1
|
deepdhar/Python-Programs
|
/Functions/reverse_num.py
| 237 | 4 | 4 |
#reverse of a number
import math
def reverse_num(n):
d=int(math.log10(n))
if n<10:
return n
else:
return (n%10*math.pow(10,d) + reverse_num(n//10))
num = int(input())
print("Reverse:", int(reverse_num(num)))
|
ef59c442daedc9de83b4f9a4f82c519fd1e71043
|
irma1991/database_homework
|
/database/database.py
| 7,721 | 3.890625 | 4 |
import sqlite3
from book import book
from book import publisher
import pprint
def create_books(book):
connection = sqlite3.connect("books.db")
cursor = connection.cursor()
sql_query_not_injectable = "INSERT into books VALUES (?, ?, ?, ?, ?)"
query_values = (book.book_title, book.author, book.publish_date, book.publisher, book.selling_price)
cursor.executemany(sql_query_not_injectable, query_values)
connection.commit()
connection.close()
book1 = book.book("Prie ezero", "Petras Petraitis", 2015, "Knygynas", 12)
create_books(book1)
print(book1)
def execute_query(query, entry):
connection = sqlite3.connect("books.db")
connection_cursor = connection.cursor()
connection_cursor.execute(query, entry)
connection.commit()
connection.close()
def create_table_books():
connection = sqlite3.connect("books.db")
connection_cursor = connection.cursor()
connection_cursor.execute("""CREATE TABLE IF NOT EXISTS books (
id integer PRIMARY KEY,
book_title text,
author text,
publish_date date,
publisher text,
selling_price numeric
)""")
connection.commit()
connection.close()
def create_table_publishers():
connection = sqlite3.connect("books.db")
connection_cursor = connection.cursor()
connection_cursor.execute("""CREATE TABLE IF NOT EXISTS publishers (
id integer PRIMARY KEY,
publisher_name text,
book_title text,
author text,
printed_quantity integer,
printing_price numeric
)""")
connection.commit()
connection.close()
def select_data(query, entry=None):
if entry is None:
entry = []
connection = sqlite3.connect("books.db")
connection_cursor = connection.cursor()
connection_cursor.execute(query, entry)
rows = []
for row in connection_cursor.execute(query, entry):
rows.append(row)
pp = pprint.PrettyPrinter()
pp.pprint(rows)
connection.close()
# Insert
def insert_book(book_title, author, publish_date, publisher, selling_price):
insert_query = """INSERT INTO books (book_title, author, publish_date, publisher, selling_price)
VALUES(?, ?, ?, ?, ?)"""
book = [book_title, author, publish_date, publisher, selling_price]
execute_query(insert_query, book)
def insert_publisher(publisher_name, book_title, author, printed_quantity, printing_price):
insert_query = """INSERT INTO publishers (publisher_name, book_title, author, printed_quantity, printing_price)
VALUES(?, ?, ?, ?, ?)"""
publisher = [publisher_name, book_title, author, printed_quantity, printing_price]
execute_query(insert_query, publisher)
# Search
def get_from_books(search_string):
select_query = """SELECT * FROM books WHERE book_title OR
author OR
publish_date OR
publisher OR
selling_price LIKE ?"""
title = ['%' + search_string + '%']
select_data(select_query, title)
def get_from_publishers(search_string):
select_query = """SELECT * FROM publishers WHERE publisher_name OR
book_title OR
author OR
printed_quantity OR
printing_price LIKE ?"""
title = ['%' + search_string + '%']
select_data(select_query, title)
# Update Book methods
def update_book_title(new_value, book_id):
update_query = """UPDATE books SET book_title = ? WHERE id = ?"""
update_data = [new_value, book_id]
execute_query(update_query, update_data)
def update_book_publisher(new_value, book_id):
update_query = """UPDATE books SET publisher = ? WHERE id = ?"""
update_data = [new_value, book_id]
execute_query(update_query, update_data)
def update_book_author(new_value, book_id):
update_query = """UPDATE books SET author = ? WHERE id = ?"""
update_data = [new_value, book_id]
execute_query(update_query, update_data)
def update_book_publish_date(new_value, book_id):
update_query = """UPDATE books SET publish_date = ? WHERE id = ?"""
update_data = [new_value, book_id]
execute_query(update_query, update_data)
def update_book_selling_price(new_value, book_id):
update_query = """UPDATE books SET selling_price = ? WHERE id = ?"""
update_data = [new_value, book_id]
execute_query(update_query, update_data)
# Update Publisher methods
def update_publisher_name(new_value, publisher_id):
update_query = """UPDATE publishers SET publisher_name = ? WHERE id = ?"""
update_data = [new_value, publisher_id]
execute_query(update_query, update_data)
def update_publisher_book_title(new_value, publisher_id):
update_query = """UPDATE publishers SET book_title = ? WHERE id = ?"""
update_data = [new_value, publisher_id]
execute_query(update_query, update_data)
def update_publisher_author(new_value, publisher_id):
update_query = """UPDATE publishers SET author = ? WHERE id = ?"""
update_data = [new_value, publisher_id]
execute_query(update_query, update_data)
def update_publisher_printed_quantity(new_value, publisher_id):
update_query = """UPDATE publishers SET printed_quantity = ? WHERE id = ?"""
update_data = [new_value, publisher_id]
execute_query(update_query, update_data)
def update_publisher_printing_price(new_value, publisher_id):
update_query = """UPDATE publishers SET printing_price = ? WHERE id = ?"""
update_data = [new_value, publisher_id]
execute_query(update_query, update_data)
# Delete
def delete_book_by_id(book_id):
delete_query = """DELETE FROM books WHERE id = ?"""
entry_id = [book_id]
execute_query(delete_query, entry_id)
def delete_publisher_by_id(publisher_id):
delete_query = """DELETE FROM publishers WHERE id = ?"""
entry_id = [publisher_id]
execute_query(delete_query, entry_id)
def get_quantity_price():
rows=[]
connection = sqlite3.connect("books.db")
connection_cursor = connection.cursor()
select_query = """SELECT (publishers.printed_quantity * SUM(books.selling_price - publishers.printing_price)) AS rez
FROM books
INNER JOIN publishers ON books.book_title = publishers.book_title"""
for row in connection_cursor.execute(select_query):
rows.append(row)
pp = pprint.PrettyPrinter()
pp.pprint(rows)
connection.close()
create_table_books()
create_table_publishers()
insert_book('Zigmas po dangum', 'Janionis', 1998, 'Alma Litera', 25)
insert_publisher('Alma litera', 'Zigmas po dangum', 'Janionis', 100, 10)
get_from_books('Zigm')
get_from_publishers('Alm')
get_quantity_price()
|
d88d7ba92f7394818b8c7531bc86e26adbcb5759
|
fabixneytor/Utp
|
/ciclo 1/Ejercicios Python/captcha.py
| 545 | 3.546875 | 4 |
from os import system
import random
system("cls")
longitud: int = 5
abedecedario:str = '1234567890abcdefghijklmnñopqrstuvxyz'
# elije aleatoriamente 5 elementos del abecedario
desordenar: list = random.sample(abedecedario, longitud)
#join crea cadenas a partir de objetos iterables
palabra: str = ''.join(desordenar)
print(palabra)
X: str = input("Ingrese el codigo que ves en pantalla: ")
if X == palabra:
print("El codigo es correcto")
else:
print('El codigo es incorrecto')
input('presiona enter para salir')
|
80da67271ab1001467171c3788c62502f9b51a25
|
jaykhopale/cs-interview-questions
|
/src/main/python/projecteuler/problem052.py
| 1,052 | 3.671875 | 4 |
#!/usr/bin/python
"""
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
"""
def samedigits(n, m):
length = (len(str(n)))
if length != len(str(m)):
return False
n = list(str(n))
m = list(str(m))
n.sort()
m.sort()
count = 0
for i in range(length):
if n[i] == m[i]:
count = count + 1
if length == count:
return True
else:
return False
def main():
for i in range(1, 1000000):
length = len(str(i))
if length == len(str(2 * i)) and length == len(str(3 * i)) and length == len(str(4 * i)) and length == len(str(5 * i)) and length == len(str(6 * i)):
if samedigits(i, 2 * i) and samedigits(i, 3 * i) and samedigits(i, 4 * i) and samedigits(i, 5 * i) and samedigits(i, 6 * i):
print(i)
if __name__ == "__main__":
main()
|
f2af49da2e43d5bdc7915b13583411c0424fe317
|
V47VANSH/Hacktober-Challenges
|
/Collatz/collatz.py
| 240 | 4.1875 | 4 |
num = int(input("Enter a number: "))
while(num != 1):
if((num % 2) == 0): # even number = divide by 2
num /= 2
else: # odd number = multiply by 3 and add 1
num = num * 3 + 1
print(int(num))
print('Done!')
|
4357057586a6c251f59740ad21919361a97ac269
|
agucadiz/pro
|
/python/proyectos/duelo/cartas.py
| 955 | 3.859375 | 4 |
"""
# Cartas.
- Las cartas son 4:
- 0. Gran Éxito: + 2 de vida.
- 1. Éxito: + 1 de vida.
- 2. Fracaso: - 1 de vida.
- 3. Gran Fracaso: - 2 de vida.
"""
# ¿Traerme funciones del repartidor aquí?
from random import shuffle as mezclar
GE,E, F, GF = range(4)
baraja = [GE, # = 0
E, # = 1
F, # = 2
GF # = 3
]
def mostrar():
"""Crea una copia de la baraja identificándola con sus siglas."""
mano = []
for carta in baraja:
if carta == GE:
mano.append('[GE]')
elif carta == E:
mano.append('[E]')
elif carta == F:
mano.append('[F]')
elif carta == GF:
mano.append('[GF]')
print('\n', mano, '\n')
def barajar():
"""Baraja las cartas de forma aleatoria."""
mezclar(baraja)
print('(El repartidor mezcla las cartas cuidadosamente.)')
def carta(seleccion):
return baraja[seleccion]
|
a66ced46ec1351bdd150ece2201f46cb76f40c4d
|
QFD-Felix/Arduino-Route-Finder
|
/route finder/dummy_server/server.py
| 6,581 | 3.53125 | 4 |
''' # Name: Adit Hasan Student ID: 1459800
# Name: QIUFENG DU Student ID: 1439484
With MinHeap and AdjacencyGraph in the same directory,
this script can be run from the command line with the
command: python3 server.py. The server can be interacted
with sending requests in the format
R <coordinateA1> <coordinateA2> <coordinateB1> <coordinateB2>
and then pressing enter. Waypoints would be provided one at a
time and requires Acknowledgement "A" everytime.
'''
import sys
import csv
import math
from adjacencygraph import AdjacencyGraph
import queue
import heapq
vertex_coord = {}
def read_city_graph(filename):
'''Takes the provided CSV file containing the information about
Edmonton map and contructs an Undirected Graph
Args:
filename (CSV_file_name): The file containing the data
Returns:
g (graph): The undirected graph
'''
g = AdjacencyGraph()
# opens the file to be read
with open(filename) as csvfile:
# separates the file into values
csv_input = csv.reader(csvfile, delimiter=',')
for row in csv_input:
# If first character of line is V add vertex
if row[0] == 'V':
g.add_vertex(int(row[1]))
# If first character of line is E add edge
elif row[0] == 'E':
g.add_edge((int(row[1]), int(row[2])))
return g
def read_vertex_coord(filename):
'''stores all vertex coordinates in a dict file with format
(vertex ID): (coordinate1, coordinate2)
Args:
filename (CSV_file_name): The file containing the data
Returns:
vertex_coord (dict): The dictionary containing the coordinates
'''
# stores all vertex coordinates in a dict file with format
# (vertex ID): (coordinate1, coordinate2)
vertex_coord = dict()
with open(filename) as csvfile:
csv_input = csv.reader(csvfile, delimiter=',')
for row in csv_input:
if row[0] == 'V':
vertex_coord[int(row[1])] = (int(float(row[2])*100000), int(float(row[3])*100000))
vertex_coord [int(row[1])] = (int(float(row[2])*100000), int(float(row[3])*100000))
else:
continue
return vertex_coord
def cost_distance(u, v):
'''Computes and returns the straight-line distance between the two
vertices u and v.
Args:
u, v: The ids for two vertices that are the start and
end of a valid edge in the graph.
Returns:
numeric value: the distance between the two vertices.
'''
term_a = (vertex_coord[u][0]-vertex_coord[v][0])**2
term_b = (vertex_coord[u][1]-vertex_coord[v][1])**2
return (term_b + term_a)**(0.5)
def read_street_names(filename):
'''Stores all edge street names in a dict file with format
(starting vertex, ending vertex) : Street Name
Args:
filename (CSV_file_name): The file containing the data
Returns:
vertex_coord (dict): The dictionary containing the coordinates
'''
# stores all edge street names in a dict file with format
# (starting vertex, ending vertex) : Street Name
street_names = dict()
with open(filename) as csvfile:
csv_input = csv.reader(csvfile, delimiter=',')
for row in csv_input:
if row[0] == 'E':
street_names[(int(row[1]), int(row[2]))] = (row[3])
else:
continue
return street_names
g = read_city_graph("edmonton-roads-2.0.1.txt")
street_names = read_street_names("edmonton-roads-2.0.1.txt")
vertex_coord = read_vertex_coord("edmonton-roads-2.0.1.txt")
def least_cost_path(graph, start, dest, cost):
"""Find and return a least cost path in graph from start
vertex to dest vertex.
Efficiency: If E is the number of edges, the run-time is
O( E log(E) ).
Args:
graph (Graph): The digraph defining the edges between the
vertices.
start: The vertex where the path starts. It is assumed
that start is a vertex of graph.
dest: The vertex where the path ends. It is assumed
that start is a vertex of graph.
cost: A function, taking the two vertices of an edge as
parameters and returning the cost of the edge. For its
interface, see the definition of cost_distance.
Returns:
list: A potentially empty list (if no path can be found) of
the vertices in the graph. If there was a path, the first
vertex is always start, the last is always dest in the list.
Any two consecutive vertices correspond to some
edge in graph.
"""
reached = {}
runners = [(0,start,start)]
while len(runners) != 0:
path = []
A = heapq.heappop(runners)
(time,goal,start_inside) = A
if goal in reached:
continue
reached[goal] = (start_inside,time)
if goal == dest:
key = dest
while key != start:
path.append(key)
key = reached[key][0]
path.append(key)
# return path in right order
return path[::-1]
for succ in graph.neighbours(goal):
heapq.heappush(runners,(time+cost(goal,succ),succ,goal))
return []
def check_cloest_point(u,v):
'''check the cloest vertices regards to the request coordinates
u is the latitude of request point
v is the longitude of request point
reutrn cloest id with its coordinates
'''
short = float("inf")
cloest = None
for w,[x,y] in vertex_coord.items():
dis = ((x-u)**2+(y-v)**2)**0.5
if dis < short:
short = dis
cloest = w
return cloest
def connect(g,r):
'''connect the arduino
g is the graph read from the csv file
r is the request sent from arduino
it should look like a statemachine
'''
low_cost = least_cost_path(g, check_cloest_point(r[1],r[2]), check_cloest_point(r[3],r[4]), cost_distance)
waypoints = len(low_cost)
print('N',waypoints)
if input() != 'A':
print("Acknowledgement not received")
if waypoints >= 0:
for v in low_cost:
print('W',vertex_coord[v][0],vertex_coord[v][1])
if input() != 'A':
break
print('E')
if __name__ == "__main__":
#state machine
while True:
request = input().split()
if request[0] == 'R':
if len(request) == 5:
for i in range(1, 5):
request[i] = int(request[i])
connect(read_city_graph("edmonton-roads-2.0.1.txt"),request)
|
aac94f03b007d5ba2de28dfe4b2ad83423889793
|
dyshko/examples
|
/Rent Data Model/src/utils.py
| 683 | 3.578125 | 4 |
import calendar
import datetime
from dateutil import relativedelta
def str_to_date(s):
if s == "":
return None
return datetime.datetime.strptime(s, "%Y-%m-%d").date()
def read_csv(filename):
with open(filename) as f:
return f.readlines()[1:] # omit header
def months_between(date1, date2):
r = relativedelta.relativedelta(date2, date1)
return abs(12 * r.years) + abs(r.months)
def add_months(source_date, months):
month = source_date.month - 1 + months
year = source_date.year + month // 12
month = month % 12 + 1
day = min(source_date.day, calendar.monthrange(year, month)[1])
return datetime.date(year, month, day)
|
f6a7d192285a72b214ca00a82deae8d5535b430c
|
Kawser-nerd/CLCDSA
|
/Source Codes/AtCoder/arc070/A/3684351.py
| 139 | 3.671875 | 4 |
x = int(input())
import math
huga = int((-1 + math.sqrt(1+8*x))/2)
if huga*(huga+1) == 2*x:
print(huga)
else:
print(huga+1)
|
53911fbd302ab182fef73aedbeb05f171b3a75de
|
dsqrt4/itfvalidator-python
|
/pyitf/check_digit.py
| 523 | 4.09375 | 4 |
import pyitf.internal as internal
def calculate_check_digit(code: int) -> int:
"""Calculates and returns the check digit for the given code."""
digits = internal.digits(code)
sum_digits = 0
for i, n in enumerate(digits):
sum_digits += n if (i+1) % 2 == 0 else n*3
mod10 = sum_digits % 10
return 0 if mod10 < 1 else 10-mod10
def append_check_digit(code: int) -> int:
"""Returns the given code including a calculated check digit."""
return code*10 + calculate_check_digit(code)
|
0c534f378b3a31e09c3095cbb3757bf458de25b8
|
AayushRajput98/PythonML
|
/Class/June6/String.py
| 277 | 4.125 | 4 |
x="Welcome To Noida"
print(x[::-1])
print(x.isupper())
print(x.islower())
print(x.istitle())
print(x.capitalize())
print(x.upper())
print(x.count("o"))
print(x.index("Welcome")) #Index of a substring
print(x.replace(" ","_"))
print(x.isidentifier()) #No space should be present
|
f34f42713c01d811472997a80f82d7ee02061d36
|
scottpeterman/clearpass-api
|
/general_scripts/time_epoch.py
| 1,391 | 4.03125 | 4 |
#!/usr/bin/env python3
#------------------------------------------------------------------------------
#
# Script to "play" with time structures
#
#------------------------------------------------------------------------------
import time
import datetime
print("Time in seconds since the epoch: %s" %time.time())
print("Current date and time: " , datetime.datetime.now())
print("Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))
date_time = '2018-06-25 00:00:01'
pattern = '%Y-%m-%d %H:%M:%S'
epoch1 = int(time.mktime(time.strptime(date_time, pattern)))
print(date_time, epoch1)
date_time = '2018-07-01 23:59:59'
pattern = '%Y-%m-%d %H:%M:%S'
epoch2 = int(time.mktime(time.strptime(date_time, pattern)))
print(date_time, epoch2)
epoch3 = epoch2 - epoch1
print(epoch3)
timestamp = 1532296800
value = datetime.datetime.fromtimestamp(timestamp)
time = value.strftime('%Y-%m-%d %H:%M:%S')
print("time is ", time)
|
9ab897fa6545951043f063c031ddccea89e59675
|
sakurasakura1996/Leetcode
|
/单调栈/problem84_柱状图中最大的矩形.py
| 1,357 | 3.796875 | 4 |
"""
84. 柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
示例:
输入: [2,1,5,6,2,3]
输出: 10
"""
# 题解中使用的是单调栈的思想
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
n = len(heights)
if n <= 0:
return 0
left, right = [0] * n, [0] * n
mono_stack = list()
for i in range(n):
while mono_stack and heights[mono_stack[-1]] >= heights[i]:
mono_stack.pop()
left[i] = mono_stack[-1] if mono_stack else -1
mono_stack.append(i)
mono_stack = list()
for i in range(n-1, -1, -1):
while mono_stack and heights[mono_stack[-1]] >= heights[i]:
mono_stack.pop()
right[i] = mono_stack[-1] if mono_stack else n
mono_stack.append(i)
ans = 0
for i in range(n):
ans = max(ans, (right[i] - left[i] -1) * heights[i])
return ans
|
24d74e825423a489de2501cb9d0724e8c32afa75
|
Albatrossiun/SVM_digital-recognition_Code_py
|
/my_queue.py
| 914 | 4.09375 | 4 |
'''
#增删查
def push(queue, num):
queue.append(num)
return queue
def pop(queue):
queue = queue[1:]
return queue
def front(queue):
return queue[0]
'''
# 类
class MyQueue:
# 构造函数
def __init__(self):
self.q = []
#print("这是构造函数")
def push(self,num):
self.q.append(num)
def pop(self):
self.q = self.q[1:]
def front(self):
return self.q[0]
def empty(self):
return len(self.q) == 0
'''
class Student:
def __init__(self):
self.name = "默认姓名"
self.age = 0
self.sex = "默认性别"
def Show(self):
print(self.name)
print(self.age)
print(self.sex)
'''
if __name__ == "__main__":
que = MyQueue()
que.push(1)
que.push(2)
que.push(3)
que.push(4)
while(not que.empty()):
print(que.front())
que.pop()
|
49b05e97fc3d05284b4c3cbb7bcf66c3a9ec430f
|
Neal0408/LeetCode
|
/Algorithm/String/#168.py
| 499 | 3.640625 | 4 |
# 168.Excel表列名称
# 给你一个整数columnNumber,返回它在 Excel 表中相对应的列名称。
# 解题思路
# 1.26为一个进制,进制转换为字母。
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
ans = list()
while columnNumber > 0:
a0 = (columnNumber - 1) % 26 + 1
ans.append(chr(a0 - 1 + ord('A')))
columnNumber = (columnNumber - a0) // 26
return "".join(ans[::-1])
obj = Solution()
|
0dd9d42f78f0014f6a37b62b80a25181534181fb
|
TomsenTan/About_asyncio
|
/asyncio_test.py
| 1,851 | 3.703125 | 4 |
#Date:2018-12-10
#Author:Thomson
from threading import Thread,currentThread
import time
#阻塞检测,一个线程阻塞,另一个线程执行
def do_something(x):
time.sleep(x)
print(time.ctime())
thread1 = Thread(target=do_something,args=(1,))
thread2 = Thread(target=do_something,args=(2,))
thread3 = Thread(target=do_something,args=(3,))
thread4 = Thread(target=do_something,args=(4,))
thread5 = Thread(target=do_something,args=(5,))
threads = []
threads.append(thread1)
threads.append(thread4)
threads.append(thread3)
threads.append(thread2)
threads.append(thread5)
for thread in threads:
thread.start()
#共有数据的争夺检测
start = time.time()
def do_something(x):
global a
time.sleep(x)
for b in range(1,51): #计算从1+...+50
a+=b
print(currentThread(),":",a)
a = 0
threads = []
for i in range(1,20000):
thread = Thread(target=do_something,args=(1,))
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
end = time.time()
print(end-start)
import asyncio
import time
a = 0
tasks = []
num = 0
start = time.time()
# 密集运算测试
async def do_something(x):
global a
global num
#num += 1 #num自增的位置(在阻塞前/后)不同会产生不同的结果
await asyncio.sleep(x)
for b in range(1,51): #计算从1+...+50
a+=b
num += 1
print("this is coroutetime",":",x,a)
for i in range(1,20000):
coroutine = do_something(1) #即使睡眠的时间很短,运算量大都不会产生资源争夺
#coroutine = do_something(i*0.01)
tasks.append(asyncio.ensure_future(coroutine))
loop = asyncio.get_event_loop() #创建事件循环
loop.run_until_complete(asyncio.wait(tasks)) #将协程塞进事件循环中
end = time.time()
print(end-start)
|
33e8259bf2f94a3059dbbc5f1563bb5d063cc0ef
|
jversoza/p4a-spring-16-examples
|
/p4a-class22/scratch/abc.py
| 817 | 3.828125 | 4 |
class InfiniteAlphabet:
START, END = 65, 90
def __init__(self):
self.code_point = InfiniteAlphabet.START
def __iter__(self):
return self
def __next__(self):
letter = chr(self.code_point)
self.code_point += 1
if self.code_point > InfiniteAlphabet.END:
self.code_point = InfiniteAlphabet.START
return letter
#for letter in InfiniteAlphabet():
# print(letter)
def infinite_alphabet():
START, END = 65, 90
code_point = START
while True:
letter = chr(code_point)
code_point += 1
if code_point > END:
code_point = START
yield letter
infinity = infinite_alphabet()
print(next(infinity))
print(next(infinity))
#for letter in infinite_alphabet():
# print(letter)
|
65bc526da1d0bc38a775869c3b3e0811e3f81f06
|
pradyumnkumarpandey/PythonAlgorithms
|
/LeetCode/0016_3sum_closest.py
| 1,423 | 3.84375 | 4 |
# Import necessary dependencies
import sys
class Solution:
def threeSumClosest(self, nums, target):
# Sort the array
nums.sort()
# Initialize closest sum
closest_sum = sys.maxsize
# Starting from the first element,fix the smallest number
# Implement the two pointers method in the remaining array
for num in range(len(nums) - 2):
# Initialize the two pointers
# One pointing to the last element
# the other pointing to element next to the fixed element.
ptr_first, ptr_last = num + 1, len(nums) - 1
# While the pointers don't cross each other
while ptr_first < ptr_last:
# Calculate the sum
sum_temp = nums[num] + nums[ptr_first] + nums[ptr_last]
# Compare against the variable closest_sum
# If it is closer than the current closest_sum
# Update closest sum. Also check :
# If sum is greater than target, decrement ptr_last to decrease sum
# Else, increment ptr_first to increase sum
if abs(target - sum_temp) < abs(target - closest_sum):
closest_sum = sum_temp
if sum_temp > target:
ptr_last = ptr_last - 1
else:
ptr_first = ptr_first + 1
return closest_sum
|
96ef6364f8bc53a8389d93f60ca0361fd67c3ded
|
xiaoruiling/My-Memo
|
/Python/Hello.py
| 2,793 | 3.5 | 4 |
##!/usr/bin/env python3
#
#name = input('Please enter you name ....\n')
#print('Hello', name)
#
#print('I\'m a girl')
#print(r'line1\nline2\nline3')
#
#print('''line1
#... line2
#... line3''')
#
#print(not (3 > 6 or 3 > 5))
#print(None)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#from tkinter import *
#import tkinter.messagebox as messagebox
#
#class Application(Frame):
#
# def __init__(self, master=None):
# Frame.__init__(self, master)
# self.pack()
# self.createWidgets()
#
# def createWidgets(self):
# self.nameInput = Entry(self)
# self.nameInput.pack()
# self.alertButton = Button(self, text='Click', command=self.helloAction)
# self.alertButton.pack()
#
# def helloAction(self):
# name = self.nameInput.get() or 'world'
# messagebox.showinfo('Message', 'Hello, %s' % name)
#
#app = Application()
## 设置窗口标题:
#app.master.title('Hello World')
## 主消息循环:
#app.mainloop()
# wxWidgets "Hello World" Program
# For compilers that support precompilation, includes "wx/wx.h".
include <wx/wxprec.h>
ifndef WX_PRECOMP
include <wx/wx.h>
#endif
class MyApp : public wxApp
{
public:
virtual bool OnInit();
};
class MyFrame : public wxFrame
{
public:
MyFrame();
private:
void OnHello(wxCommandEvent& event);
void OnExit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
};
enum
{
ID_Hello = 1
};
wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit()
{
MyFrame *frame = new MyFrame();
frame->Show(true);
return true;
}
MyFrame::MyFrame()
: wxFrame(NULL, wxID_ANY, "Hello World")
{
wxMenu *menuFile = new wxMenu;
menuFile->Append(ID_Hello, "&Hello...\tCtrl-H",
"Help string shown in status bar for this menu item");
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
wxMenu *menuHelp = new wxMenu;
menuHelp->Append(wxID_ABOUT);
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(menuFile, "&File");
menuBar->Append(menuHelp, "&Help");
SetMenuBar( menuBar );
CreateStatusBar();
SetStatusText("Welcome to wxWidgets!");
Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}
void MyFrame::OnExit(wxCommandEvent& event)
{
Close(true);
}
void MyFrame::OnAbout(wxCommandEvent& event)
{
wxMessageBox("This is a wxWidgets Hello World example",
"About Hello World", wxOK | wxICON_INFORMATION);
}
void MyFrame::OnHello(wxCommandEvent& event)
{
wxLogMessage("Hello world from wxWidgets!");
}
|
01c834965bf83f7c4bca7938034ff309698eaed6
|
geethusk/faslulfarisa
|
/python_code/swap.py
| 91 | 3.96875 | 4 |
print("Before Swap:")
a=5
b=6
print (a,b)
print("After Swap:")
a=a+b
b=a-b
a=a-b
print(a,b)
|
e4aa74b2ace15b6ed72e3e40634616f76f027c9c
|
jeffersonvital20/Faculdade
|
/InteligenciaArtificial/perceptron/perceptron.py
| 2,791 | 3.75 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# aplicativo para verificar se o ser vivo eh quadrupede ou bipede
# quadrupede = 1, bipede = -1
# cao = [-1,-1,1,1] | resposta = 1
# gato = [1,1,1,1] | resposta = 1
# cavalo = [1,1,-1,1] | resposta = 1
# homem = [-1,-1,-1,1] | resposta = -1
# pesos (sinapses)
# w = [0,0]
w = [0, 0, 0, 0]
# entradas
# x = [[0,0],[0,1],[1,0],[1,1]]
x = [[-1, -1, 1, 1],
[1, 1, 1, 1],
[1, 1, -1, 1],
[-1, -1, -1, 1]]
# respostas esperadas
t = [1, 1, 1, -1]
# bias (ajuste fino)
b = 0
# saida
y = 0
# numero maximo de interacoes
max_int = 10
# taxa de aprendizado
taxa_aprendizado = 1
# soma
soma = 0
# theshold
threshold = 1
# nome do animal
animal = ""
# resposta = acerto ou falha
resposta = ""
# dicionario de dados
# d = {'0,0': 'cao','0,1': 'gato','1,0': 'cavalo','1,1': 'homem' }
d = {'-1,-1,1,1': 'cao', '1,1,1,1': 'gato', '1,1,-1,1': 'cavalo', '-1,-1,-1,1': 'homem'}
print("Treinando")
# funcao para converter listas em strings
def listToString(list):
s = str(list).strip('[]')
s = s.replace(' ', '')
return s
# inicio do algoritmo
for k in range(1, max_int):
acertos = 0
print("INTERACAO " + str(k) + "-------------------------")
for i in range(0, len(x)):
soma = 0
# pega o nome do animal no dicionário
if listToString(x[i]) in d: # d.keys() == listToString(x[i])
animal = d[listToString(x[i])]
else:
animal = ""
# para calcular a saida do perceptron, cada entrada de x eh multiplicada
# pelo seu peso w correspondente
for j in range(0, len(x[i])):
soma += x[i][j] * w[j]
# a saida eh igual a adicao do bias com a soma anterior
y_in = b + soma
# print("y_in = ",str(y_in))
# funcao de saida eh determinada pelo threshold
if y_in > threshold:
y = 1
elif y_in >= -threshold and y_in <= threshold:
y = 0
else:
y = -1
# atualiza os pesos caso a saida nao corresponda ao valor esperado
if y == t[i]:
acertos += 1
resposta = "acerto"
else:
for j in range(0, len(w)):
w[j] = w[j] + (taxa_aprendizado * t[i] * x[i][j])
b = b + taxa_aprendizado * t[i]
resposta = "Falha - Peso atualizado"
# imprime a resposta
if y == 1:
print(animal + " = quadrupede = " + resposta)
elif y == 0:
print(animal + " = padrao nao identificado = " + resposta)
elif y == -1:
print(animal + " = bipede = " + resposta)
if acertos == len(x):
print("Funcionalidade aprendida com " + str(k) + " interacoes")
break;
print("")
print("Finalizado")
print(w)
|
bb208cdd65154e0228ea9a722342e97f1002d977
|
rakshithk10/protothon01
|
/main.py
| 747 | 3.9375 | 4 |
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
def add(a,b):
return a+b
def sub(a,b):
return a-b
def multiply(a,b):
return a*b
def div(a,b):
return a/b
print("Select the operation")
print("1.Add")
print("2.subract")
print("3.multiply")
print("4.division")
num1=float(input())
num2=float(input())
choise=(input())
if choise == '1':
print(add(num1,num2))
elif choise == '2':
print(add(num1,num2))
elif choise == '3':
print(add(num1,num2))
elif choise == '4':
print(add(num1,num2))
else:
print("Invalid input")
|
f7321008c0478fed6fa496e73f379f8df68f1d33
|
Roobanpriyanka/guvi-code-kata-
|
/palin.py
| 223 | 4.09375 | 4 |
x=int(input("enter the number:"))
temp=x
rev=0
while(x>0):
dig=x%10
rev=rev*10+dig
x=x//10
if(temp==rev):
print("the number is palindrome:")
else:
print("the number is not a palindrome:")
|
935a521afa739eef1fd7a0f41183d701be79bea8
|
Cachemarra/ML_Pro
|
/Easy/1D_Histogram.py
| 1,829 | 4.28125 | 4 |
#%%
"""
A histogram represents the frequency distributionof data. The idea is to take
a list of values and make a tally of how many times each value occurs.
Given a 1D NumPy array, create a histogram of the data represented as a NumPy array
where the index represents the number and the value represents the count.
Note that the first index (position 0) represents how many times number 1 occurs.
There are 2 things to note:
The parameter range default from min to max, however the task requires
histogram starting from 1.
bins default to only 10 values, therefore we must set it to max cover all the
numbers in the np.array
example:
arr: [1, 1, 1, 2, 2, 3, 5, 6, 7, 8, 9, 6, 8, 9, 7, 2, 9]
output:[3, 3, 1, 0, 1, 2, 2, 2, 3]
"""
# Libraries
import numpy as np
# Solution Class
def get_histogram(arr: np.array) -> np.array:
"""
Function to get an histogram of a 1D array.
:param arr: 1D array
:return: 1D array
"""
# Check if the array is not an numpy object. If not, convert it to one.
if type(arr) != np.ndarray:
arr = np.array(arr)
# Create a histogram of the array
larg = np.unique(arr)
# Create an array with the true large of the input.
# larg has all the unique values ordered from min to max.
# we iterate to ensure to have all the integers between the min and max.
histogram = []
for i in range(larg[-1]):
histogram.append((arr == i+1).sum())
return np.array(histogram)
#%% Test
if __name__ == "__main__":
# Test 1
arr = np.array([1, 1, 1, 2, 2, 3, 5, 6, 7, 8, 9, 6, 8, 9, 7, 2, 9])
print(get_histogram(arr))
# Test 2
arr = np.array([1, 12, 6, 7, 2, 3, 4, 12, 12, 12, 6 ,6, 7, 7, 7, 7, 1, 1, 1, 1, 4, 4, 4, 4])
print(get_histogram(arr))
|
283233c2b216cef655ef3de395cab3de6a2fd857
|
anand84471/Python-for-Bioinfromatics-Oct-2021
|
/day8/dictionary_functions.py
| 572 | 3.921875 | 4 |
seq_records={
"YC1":"ATAGATGATAAGA",
"YC2":"ATGTTATATATAT"
}
print(seq_records)
#adding new value to dict
seq_records["YC3"]="ATGATAGATAATA"
print(seq_records)
#getting all the keys
print(seq_records.keys())
#getting all the values
print(seq_records.values())
#getting length of dict
print(len(seq_records))
dict_example={
"name":"Anand",
"email":"[email protected]"
}
dict_example["phone"]="123"
dict_example["address"]="Noida"
print(len(dict_example))
# clear() :Removes all the elements from the dictionary
# copy(): Returns a copy of the dictionary
|
ff1fdc757899946da657b84c9dd36cbcdcb69298
|
GaoPeiRu/python-vs-code
|
/6-3.py
| 143 | 3.65625 | 4 |
n=int(input())
i=0
while 2**(i+1)<=n:
i+=1
print(i,2**i)
#x = int(input())
#n = 1
#while 2 ** n <= x:
#n += 1
#print(n - 1, 2 ** (n - 1))
|
8321c3b13a79bd692806e6ddd4cdd58d3df1dfd3
|
LYblogs/python
|
/Python1808/第一阶段/day2-Python语法基础/Python/元祖语句.py
| 376 | 4.34375 | 4 |
# 创建一个空的元组
tuple1 = ()
print('tuple1 =',tuple1)
#创建带有元素的元组 (可以是不同类型的)
tuple2 = (1,2,3,'good',True)
print('tuple2 = ',tuple2)
#定义只有一个元素的元组
tuple3 = (1,)
print('tuple3 = ',tuple3)
#元组元素的访问
#格式: 元组名[下标]
tuple4 = (1,2,3,4,5)
print('tuple4[2] = ',tuple4[2])
#修改元组
|
aa15afa1a4e6436600a4bd7f58178053b7768bdb
|
gabrielleevaristo/algo-practice
|
/searching/jumpsearch.py
| 888 | 3.96875 | 4 |
# Time complexity: O(sqrt(n))
import math
def jumpSearch(arr,target):
# Get step size
step = math.sqrt(len(arr))
prev = 0
# Finds block where target is present (if present)
""" -1 is returned here when target is greater than
the last element in the array """
while arr[int(min(step,len(arr)))-1] < target:
prev = step
step += math.sqrt(len(arr))
if prev >= len(arr):
return -1
# Perform a linear search for target in block
# beginning with prev
while arr[int(prev)] < target:
prev += 1
# If next block or end of array is reached,
# target is not present
if prev == min(step,len(arr)):
return -1
# If target is at prev index, return it
if arr[int(prev)] == target:
return int(prev)
return -1
arr = [1,3,5,6,7,9,10]
print(jumpSearch(arr, 7))
|
0dbb2117c9998390c7058edb3d3564b5078913f5
|
BasicProbability/PythonCode_Fall2015
|
/src/week4_debugging_and_testing/distributions_solution.py
| 4,125 | 4.15625 | 4 |
'''
Created on Sep 19, 2015
@author: Philip Schulz
'''
from random import Random, shuffle
from math import factorial
class BinomialDistribution(object):
'''
This class implements the binomial distribution with parameters n and theta, where n
is the number i.i.d. random binary decisions and theta is the probability for a success.
Successes and failures can be arbitrary objects.
'''
success = None
failure = None
n = None
theta = None
random_generator = None
def __init__(self, success, failure, n = 10, theta = 0.5):
'''
Constructor
@param success: the value of a success
@param failure: the value of a failure
@param n: the value of the parameter n
@param theta: the value of the parameter theta
@raise ValueError: if theta is outside [0,1] or n <= 0
'''
self.set_n(n)
self.set_theta(theta)
self.success = success
self.failure = failure
self.random_generator = Random()
def set_n(self, n):
'''
Set a new value for the parameter n.
@param n: the new value for n
@raise ValueError: if n <= 0
'''
if n < 1:
raise ValueError("The argument n needs to be strictly greater than 0.")
self.n = n
def set_theta(self, theta):
'''
Set a new value for the parameter theta.
@param theta: the new value for the parameter theta
@raise ValueError: if theta is outside [0,1]
'''
if theta < 0 or theta > 1:
raise ValueError("The argument theta needs to lie in [0,1].")
self.theta = theta
def compute_probability(self, k):
'''
Compute the probability of obtaining exactly k successes.
@param k: the number of successes
@return The probability of obtaining exactly the specified number of successes
@raise ValueError: if k > n or k < 0
'''
if k > self.n:
raise ValueError("There cannot be more successes than draws. Decrease k!")
elif k < 0:
raise ValueError("The number of successes has to be positive.")
binomial_coefficient = factorial(self.n)/(factorial(k)*factorial(self.n-k))
return binomial_coefficient*(self.theta**k)*((1-self.theta)**(self.n-k))
def sample_with_k_successes(self, k):
'''
Randomly sample an outcome with exactly k successes.
@param k: the number of successes
@return: A randomly sampled outcome with exactly k successes.
@raise ValueError: if k > n or k < 0
'''
if k > self.n:
raise ValueError("There cannot be more successes than draws. Decrease k!")
elif k < 0:
raise ValueError("The number of successes has to be positive.")
sampled_value = list()
for i in xrange(k):
sampled_value.append(self.success)
for i in xrange(self.n-k):
sampled_value.append(self.failure)
shuffle(sampled_value)
return sampled_value
def sample(self):
'''
Samples a random outcome from this distribution.
@return A randomly sampled outcome from this distribution in form of a list.
'''
threshold = self.random_generator.random()
total = 0
for k in xrange(self.n+1):
total += self.compute_probability(k)
if total > threshold:
return self.sample_with_k_successes(k)
def sample_list(self, m):
'''
Samples m random outcomes from this distribution.
@param m: The number of outcomes to be sampled
@return A list of k random outcomes from this distribution.
@raise ValueError: if m < 1
'''
result = list()
for i in xrange(m):
result.append(self.sample())
return result
|
78a26a265a5f3283be50516249e44697453f77cc
|
milenaS92/HW070172
|
/L05/python/chap7/excercise03.py
| 386 | 4.09375 | 4 |
# exercise 3 chap 7
def gradeOfQuiz(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def main():
score = int(input("Please enter the score: "))
grade = gradeOfQuiz(score)
print("The corresponding grade is:", grade)
main()
|
7a2a8c2589b4a47dba283d4e3119d3b3b82dad09
|
antoniobarbozaneto/Curso_Descubra-Python
|
/condicionais_start.py
| 324 | 3.921875 | 4 |
#
# Arquivo de exemplo das estruturas condicionais
#
def Condicionais():
x,y = 10, 100 #Declarando 2 variaveis e passando os valores diretos para ela.
if(x < y):
print("X é menor que Y")
elif( x == y): #elif é igual ao else if
print("X é igual a Y")
else:
print("X é maior que Y")
Condicionais()
|
af55033e0c4c035a92bc9ea78aa54632da3de6a1
|
bicknest/coding_interview_problems
|
/strings_and_arrays/merge_calendars/python/merge_calendars.py
| 823 | 3.859375 | 4 |
# Merge two calendars
# Input is a list of tuples where the first item in tuple is start time and second item is end time
def merge_calendars(calendar):
if len(calendar) < 2:
return calendar
def sort_calendar(event):
return event[0]
calendar.sort(key=sort_calendar)
update_index = 0
for i in range(1, len(calendar)):
if calendar[update_index][1] >= calendar[i][0]:
calendar[update_index][1] = max(calendar[update_index][1], calendar[i][1])
calendar[update_index][0] = min(calendar[update_index][0], calendar[i][0])
else:
calendar[update_index + 1] = calendar[i]
update_index += 1
length_diff = len(calendar) - update_index
for i in range(1, length_diff):
calendar.pop()
return calendar
|
ef68695cffce198a6115b6afd14f0d7c2fe39156
|
ItsSamarth/ds-python
|
/hrfindAngle.py
| 237 | 3.9375 | 4 |
import math
ab,bc = float(input()) , float(input())
#calculate hypotenus
hype = math.hypot(ab,bc)
#calculate required angle
angle = round(math.degrees(math.acos(bc/hype)))
#degree symbol
degree = chr(176)
print(angle,degree, sep='')
|
6d45203bc95d206c45489d2c8e5e49c890f2d9da
|
fsancho1985/Infinity_school
|
/Lógica de Programação/exercicio_5_aula_29-05.py
| 186 | 3.953125 | 4 |
def fatorial(n1):
resultado = 1
for i in range(1, n1+1):
resultado *= i
return resultado
numero = int(input("Digite um número: "))
print(fatorial(numero))
|
16f1d011b15eb6538b6efef8f0cb3949ba8b53de
|
Preksha1998/python
|
/functions/calculator.py
| 815 | 3.90625 | 4 |
def addition(x,y):
add = x + y
return add
def subtraction(c,d):
sub = c - d
return sub
def multiplication(e,f):
mul = e * f
return mul
def division(g,h):
div = g / h
return div
a = int(input("enter value :"))
b = int(input("enter value :"))
ch = 1
while ch != 0 :
print("\n1.Addition..")
print("\n2.Subtraction..")
print("\n3.Multipliation..")
print("\n4.Division..")
print("\n0.exit..")
ch = int(input("enter your choice :"))
if (ch == 1):
result = addition(a,b)
print("\nAddition =",result)
elif (ch == 2):
result = subtraction(a,b)
print("\nSubtraction =",result)
elif (ch == 3):
result = multiplication(a,b)
print("\nMultiplication = ",result)
elif (ch == 4):
result = division(a,b)
print("\nDivision = ",result)
else :
print("\nenter correct choice..")
|
3936956c1b105c7fc2a081c5fedb08572862b6e2
|
H1world/Pythonbasic
|
/isdemos.py
| 4,567 | 3.921875 | 4 |
# def demo(num1, num2):
# if num1 < num2:
# print('too small')
# return False
# elif num1 > num2:
# print('too big')
# return False
# else:
# print('BINGO')
# return True
# from random import randint
# num = randint(1,100)
# print ('Guess what I think?')
# bingo = False
# while bingo == False:
# answer = int(input())
# bingo = (demo(answer, num))
# //
# if answer < num:
# print ('%d is too small'% answer)
# if answer > num:
# print ('too big?')
# if answer == num:
# print ('BINGO')
# bingo = True
# a = 0
# b = 1
# while b < 101:
# a = a + b
# b += 1
# print(a)
# for i in range(1, 101):
# print (i)
# print(1)
# a = input()
# print(2)
# a = 0
# for i in range(1,101):
# a = a + i
# print (a)
# print (sum(range(1, 101)))
# print("*\n***\n*****\n***\n*")
# num = 'Crossin'
# print('%s.is a good teacher.' % num)
# for i in range(0, 5):
# for j in range(0, i + 1):
# print('*',end='')
# print('')
# print ("%s's score is %d"%('mike',87))
# def sayHello():
# print ('hello')
# sayHello();
# a = [1,'daf',2,3,True]
# a.append('llal'); #添加到数组内
# del a[0];
# print(a)
# //随机从数组中获取一个
# from random import choice
# print ('Choose one side to shoot:')
# print ('left, center, right')
# you = input()
# print ('You kicked ' + you)
# direction = ['left', 'center', 'right']
# com = choice(direction)
# print ('Computer saved ' + com)
# if you != com:
# print ('Goal!')
# else:
# print ('Oops...')
# //split() 分割字符串,默认为''切割
# print('aaa'.split('a'))
# //join() 将数组转化连接成字符串
# s = ','
# li = ['apple', 'pear', 'orange']
# fruit = s.join(li)
# print(fruit)
# word = 'helloworld'
# for c in word:
# print(c) #word字符串每个字符都会print出来
# // py2版本打开文件:file() py3为open()
#read()函数把文件内所有内容读进一个字符串中
#readline() 读取一行内容
#readlines() 把内容按行读取至一个list中
#close为关闭文件,释放资源
# f = open('text.txt')
# data = f.read()
# print (data)
# f.close()
# a = input()
# ff = open('text2.txt')
# 'w'就是writing,以这种模式打开文件,原来文件中的内容会被你新写入的内容覆盖掉,如果文件不存在,会自动创建文件。 另外还有一种模式是'a',appending。它也是一种写入模式,但你写入的内容不会覆盖之前的内容,而是添加到文件中。 write写入
# ff.write(a)
#↓读取数据,操作数据求和
# FILE_OBJECT = open('text2.txt', encoding='UTF-8') # 修改文件编码格式.默认貌似是GBK 修改为UTF-8
# lines = FILE_OBJECT.readlines()
# FILE_OBJECT.close()
# results = []
# for line in lines:
# # print(line)
# data = line.split()
# # print(data)
# sum = 0
# for score in data[1:]:
# sum += int(score)
# result = '%s\t: %d\n' % (data[0], sum)
# results.append(result)
# print(results)
# output = open('result.txt', 'w', encoding='UTF-8')
# output.writelines(results)
# output.close()
# ↓break 强制终止循环
# while True:
# a = input()
# if a == 'EOF':
# break
# for i in range(10):
# a = input()
# if a == 'SOS':
# break
# ↓continue 终止此次循环继续下面的循环
# i=0
# while i<5:
# i+=1
# for j in range(3):
# print (j)
# if j==2:
# break
# for k in range(3):
# if k==2:
# continue
# print(k)
# if i > 3:
# break
# print(i)
# ↓ try...except-块 用来处理异常语句.
# try:
# FILE_OBJECT = open('text2.txt',encoding='UTF-8') #如果不加encoding='UTF-8' 那么将报错.
# a = FILE_OBJECT.read()
# print(a)
# except:
# print ('File not exists.')
# print('dadaf')
# score = {
# '萧峰': 95,
# '段誉': 97,
# '虚竹': 89
# }
# print (score['段誉'])
# for name in score:
# print (score[name])
from turtle import *
def curvemove():
for i in range(200):
right(1)
forward(1)
color('red', 'pink')
begin_fill()
left(140)
forward(111.65)
curvemove()
left(120)
curvemove()
forward(111.65)
end_fill()
done()
# pensize(1)
# pencolor('red')
# fillcolor('pink')
# speed(5)
# up()
# goto(-30, 100)
# down()
# begin_fill()
# left(90)
# circle(120, 180)
# circle(360, 70)
# left(38)
# circle(360, 70)
# circle(120, 180)
# end_fill()
# up()
# goto(-100, -100)
# down()
|
13ea27c0f0696c17d1c4ef9ff9b99dd952c96202
|
daniela-mejia/Python-Net-idf19-
|
/PhythonAssig/5-06-19 Assigment7/coin.py
| 664 | 4.0625 | 4 |
#Write a program to make change for an amount of money from 0 through99 cents input by the user
#The output of the program should show the number of coins from each denomination used to make the change.
#Daniela Mejia
def main ():
coin = int(input('write the amount of money from 0 to 99 cents you need: '))
if (coin > 100) :
print("WRONG TYPE A RIGHT VARIABLE")
quit ()
elif (coin < 100) :
print(coin//25, "quarters")
coin = coin%25
print(coin//10, "dimes")
coin = coin%10
print(coin//5, "nickles")
coin = coin%5
print(coin//1, "pennies")
main ()
|
1f7167a8cee49e292deb9e83d8f78def254edf98
|
elijp616/CS-2340-Georgia-Tech-Objects-and-Design
|
/CS2340-62/app/entities.py
| 11,409 | 3.5 | 4 |
from enum import Enum
from app.ships import *
import random
import math
import json
class techLevel(Enum):
PREAG = 1
AGRICULTURE = 2
MEDIEVAL = 3
RENAISSANCE = 4
INDUSTRIAL = 5
MODERN = 6
FUTURISTIC = 7
def to_json(self):
data["name"] = self.name
data["value"] = self.value
return json.dumps(data)
class Item():
name = ""
cargo_space = 1
price = 0
def __init__(self, name="", cargo_space=1, price=1):
self.name = name
self.cargo_space = cargo_space
self.price = price
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_cargo_space(self):
return self.cargo_space
def set_cargo_space(self, cargo_space):
self.cargo_space = cargo_space
def get_price(self):
return self.price
def set_price(self, price):
self.price = price
def to_json(self):
data={}
data["name"] = self.name
data["cargo_space"] = self.cargo_space
data["price"] = self.price
return json.dumps(data)
class Market():
# name, cargo space, price
tech_level = techLevel(3)
price_multiplier = 1
items = [Item("spear", 3, 5),
Item("axe", 2, 6),
Item("hatchet", 2, 7),
Item("arrowhead", 1, 1),
Item("beef", 1, 5),
Item("chicken", 1, 5),
Item("animal pelt", 3, 12),
Item("flint", 1, 1),
Item("stick", 3, 1),
Item("root", 1, 1),
] # default to the PREAG, add more items as we check each tech level
def get_tech_level(self):
return self.tech_level
def fill_inventory(self):
#print("dwadwaL " + str(self.tech_level))
print("inventory is being filled with: " + str(self.tech_level))
if self.tech_level.value >= 2: # AGRI
agri_items = [Item("rake", 3, 5),
Item("carrots", 2, 5),
Item("soil", 1, 3),
Item("cow", 10, 10),
Item("pig", 9, 10),
Item("knife", 1, 8),
Item("wheat", 2, 7),
Item("cotton", 2, 13),
Item("tobacco", 2, 11),
Item("hoe", 3, 8),
]
self.items = agri_items
if self.tech_level.value >= 3:
medi_items = [Item("longsword", 10, 15),
Item("shield", 9, 15),
Item("saddle", 5, 13),
Item("bow", 4, 13),
Item("arrow", 2, 7),
Item("dagger", 2, 8),
Item("candle", 1, 9),
Item("plate", 1, 5),
Item("robes", 3, 14),
Item("poison", 1, 15),
]
self.items = medi_items
if self.tech_level.value >= 4:
rena_items = [Item("paintbrush", 2, 10),
Item("canvas", 6, 10),
Item("book", 1, 20),
Item("art", 3, 20),
Item("journal", 2, 15),
Item("compass", 1, 14),
Item("pencil", 1, 9),
Item("pen", 1, 9),
Item("glass", 5, 16),
Item("spectacle", 1, 20),
]
self.items = rena_items
if self.tech_level.value >= 5:
indu_items = [Item("gun", 2, 25),
Item("cigarette", 1, 20),
Item("coal", 3, 25),
Item("jacket", 2, 21),
Item("top hat", 3, 23),
Item("lightbulb", 2, 30),
Item("ink", 3, 25),
Item("dog", 5, 40),
Item("firewood", 6, 30),
Item("collared shirt", 4, 45),
]
self.items = indu_items
if self.tech_level.value >= 6:
mode_items = [Item("phone", 3, 55),
Item("laptop", 1, 20),
Item("tablet", 3, 25),
Item("medicine", 2, 21),
Item("fast food", 3, 23),
Item("DVD", 2, 30),
Item("newspaper", 3, 25),
Item("protein bar", 5, 40),
Item("pepper spray", 6, 30),
Item("graphic t-shirt", 4, 45),
]
self.items = mode_items
if self.tech_level.value >= 7:
futu_items = [Item("laser gun", 3, 70),
Item("robot", 8, 50),
Item("super medicine", 3, 25),
Item("satellite", 12, 90),
Item("solar ray", 3, 23),
Item("flying car", 2, 130),
Item("cool jacket", 3, 25),
Item("e-sunglasses", 1, 40),
Item("smart dog", 6, 30),
Item("hologram", 4, 45),
]
self.items = futu_items
# Run all the items through the price calculator
for item in self.items:
new_price = item.get_price() * 1+self.price_multiplier
print("setting old price: " + str(item.get_price()) + " to new one: " + str(new_price))
item.set_price(new_price)
def __init__(self, tech_level, price_multiplier):
self.tech_level = tech_level
self.price_multiplier = price_multiplier
print("brought in: " + str(tech_level.value))
self.fill_inventory()
def get_current_cargo(self):
return self.items
def to_json(self):
data = []
for item in self.items:
data.append(item.to_json())
return json.dumps(data)
class Region():
x_coord = 0
y_coord = 0
tech_level = techLevel(1)
name = ""
price_multiplier = 0
market = None
def __init__(self, x, y, tech_level, name):
print("region tech??: " + str(tech_level))
self.x_coord = x
self.y_coord = y
self.tech_level = tech_level
self.name = name
self.price_multiplier = round(abs(x + y) / 500, 2)
self.market = Market(tech_level, self.price_multiplier)
self.market.fill_inventory()
print(self.market.get_current_cargo()[0].name)
def get_x(self):
return self.x_coord
def get_y(self):
return self.y_coord
def get_name(self):
return self.name
def get_tech_level(self):
return self.tech_level
def get_market(self):
return self.market
def to_json(self):
data = {}
data["name"] = self.name
data["x_coord"] = self.x_coord
data["y_coord"] = self.y_coord
data["tech_level"] = self.tech_level.to_json()
data["market"] = self.market.to_json()
return json.dumps(data)
class User():
name = ""
pilot_skill = 0
fighter_skill = 0
merchant_skill = 0
engineer_skill = 0
credits = 0
region = Region(0, 0, techLevel(1), "Default")
ship = Ladybug()
def __init__(self):
pass
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_pilot_skill(self):
return self.pilot_skill
def set_pilot_skill(self, skill):
self.pilot_skill = skill
def get_fighter_skill(self):
return self.fighter_skill
def set_fighter_skill(self, skill):
self.fighter_skill = skill
def get_merchant_skill(self):
return self.merchant_skill
def set_merchant_skill(self, skill):
self.merchant_skill = skill
def get_engineer_skill(self):
return self.engineer_skill
def set_engineer_skill(self, skill):
self.engineer_skill = skill
def get_credits(self):
return self.credits
def set_credits(self, credits):
self.credits = credits
def get_region(self):
return self.region
def set_region(self, region):
self.region = region
def set_ship(self, ship):
self.ship = ship
def get_ship(self):
return self.ship
def to_json(self):
data["name"] = self.name
data["credits"] = self.credits
data["pilot_skill"] = self.pilot_skill
data["fighter_skill"] = self.fighter_skill
data["merchant_skill"] = self.merchant_skill
data["engineer_skill"] = self.engineer_skill
data["region"] = self.region.get_name()
data["ship"] = self.ship.to_json()
class Game():
names = ['Plantar', 'Jantar', 'Cantar', 'Exodous', 'Beef',
'Tanger', 'Pangeria', 'Tanzia', 'Lokus', 'Asakuki']
gameDifficulty = ""
x_coord = 10
def __init__(self):
pass
def set_difficulty(self, difficulty):
self.gameDifficulty = difficulty
def start_game(self, player, universe):
if (self.gameDifficulty == "easy"):
self.x_coord = 1000
elif (self.gameDifficulty == "medium"):
self.x_coord = 500
player.set_credits(self.x_coord)
universe.create_universe(self.names)
player.set_region(universe.regionList[random.randint(0, 9)])
def get_difficulty(self):
return self.gameDifficulty
class Universe():
regionList = []
def __init__(self):
pass
def get_region(self, num):
return self.regionList[num]
def get_region_list(self):
return self.regionList
def create_universe(self, regions):
if (self.regionList != []):
self.regionList = []
usedCoords = []
for region in regions:
currCoords = []
x = random.randrange(-200, 200, 5)
y = random.randrange(-200, 200, 5)
currCoords.append(x)
currCoords.append(y)
if currCoords not in usedCoords:
usedCoords.append(currCoords)
else:
x = random.randrange(-200, 200, 3)
y = random.randrange(-200, 200, 3)
currCoords.append(x)
currCoords.append(y)
usedCoords.append(currCoords)
self.regionList.append(Region(x, y, techLevel(random.randint(1, 7)), region))
def to_json(self):
data = []
for region in self.regionList:
data.append(region.to_json())
return json.dumps(data)
class Calculations:
def __init__(self):
pass
def distance_x_y(self, x1, y1, x2, y2):
return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2))
|
f9f71eaa0492e3e540d5a0b9e10f91e194bcffb9
|
VINSHOT75/PythonPractice
|
/python/replace01.py
| 230 | 3.71875 | 4 |
a = int(input('enter a number'))
x=1
re=0
while a>0 :
x=a%10
if x==0:
x=1
elif x==1:
x=0
re = re*10 + x
a =a//10
rev = 0
while re>0 :
rev = int(re%10)
print(rev , end='')
re= re//10
|
608d8c55d009f0150a234fddf5a1d422dfe94fb4
|
Queena805/100-Days-Python
|
/Day10/Calculator.py
| 1,025 | 4.125 | 4 |
#calculator
from replit import clear
from art import logo
#add
def add(n1,n2):
return n1 + n2
#subtract
def subtract(n1, n2):
return n1 - n2
#Multiply
def multiply(n1,n2):
return n1 * n2
#Divide
def devide(n1, n2):
return n1/n2
operations = {}
operations["+"] = add
operations["-"] = subtract
operations["*"] = multiply
operations["/"] = devide
def calculator():
print(logo)
num1 = float(input("What is the first number?: "))
for symbol in operations:
print(symbol)
should_continue = True
while should_continue:
operation_symbol = input("Pick an operation: ")
num2 = float(input("What is the next number?: "))
calculation = operations[operation_symbol]
answer = calculation(num1, num2)
print(f"{num1}{operation_symbol}{num2} = {answer}")
result = input(f"Type 'y' to continue calculating with {answer}, or type 'n' to exit.: ")
if result == "y":
num1 = answer
else:
should_continue = False
clear()
calculator()
calculator()
|
76804de0e98d9541ec681c140dd8512e754e71ab
|
taoranzhishang/Python_codes_for_learning
|
/study_code/class_code/26String_length_calc.py
| 489 | 4.375 | 4 |
def string_length_calc(str):
count = 0
for data in str:#遍历字符串,轮巡一次,计数器加1
count += 1
return count
def main():
string = input("Please enter a string:")
characters_count = string_length_calc(string)
print("The number of characters in this string are: %d" % characters_count if characters_count > 1 \
else "The number of characters in this string is: %d" % characters_count)
if __name__ == "__main__":
main()
|
cbe2cc69a1a32adc68300359ca5248866e449e2d
|
satishp962/40-example-python-scripts
|
/6.py
| 617 | 3.90625 | 4 |
num = int(input("Enter the no. of lines: "))
half = num // 2
for p in range(half):
print('*', end='')
for l in range(num):
print(' ', end='')
print('*')
for i in range(half):
for j in range(half - i):
if j==0:
print('*', end='')
else:
print(' ', end='')
print('*', end='')
if i != 0:
for k in range(i):
print(' ', end='')
for j in range(i, 0, -1):
print(' ', end='')
print('*', end='')
for j in range(half - i - 1):
print(' ', end='')
print('*')
|
3abea0ab175f2255eeafb50c358d61826aef47f8
|
tigju/Sprint-Challenge--Data-Structures-Python
|
/reverse/reverse.py
| 1,629 | 4.0625 | 4 |
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:
def __init__(self):
self.head = None
def add_to_head(self, value):
node = Node(value)
if self.head is not None:
node.set_next(self.head)
self.head = node
def contains(self, value):
if not self.head:
return False
current = self.head
while current:
if current.get_value() == value:
return True
current = current.get_next()
return False
def reverse_list(self, node, prev):
if node == self.head:
cur = self.head
while cur:
print(cur.get_value())
nxt = cur.get_next()
cur.set_next(prev)
prev = cur
cur = nxt
self.head = prev
else:
cur = node
while cur:
print(cur.get_value())
nxt = cur.get_next()
cur.set_next(prev)
prev = cur
cur = nxt
node = prev
list1 = LinkedList()
list1.add_to_head(1)
list1.add_to_head(2)
list1.add_to_head(3)
# print(list1.head.get_value())
# print(list1.head.get_next().get_value())
# print(list1.head.get_next().get_next().get_value())
# print(list1.reverse_list(list1.head, None))
|
1dd14904a9ac322bf76124f68c5196785e41dd2d
|
midasscheffers/room_game
|
/new/classes/player.py
| 4,138 | 3.5625 | 4 |
import random
class player:
def __init__(self):
self.name = ''
self.x = 1
self.y = 1
self.char = '@'
self.inventory = ["key"]
self.show_data = False
self.show_data_str = ""
self.score = 0
self.health = 100
self.use_functions = {"sword" : self.attack, "healing potion" : self.heal}
def print_data(self):
if self.show_data:
print(self.show_data_str)
def draw_player(self, _map):
player_map = _map.copy()
player_map[self.y] = player_map[self.y][:self.x] + self.char[0] + player_map[self.y][self.x+1:]
return player_map
def move(self, user_inp, w):
if (user_inp == "d"):
if(not w._map[self.y][self.x+1] == w.wall_char):
self.x += 1
self.show_data = False
else:
self.show_data = True
self.show_data_str = "you can't move here\n"
elif (user_inp == "a"):
if(not w._map[self.y][self.x-1] == w.wall_char):
self.x -= 1
self.show_data = False
else:
self.show_data = True
self.show_data_str = "you can't move here\n"
elif (user_inp == "s"):
if(not w._map[self.y+1][self.x] == w.wall_char):
self.y += 1
self.show_data = False
else:
self.show_data = True
self.show_data_str = "you can't move here\n"
elif (user_inp == "w"):
if(not w._map[self.y-1][self.x] == w.wall_char):
self.y -= 1
self.show_data = False
else:
self.show_data = True
self.show_data_str = "you can't move here\n"
else:
self.show_data = False
def attack(self, room, j):
room.monsterHealth -= 20
if random.randint(1,20) == 19:
self.inventory.remove(j)
self.show_data = True
self.show_data_str = "your sword broke"
if room.monsterHealth <= 0:
room.monsterHere = False
self.show_data = True
self.show_data_str = "you have slain the monster"
self.score += 200
def heal(self, room, j):
self.health += 20
self.inventory.remove(j)
self.score += 50
def player_logic(self, user_inp, rooms):
# if user_inp[0:4] != "use ":
# return
# for room in rooms:
if user_inp[0:4] == "use ":
for room in rooms:
if room.x == self.x and room.y == self.y:
if (user_inp[4:-1] + user_inp[-1]) in self.inventory[::-1]:
j = user_inp[4:-1] + user_inp[-1]
# self.use_functions[user_inp[4:-1] + user_inp[-1]](room, j)
try:
self.use_functions[user_inp[4:-1] + user_inp[-1]](room, j)
except:
self.show_data = True
self.show_data_str = "you can't use this Item:" + user_inp[4:-1] + user_inp[-1]
break
else:
self.show_data = True
self.show_data_str = "you haven't got that Item"
if user_inp == "i":
self.show_data = True
self.show_data_str = str(self.inventory) + "\n"
if user_inp[0:5] == "drop ":
for i in range(len(rooms)):
if rooms[i].x == self.x and rooms[i].y == self.y:
for j in self.inventory[::-1]:
if user_inp[5:-1] + user_inp[-1] == j:
rooms[i].inventory.append(j)
print()
self.show_data = True
self.show_data_str = "You droped: " + j + "\n"
self.inventory.remove(j)
break
|
94de54641eb2e9d115c0f8d481a2bfa8ba7732df
|
Jarvis1217/Python
|
/Python/24点.py
| 737 | 3.53125 | 4 |
import random
import itertools
# Give random number list
def Give_num():
li=[random.randint(1,9) for i in range(4)]
return li
# List to String
def st(num_list):
li=[str(i) for i in num_list]
return li
# 24 calculation
def calc_24(li):
result=[]
symbols=["+","-","*","/"]
for li in itertools.permutations(li,4):
for op in itertools.product(symbols,repeat=4):
n=li[0]+op[0]+li[1]+op[1]+li[2]+op[2]+li[3]
if eval(n) == 24:
result.append(n)
return result
# main()
num_list=Give_num()
print('随机数组:%s' %num_list)
num_list=st(num_list)
res=calc_24(num_list)
for i in set(res):
print(i +'=24')
|
051342987950075110463a40aaa5fa74bc90454f
|
donald-f-ferguson/GoTHW
|
/src/data_tables/BaseDataTable.py
| 5,682 | 4.09375 | 4 |
# Import package to enable defining abstract classes in Python.
# Do not worry about understanding abstract base classes. This is just a class that defines
# some methods that subclasses must implement.
from abc import ABC, abstractmethod
class DataTableException(Exception):
"""
A simple class that maps underlying implementation exceptions to generic exceptions.
"""
invalid_method = 1001
# General
def __init__(self, code, message):
self.code = code
self.message = message
def __str__(self):
result = (
type(self), {"code": self.code, "message": self.message}
)
result = str(result)
return result
class BaseDataTable(ABC):
"""
The implementation classes (XXXDataTable) for CSV database, relational, etc. will extend the
base class and implement the abstract methods.
"""
def __init__(self, entity_type_name, connect_info, key_columns=None, context=None):
"""
:param entity_type_name: Name of the logcal entity type. This maps to various abstractions in
underlying stores, e.g. file names, RDB tables, Neo4j Labels, ...
:param connect_info: Dictionary of parameters necessary to connect to the data. See examples in subclasses.
:param key_columns: List, in order, of the columns (fields) that comprise the primary key.
A primary key is a set of columns whose values are unique and uniquely identify a row. For Appearances,
the columns are ['playerID', 'teamID', 'yearID']
:param contex: Holds context and environment information.
"""
self._table_name = entity_type_name
self._connect_info = connect_info
self._key_columns = key_columns
self._context = context
@abstractmethod
def find_by_primary_key(self, key_fields, field_list=None, context=None):
"""
:param key_fields: The values for the key_columns, in order, to use to find a record. For example,
for Appearances this could be ['willite01', 'BOS', '1960']
:param field_list: A subset of the fields of the record to return. The CSV file or RDB table may have many
additional columns, but the caller only requests this subset.
:return: None, or a dictionary containing the columns/values for the row.
"""
pass
@abstractmethod
def find_by_template(self, template, field_list=None, limit=None, offset=None, order_by=None, context=None):
"""
:param template: A dictionary of the form { "field1" : value1, "field2": value2, ...}. The function will return
a derived table containing the rows that match the template.
:param field_list: A list of requested fields of the form, ['fielda', 'fieldb', ...]
:param limit: Do not worry about this for now.
:param offset: Do not worry about this for now.
:param order_by: Do not worry about this for now.
:return: A derived table containing the computed rows.
"""
pass
@abstractmethod
def insert(self, new_entity, context=None):
"""
:param new_record: A dictionary representing a row to add to the set of records. Raises an exception if this
creates a duplicate primary key.
:return: None
"""
pass
@abstractmethod
def delete_by_template(self, template, context=None):
"""
Deletes all records that match the template.
:param template: A template.
:return: A count of the rows deleted.
"""
pass
@abstractmethod
def delete_by_key(self, key_fields, Context=None):
"""
Delete record with corresponding key.
:param key_fields: List containing the values for the key columns
:return: A count of the rows deleted.
"""
pass
@abstractmethod
def update_by_template(self, template, new_values, context=None):
"""
:param template: A template that defines which matching rows to update.
:param new_values: A dictionary containing fields and the values to set for the corresponding fields
in the records. This returns an error if the update would create a duplicate primary key. NO ROWS are
update on this error.
:return: The number of rows updates.
"""
pass
@abstractmethod
def update_by_key(self, key_fields, new_values, context=None):
"""
:param key_fields: List of values for primary key fields
:param new_values: A dictionary containing fields and the values to set for the corresponding fields
in the records. This returns an error if the update would create a duplicate primary key. NO ROWS are
update on this error.
:return: The number of rows updates.
"""
pass
@abstractmethod
def query(self, query_statement, args, context=None):
"""
Passed through/executes a raw query in the native implementation language of the backend.
:param query_statement: Query statement as a string.
:param args: Args to insert into query if it is a template
:param context:
:return: A JSON object containing the result of the operation.
"""
pass
@abstractmethod
def load(self, rows=None):
"""
Loads data into the data table.
:param rows:
:return: Number of rows loaded.
"""
@abstractmethod
def save(self, context):
"""
Writes any cached data to a backing store.
:param context:
:return:
"""
|
918d1aa43016f2cb3376023d39245d056b526fa6
|
AmitBaanerjee/Data-Structures-Algo-Practise
|
/leetcode problems/868.py
| 1,403 | 4 | 4 |
# 868. Binary Gap
#
# Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.
#
# If there aren't two consecutive 1's, return 0.
#
# Example 1:
#
# Input: 22
# Output: 2
# Explanation:
# 22 in binary is 0b10110.
# In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
# The first consecutive pair of 1's have distance 2.
# The second consecutive pair of 1's have distance 1.
# The answer is the largest of these two distances, which is 2.
# Example 2:
#
# Input: 5
# Output: 2
# Explanation:
# 5 in binary is 0b101.
# Example 3:
#
# Input: 6
# Output: 1
# Explanation:
# 6 in binary is 0b110.
# Example 4:
#
# Input: 8
# Output: 0
# Explanation:
# 8 in binary is 0b1000.
# There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.
#
class Solution:
def binaryGap(self, number: int) -> int:
binval=bin(number)
positions=[]
for i in range(2,len(binval)):
if binval[i]=='1':
positions.append(i)
diff=0
if len(positions)==1:
return 0
else:
for i in range(len(positions)-1):
tempdiff=abs(positions[i]-positions[i+1])
if tempdiff>diff:
diff=tempdiff
return diff
|
72b377dffaecd314e6c5794d4b06701d8d8e84eb
|
JEONJinah/Shin
|
/inner.py
| 1,885 | 3.5625 | 4 |
# abs
print(-3, abs(-3), abs(3))
# ALL / ANY (AND / OR 유사한 동작)
list_a = [1, 2, 3, 0]
list_b = [1, 2, 3]
# False, True, ... 예상..값 작성하면 좋을 것 같습니다
print(all(list_a), all(list_b), any(list_a), any(list_b), any([0, "", []]))
# Chr 내장함수 해볼 것
# dir: 객체 또는 자료형에서 가지고 있느 내장함수의 목록을 반환
list_var = [1, 2, 3]
str_var = "ABC"
dict_var = {'key': 'value'}
print(dir(list_var))
print(dir(str_var))
print(dir(dict_var))
# divmod: 나눗셈을 몫과 나머지를 반환하는 내장ㅎ ㅏㅁ수
# 함수로 작성
def div_mod(in_a, in_b):
return ((in_a//in_b), (in_a % in_b))
print(divmod(7, 3))
print(div_mod(7, 3))
# (ENUM)
for i, name in enumerate(['body', 'foo', 'bar']):
print(i, name)
# for(i = 0; i < max_num; i++)
# {
# # operation
# if array[i] > 10
# }
# filter | filter(func, iterable 자료형)
# Func: def, lambda
def func_positive(x):
return x > 0
print(list(filter(func_positive, [7, 2, -3, -4, 1])))
print(list(filter(lambda x: x > 0, [7, 2, -3, -4, 1])))
# id 변수 파트에서 설명했으므로 Pass
# id: 객체의 메모리 주소를 반환
# input: input의 결과는 문자열이다...
# len: 객체의 length를 반환하는 내장함수로 대부분의 객체의 내장함수에
# define NUM_ARR_A (100)
# for (i=0; i < NUM_ARR_A; i++)
# 모든 자료형에서의 형변환은 프로그램을 작성하면서 ... 실습해보는 것으로...
# map| map(func, iterable 자료형)
def two_times(x): return x * 2
in_list = [1, 2, 3, 4]
print(list(map(two_times, in_list)))
# 함수대신에 lambda 를 사용해도 됨.
# zip
list_1 = [1, 2, 3]
list_2 = [4, 5, 6]
list_3 = list(zip(list_1, list_2))
print(list_3, list_3[0][0], list_3[0][1])
print(list(zip("abc", "def")))
|
0eed54a44e46a5b540b6eadf882142856e641ad2
|
wonjong-github/Python_algorithm
|
/leetcode/2.py
| 1,185 | 3.8125 | 4 |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def addTwoNumbers(self, l1: ListNode, l2: ListNode)->ListNode:
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
num1 = 0
index = 0
while l1 is not None:
num1 = (10**index)*l1.val + num1
l1 = l1.next
index+=1
num2 = 0
index = 0
while l2 is not None:
num2 = (10 ** index) * l2.val + num2
l2 = l2.next
index += 1
num1 += num2
def go(num:int):
if not num1:
return ListNode(0, None)
if not num:
return None
ret = ListNode(num%10, None)
ret.next = go(num//10)
return ret
return go(num1)
a = Solution()
arg1, arg2 = None, None
for n in [4, 2, 1]:
temp = ListNode(n, None)
arg1, arg1.next = temp, arg1
for n in [4, 3, 1]:
temp = ListNode(n, None)
arg2, arg2.next = temp, arg2
a.addTwoNumbers(arg1, arg2)
|
e2a9ec536b2a85e7a6214d70eb2eed8fe3947e54
|
amartyahatua/programpractice
|
/Ritu/IntersectionOfArray.py
| 1,086 | 3.671875 | 4 |
class Intersection:
def findUnion(self, array1, array2):
result = []
while(len(array1)>0 and len(array2)>0):
temp1 = array1[0]
temp2 = array2[0]
if(temp1 == temp2):
result.append(temp1)
array1.pop(0)
array2.pop(0)
elif(temp1<temp2):
result.append(temp1)
array1.pop(0)
else:
result.append(temp2)
array2.pop(0)
if(len(array1)>0):
result.extend(array1)
if(len(array2)>0):
result.extend(array2)
return result
def findIntersection(self, array1, array2):
result = []
for i in range(len(array1)):
temp = array1[i]
if(temp in array2):
result.append(temp)
return result
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 7, 8, 9]
inter = Intersection()
print(inter.findUnion(array1, array2))
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 7, 8, 9]
print(inter.findIntersection(array1, array2))
|
6aec88f8531ce166ff03af1717791aae9ac4b045
|
shivapriya89/leetcode
|
/findComplement.py
| 324 | 3.578125 | 4 |
class Solution(object):
def findComplement(self, num):
num=format(num,'b')
s=''
for char in num:
if char=='1':
s+=('0')
if char=='0':
s+=('1')
return int(s,2)
if __name__=='__main__':
a=Solution()
print(a.findComplement(5))
|
499ad7fff98a5a07b876507cbd64332d60691a64
|
pasignature/holbertonschool-higher_level_programming
|
/0x08-python-more_classes/101-nqueens.py
| 1,635 | 3.71875 | 4 |
#!/usr/bin/python3
"""Module is to solve the N-Queens challenge problem"""
from sys import argv
def checkspot(board, r, c):
n = len(board) - 1
if board[r][c]:
return 0
for row in range(r):
if board[row][c]:
return 0
i = r
j = c
while i > 0 and j > 0:
i -= 1
j -= 1
if board[i][j]:
return 0
i = r
j = c
while i > 0 and j < n:
i -= 1
j += 1
if board[i][j]:
return 0
return 1
def initboard(n=4):
b = []
for r in range(n):
b.append([0 for c in range(n)])
return b
def findsoln(board, row):
for col in range(len(board)):
if checkspot(board, row, col):
board[row][col] = 1
if row == len(board) - 1:
print(convtosoln(board))
board[row][col] = 0
continue
if findsoln(board, row + 1):
return board
else:
board[row][col] = 0
return None
def convtosoln(board):
soln = []
n = len(board)
for r in range(n):
for c in range(n):
if board[r][c]:
soln.append([r, c])
return soln
def nqueens(n=4):
for col in range(n):
board = initboard(n)
board[0][col] = 1
findsoln(board, 1)
if __name__ == "__main__":
if len(argv) != 2:
print("Usage: nqueens N")
exit(1)
try:
n = int(argv[1])
except:
print("N must be a number")
exit(1)
if n < 4:
print("N must be at least 4")
exit(1)
nqueens(n)
|
95e4c97ad349f487b243a5d497629ae983d2a226
|
Reldan/python-generators-tutorial
|
/yieldex.py
| 316 | 3.96875 | 4 |
# yieldex.py example of yield, return in generator functions
def gy():
x = 2
y = 3
yield x, y, x+y
z = 12
yield z/x
print z/y
return
def main():
g = gy()
print g.next() # prints x, y, x+y
print g.next() # prints z/x
print g.next()
if __name__ == '__main__':
main()
|
ca1cff9db2d640c6c598f8cc711d478b8f6353e1
|
lex-pan/Wave-1
|
/compound_interest.py
| 195 | 3.796875 | 4 |
initialAmount = int(input())
year1 = initialAmount + initialAmount*0.04
print(round(year1, 2))
year2 = year1 + year1*0.04
print(round(year2, 2))
year3 = year2 + year2*0.04
print(round(year3, 2))
|
59031a3e9d30318fdb7899751e3c7f7ddf7caf0e
|
yenvth57/sector-detection
|
/sector-detection.py
| 222 | 3.734375 | 4 |
import csv
sector_name: str = input('Please input a sector name: ')
with open('input.csv', 'r') as sector:
r = csv.reader(sector)
for i in range(len(r)):
if sector_name in r[i][13]:
print(r[i])
|
2399a71da6a09a9ddf0a818a471214c49e73d0bb
|
avallonking/UCSD-iGEM_2014
|
/Modeling/DEVICE_1.py
| 1,147 | 3.5625 | 4 |
# -*- coding: utf-8 -*-
"""
@author: youbin
"""
def device_1(od, input, output, dt = 0.1):
''' This device is device_1''' ## Here is the discription of device
k1 = 0.3
k2 = 0.5
k3 = 0
input_1 = input - k1*od*input*dt
output_1 = output + (k2*input*od - k3*od)*dt
return (input_1, output_1)
def device_2(od, input, output, dt = 0.1):
''' This device is device_2'''
k1 = 0.3
k2 = 0.5
k3 = 0
input_1 = input - k1*od*input*dt
output_1 = output + (k2*input*od - k3*od)*dt
return (input_1, output_1)
def device_3(od, input, output, dt = 0.1):
k1 = 0.3
k2 = 0.5
k3 = 0
input_1 = input - k1*od*input*dt
output_1 = output + (k2*input*od - k3*od)*dt
return (input_1, output_1)
def device_4(od, input, output, dt = 0.1):
k1 = 0.3
k2 = 0.5
k3 = 0
input_1 = input - k1*od*input*dt
output_1 = output + (k2*input*od - k3*od)*dt
return (input_1, output_1)
def device_5(od, input, output, dt = 0.1):
k1 = 0.3
k2 = 0.5
k3 = 0
input_1 = input - k1*od*input*dt
output_1 = output + (k2*input*od - k3*od)*dt
return (input_1, output_1)
|
db8928f19afe6241b8c9939fa1b83c5d95a7fe44
|
Afsarsoft/python
|
/17_01_02_class_intro.py
| 934 | 3.90625 | 4 |
# pyright: strict
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Why classes?
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Classes allow us to logically group our data and code (attributes and methods).
class Car:
pass # use pass for empty class
# Define objects
toyota: Car
honda: Car
audi: Car
# Create objects
# We create objects based on Classes
# Note: Object or instance of class car
toyota = Car()
honda = Car()
audi = Car()
print(toyota)
print(honda)
print(audi)
print(type(toyota))
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class Rectangle:
pass
# Define objects
rectangle1: Rectangle
rectangle2: Rectangle
rectangle3: Rectangle
# Create objects
rectangle1 = Rectangle()
rectangle2 = Rectangle()
rectangle3 = Rectangle()
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
8a54dbb1a1da9cf58b1b323773830e09ffdcd837
|
schnneee/POOP0311
|
/day3_demo7.py
| 647 | 3.875 | 4 |
a1 = True
a2 = False
print(a1 and a1, a1 or a2, a2 and a2, a2 or a2, not a1, not a2)
B = [True, False, None, 3.14, "Hello world", '打個中文', 500]
print("-- True and b ------------------")
# A and B 時,當A為true,B可為任何東西
for b in B:
print(a1 and b)
print("-- False and b ------------------")
# A and B 時,當A為false,B不管是啥都為false
for b in B:
print(a2 and b)
print("-- True or b ------------------")
# A or B 時,當A為true,B不管是啥都為true
for b in B:
print(a1 or b)
print("-- False or b ------------------")
# A or B 時,當A為false,A會是B
for b in B:
print(a2 or b)
|
679981690edc1b45cc8f256aaaf5b9b193577876
|
TwoRavens/raven-metadata-service
|
/preprocess/raven_preprocess/msg_util.py
| 541 | 3.53125 | 4 |
"""Convenience methods for printing to screen"""
import sys
def msg(user_msg):
"""Print"""
print(user_msg)
def dashes(char='-'):
"""Dashed line"""
msg(40*char)
def msgt(user_msg):
"""print message with dashed line before/after"""
dashes()
msg(user_msg)
dashes()
def msgn(user_msg):
"""print message with dashed line before"""
dashes()
msg(user_msg)
def msgx(user_msg):
"""Print message and exit program--hard exit"""
dashes('=')
msg(user_msg)
dashes('=')
sys.exit(0)
|
5c071aae056f398e74224b3bb1459783827994a4
|
fnqn/lphython27
|
/def_enroll_001.py
| 738 | 3.84375 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
####define 一年级小学生注册####
####only name gender####
def enroll(name, gender):
print 'name:', name
print 'gender:', gender
enroll('Sarah','F')
####only name gender age city####
def enroll(name, gender, age=6, city='Beijing'):
print 'name: ', name
print 'gender: ', gender
print 'age: ', age
print 'city: ', city
enroll('Sarah','M')
enroll('Bob','F','8')
enroll('Nick','F',city='Sanya')
enroll('Jason','M','8','Shanghai')
####None parameter####
def add_end(L=[]):
L.append('END')
return L
add_end([1,2,3])
add_end(['x','y','z'])
add_end()
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
|
5e68a0b14e5d9f47af2573bd90c6bea797cbb6f9
|
phuwadonop/Python-Lab
|
/hms.py
| 1,077 | 3.78125 | 4 |
print("*** Converting hh.mm.ss to seconds ***")
lst_input = [int(e) for e in input("Enter hh mm ss : ").split()]
hh,mm,ss = lst_input
str_hh = str_mm = str_ss = ''
if hh < 0 or hh != int(hh) : print('hh(%d) is invalid!' %hh)
elif mm < 0 or mm > 59 or mm != int(mm) : print('mm(%d) is invalid!' %mm)
elif ss < 0 or ss > 59 or ss != int(ss) : print('ss(%d) is invalid!' %ss)
else :
int_ans = (hh*3600) + (mm*60) + ss
strIntAns = str(int_ans)
ls = []
numCout = 0
for i in range(len(strIntAns) - 1,-1,-1):
ls.append(strIntAns[i])
numCout += 1
if numCout == 3 and i != 0 :
ls.append(',')
numCout = 0
ls.reverse()
strIntAns = ""
for ele in ls : strIntAns += ele
str_ans = '{}:{}:{} = {} seconds'
if hh < 10 : str_hh = "0" + str(hh)
else : str_hh = str(hh)
if mm < 10 : str_mm = "0" + str(mm)
else : str_mm = str(mm)
if ss < 10 : str_ss = "0" + str(ss)
else : str_ss = str(ss)
print(str_ans.format(str_hh,str_mm,str_ss,strIntAns))
|
9e90d9111ca630267906aa6e7bd40bcb444363f6
|
Zahirgeek/learning_python
|
/Functional_Programming/p1_1.py
| 548 | 3.5 | 4 |
# Decrator
# 任务:
# 对hello函数进行功能扩展,每次执行hello打印当前时间
import time
# 高阶函数,以函数作为参考
def printTime(f):
def wrapper(*args, **kwargs):
print("Time: ", time.ctime())
return f(*args, **kwargs)
return wrapper
@printTime
def hello():
print("Hello World")
hello()
# 上述对函数的装饰使用了系统定义的语法糖
# 下面开始手动执行下装饰器
# 先定义函数
def hello3():
print("手动执行")
hello3()
hello3 = printTime(hello3)
hello3()
|
b9c1c5072033356297a4b92de09ffa47d9d9b7eb
|
Mike543/GB_python_homework_1
|
/Lesson 2/homework2_5.py
| 179 | 3.921875 | 4 |
my_list = [7, 5, 3, 3, 2]
my_list.append(int(input('Введите натуральное целое число: ')))
new_list = sorted(my_list)
new_list.reverse()
print(new_list)
|
66d17aa926e2097acc4ab854cc04c4b62fe8849b
|
gokou00/python_programming_challenges
|
/coderbyte/SymmetricMatrix.py
| 298 | 3.828125 | 4 |
# https://stackoverflow.com/questions/42908334/checking-if-a-matrix-is-symmetric-in-numpy
def SymmetricMatrix(strArr):
test1 = "".join(strArr)
test2 = test1.split("<>")
print(test2)
print(len(test2))
print(SymmetricMatrix(["1","0","1","<>","0","1","0","<>","1","0","1"]))
|
cdfac11934858e101e75e61738612c8bac2f5dc0
|
klee2017/python-practice
|
/0918/lesson/try.py
| 594 | 3.8125 | 4 |
l = list('abcde')
d = dict(name='Lux', champion_type='Magician')
print('program start!')
try:
print('before l[5]')
d['Sona']
l[5]
print('after l[5]')
except IndexError:
print('l[5] exception!')
except KeyError:
print("d['Sona'] exception!")
print('program terminate')
while True:
try :
value = int(input("숫자입력: "))
l[value]
print(l[value])
except IndexError:
print('IndexError!')
except ValueError:
print('ValueError!')
else:
print('good')
finally:
print('finished')
break
|
51dad3bc056febf3e254cd6b3fb831252daa49eb
|
tony520/supervised-BiLSTM-CRF-ore
|
/new_tagging_schema/gen_new_tagging_schema.py
| 3,535 | 3.578125 | 4 |
"""
Functions used to generate the new tagging schema sequence
"""
import pandas as pd
import numpy as np
"""
Convert a list to a string
"""
def list_to_string(in_list):
strg = ''
strg = ' '.join([str(elem) for elem in in_list])
return strg
"""
Compare whether the two sequences are same
"""
def compare_seq(seq_1, seq_2):
if len(seq_1) != len(seq_2):
return False
else:
for i in range(len(seq_1)):
if seq_1[i] != seq_2[i]:
return False
return True
"""
Initiate the tagging sequence with only "O"
"""
def gen_tagging_seq(sent):
init_tags = []
l = len(sent.split(' '))
for i in range(l):
init_tags.append('O')
res = list_to_string(init_tags)
return res
"""
Initiate the dictionary to store each unique sentence
"""
def gen_init_dict(sents):
dic = {}
for sent in sents:
if sent not in dic:
dic[sent] = gen_tagging_seq(sent)
return dic
"""
Generate tuples of (sentence, tag sequence) from datasets
"""
def gen_data_tuples(sents, tags):
ds, dt = [], []
for i in range(len(sents)):
if len(sents[i]) > 0:
ds.append(sents[i])
dt.append(tags[i])
else:
continue
dtuples = [(ds[i].split(), dt[i].split()) for i in range(len(ds))]
return dtuples
"""
Add predicates into the tagging sequence
"""
def upd_tagging_seq(dic, dtuples):
for i in range(len(dtuples)):
sent = list_to_string(dtuples[i][0])
dr = dtuples[i][1]
dt = dic[sent].split(' ')
for j in range(len(dr)):
if dt[j] == 'O' and (dr[j] == 'P-B' or dr[j] == 'P-I'):
dt[j] = dr[j]
dic[sent] = list_to_string(dt)
return dic
"""
Add arguments into the tagging sequence
"""
def upd_tagging_seq_arg(dic, dtuples):
for i in range(len(dtuples)):
sent = list_to_string(dtuples[i][0])
dr = dtuples[i][1]
dt = dic[sent].split(' ')
for j in range(len(dr)):
if dt[j] == 'O' and (dr[j][0] == 'A' and dr[j][-1] == 'B'):
dt[j] = 'A-B'
if dt[j] == 'O' and (dr[j][0] == 'A' and dr[j][-1] == 'I'):
dt[j] = 'A-I'
dic[sent] = list_to_string(dt)
return dic
"""
Make predicates in order P0-B, P1-B, P2-B...
"""
def add_order_to_pred(seq):
arr = seq.split()
ord_pb = 0
ord_pi = 0
for i in range(len(arr)):
if arr[i] == 'P-B':
arr[i] = 'P' + str(ord_pb) + '-B'
ord_pi = ord_pb
ord_pb += 1
elif arr[i] == 'P-I':
arr[i] = 'P' + str(ord_pi) + '-I'
return arr
"""
Make arguments in order A0-B A0-I A1-B A1-I A2-B A2-I...
"""
def add_order_to_args(seq):
arr = seq.split()
ord_pb = 0
ord_pi = 0
for i in range(len(arr)):
if arr[i] == 'A-B':
arr[i] = 'A' + str(ord_pb) + '-B'
ord_pi = ord_pb
ord_pb += 1
elif arr[i] == 'A-I':
arr[i] = 'A' + str(ord_pi) + '-I'
return arr
"""
Generate the new tagging sequence with multiple predicates (relations)
"""
def gen_tagging_res(sents, tags):
dtuples = gen_data_tuples(sents, tags)
dic = gen_init_dict(sents)
dic = upd_tagging_seq(dic, dtuples)
data_s, data_t = [], []
for k in dic:
if len(k) > 0:
data_s.append(k)
data_t.append(dic[k])
data = [(data_s[i].split(), add_order_to_pred(data_t[i])) for i in range(len(data_s))]
return data
|
128f3d28de5374a56a714cf0e06314f27e092b09
|
danny099/holbertonschool-higher_level_programming
|
/0x0F-python-object_relational_mapping/4-cities_by_state.py
| 540 | 3.5 | 4 |
#!/usr/bin/python3
"""cities by state"""
import MySQLdb
from sys import argv
if __name__ == "__main__":
user = argv[1]
passwd = argv[2]
db = argv[3]
conectDB = MySQLdb.connect(
host='localhost', user=user, passwd=passwd, db=db, port=3306)
cur = conectDB.cursor()
cur.execute("""SELECT cities.id, cities.name, states.name FROM cities
JOIN states ON cities.state_id = states.id ORDER BY cities.id""")
states = cur.fetchall()
for i in states:
print(i)
cur.close()
conectDB.close()
|
10725477597a928af475852546bcbadc81aa7dd5
|
Katherinaxxx/leetcode
|
/134. 加油站.py
| 2,129 | 3.515625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/11/18 8:25 PM
@Author : Catherinexxx
@Site : github.com/Katherinaxxx
@File : 134. 加油站.py
@Description: 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gas-station
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# 遍历
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(cost) > sum(gas): return -1
n = len(gas)
for i in range(n):
if gas[i] < cost[i]: continue
cur = 0
flag = True
for j in range(n):
idx = (i + j) % n
cur = cur + gas[idx] - cost[idx]
if cur < 0:
flag = False
break
if flag: return i
return -1
# O(n) O(1) 需满足两个条件:1)总和大于消耗 2)每次剩余大于消耗
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
# total记录可获得的总油量-总油耗, cur记录当前油耗情况, ans记录出发位置
total, cur, ans = 0, 0, 0
for i in range(len(gas)):
total += gas[i] - cost[i]
cur += gas[i] - cost[i]
if cur < 0: # 油不够开到i站
cur = 0 # cur置零,在新位置重新开始计算油耗情况
ans = i + 1 # 将起始位置改成i+1
return ans if total >= 0 else -1 # 如果获得的汽油的量小于总油耗,则无法环
# 行一周返回 -1;反之返回ans
|
1678720786651826233b054af804d5b164d6edf7
|
shreyasabharwal/Data-Structures-and-Algorithms
|
/LinkedList/160.IntersectionOfLinkedLists.py
| 1,947 | 3.75 | 4 |
'''160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.'''
'''
Approach: Maintain two pointers pApA and pBpB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pApA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pBpB reaches the end of a list, redirect it the head of A.
If at any point pApA meets pBpB, then pApA/pBpB is the intersection node.
To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pBpB would reach the end of the merged list first, because pBpB traverses exactly 2 nodes less than pApA does. By redirecting pBpB to head A, and pApA to head B, we now ask pBpB to travel exactly 2 more nodes than pApA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
a = headA
b = headB
while a != b:
if not a:
a = headB
else:
a = a.next
if not b:
b = headA
else:
b = b.next
return a
|
fa17e4dc73eec56c17f1247119c4e114e0fab2d3
|
karthikshivaram24/Text-Summarization-of-Movie-Reviews
|
/code/RottenTomatoesScrapper.py
| 10,446 | 3.65625 | 4 |
"""
This file contains the code to scrape rotten tomatoes for moview reviews as well as the corresponding links of the critic reviews.
It is the starting phase of our text summarization project.
"""
from newspaper import Article
import urllib # For url response
import bs4 # Beautiful Soup for html parsing
import pandas as pd # Pandas for organization of data
import time # To make the crawler sleep to prevent ip ban
import os # To create file and folder structures for our data
import math
import sys
import configparser as cp
import ast
class RTScrapper(object):
def __init__(self,):
"""
This is just the constructor for the RTScrapper object where we set up our user Agent for our headers parameters.
This is done so that if any site prevents a program from automatically accessing it or if it has a robot.txt and you
get an error like an "HTTP 403 Error - Forbidden" this will fix it.
"""
self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
self.base_url = "https://www.rottentomatoes.com"
def mainUrls(self,movie_names,pickleFilename):
"""
This method reads the given file with url's to rotten tomatoes movie reviews and calls the scrapper on each url to collect
the links to all critic reviews as well as scrape the given one sentence summary of the critic review.
Params: MovieNames : Names of movies to scrape reviews for.
pickleFilename : The name of the file to store the dataframe
Returns: Nothing (Saves the pandas dataframe as a .pkl file)
"""
# with open(filename,'r') as fp:
# movie_names = fp.readlines()
No_of_Movies = len(movie_names)
column_names = ["Id","MovieName","ReviewsLink","Total_No_of_Reviews"]
df = pd.DataFrame(index = [x for x in range(No_of_Movies)] ,columns = column_names)
df = df.fillna(0)
for movie_index in range(No_of_Movies):
req = urllib.request.Request(self.base_url+"/m/"+movie_names[movie_index], None, self.headers)
opener = urllib.request.build_opener()
response = opener.open(req)
soup = bs4.BeautifulSoup(response,'lxml')
linkAndReviewNos = soup.find('a',{"class":"view_all_critic_reviews"})
link = linkAndReviewNos['href']
ReviewNos = linkAndReviewNos.text.split()[-1].replace("(","").replace(")","")
df.loc[movie_index] = [movie_index,movie_names[movie_index],link,ReviewNos]
movie2review = dict()
total_reviews = 0
for index, row in df.iterrows():
link,page_nos = row["ReviewsLink"],row["Total_No_of_Reviews"]
movie_name = row["MovieName"]
pages = math.ceil(int(page_nos)/20)
summary = []
reviewLink = []
print("Scrapping "+ movie_name.strip() + ":")
for i in range(1,pages+1,1):
req = urllib.request.Request(self.base_url+link+"?page="+str(i)+"&sort=", None, self.headers)
opener = urllib.request.build_opener()
response = opener.open(req)
soup = bs4.BeautifulSoup(response,'lxml')
cont = soup.find('div',{'class':'content'}).find('div',{'class':'review_table'})
page_no = soup.find('div',{'class':'content'}).find('span',{'class':'pageInfo'}).text
for row in cont.find_all('div',{'class':'row review_table_row'}):
if row != None:
content = row.find('div',{'class':'col-xs-16 review_container'}).find('div',{'class':'review_area'}).find('div',{'class':'review_desc'})
date = row.find('div',{'class':'col-xs-16 review_container'}).find('div',{'class':'review_area'}).find('div',{'class':'review_date subtle small'}).text
year = date.split(",")[-1].strip()
line_summary = content.find('div',{'class':'the_review'}).text
if(content.find('a') != None):
article_link = content.find('a')['href']
# Check date (select if only after 2008) because older links might not exist anymore
if ( int(year)>=2008 and (content.find('a') != None and "[Full review in Spanish]" not in line_summary)):
summary.append(content.find('div',{'class':'the_review'}).text)
reviewLink.append(content.find('a')['href'])
total_reviews+=1
movie2review[movie_name]= {"summary":summary,"reviewLink":reviewLink}
self.writeDftoFile(movie2review=movie2review,filename=pickleFilename)
print("Retrieved " +str(total_reviews) + " reviews for " + str(No_of_Movies)+" Movies" )
def scrapeCriticsReview(self,filename,sleepTime = 5):
"""
This method basically scrapes the critic's review on the critics main page
Params: filename - The file containing a pandas dataframe stored as a pickle object
Returns: Nothing (Saves the summary to a .txt file)
"""
overall_df = pd.read_pickle(filename)
if not os.path.exists("ScrappedData"):
os.makedirs("ScrappedData")
for index, row in overall_df.iterrows():
if index >= 25 and index % 25 == 0:
print("Crawler is sleeping for "+str(sleepTime)+" seconds")
time.sleep(sleepTime)
url = row["ReviewLink"]
if not url.startswith("http"):
url = "http://"+url
try:
print("Scrapping --> " + url)
article = Article(url)
article.download()
article.parse()
summary = article.text
summary = self.cleanContent(reviewStripped=summary)
self.saveReview(id=row["Id"],movieName=row["Movie"],Review=summary)
except Exception as e:
print(str(e))
# if index >= 25 and index % 25 == 0:
# print("Crawler is sleeping for "+str(sleepTime)+" seconds")
# time.sleep(sleepTime)
# url = row["ReviewLink"]
# if not url.startswith("http"):
# url = "http://"+url
# req = urllib.request.Request(url, None, self.headers)
# try:
# print("Scrapping --> " + url)
# opener = urllib.request.build_opener()
# response = opener.open(req)
# soup = bs4.BeautifulSoup(response,'lxml')
#
# # Remove JavaScript and other unwanted Style elements
# for script in soup(["script", "style"]):
# script.extract()
#
# body = soup.body
# para_list =[]
# for para in body.find_all('p'):
# para_list.append(para.text.strip())
# summary = " ".join(para_list)
# summary = self.cleanContent(reviewStripped=summary)
# self.saveReview(id=row["Id"],movieName=row["Movie"],Review=summary)
#
# except Exception as e:
# print(str(e))
def writeDftoFile(self,movie2review,filename):
"""
This method just converts a dictionar to a pandas dataframe and then to a pickle file.
Params: movie2review : The dictionary containing movie to reviews pairs
filename : The name of the file to save as
Returns: Nothing
"""
overall_df = pd.DataFrame()
id_ = 0
for movie in movie2review:
for entry1,entry2 in zip(movie2review[movie]["summary"],movie2review[movie]["reviewLink"]):
overall_df = overall_df.append({"Id":int(id_),"Movie":movie,"ReviewLink":entry2,"Summary":entry1},ignore_index=True)
id_+=1
print("Saving DataFrame to File .........")
overall_df.to_pickle(filename)
def saveReview(self,id,movieName,Review):
"""
This method saves the review string to a .txt file.
Params: id : The id of the review for the movie
movieName : The name of the movie for which we are saving the review
Review : The string containing the review of the movie
Returns: Nothing
"""
if not os.path.exists("ScrappedData"+os.sep+movieName.strip("\n")):
os.makedirs("ScrappedData"+os.sep+movieName.strip("\n"))
with open("ScrappedData"+os.sep+movieName.strip("\n")+os.sep+str(int(id))+"_"+movieName.strip("\n")+".txt",'w') as fp:
fp.write(Review)
print("Written Summary to --> " + "ScrappedData"+os.sep+movieName.strip("\n")+os.sep+str(int(id))+"_"+movieName.strip("\n")+".txt")
fp.close()
def cleanContent(self,reviewStripped):
"""
This method removes \\n,\\t and other space related characters
from the scraped data.
"""
wordList = reviewStripped.split()
return " ".join(wordList)
def readMovies(self):
"""
This reads a .properties file to get the list of movies we need to scrape
reviews for.
Params : None
Returns: movieNames: A list containing names of movies we want to scrape
"""
config = cp.ConfigParser()
config.read("ConfigFile.properties")
movieNames = ast.literal_eval(config.get("MovieNames","moviesName"))
return movieNames
def main(self):
print("\t-------------------------- Starting Rotten Tomatoes Scrapper --------------------------")
movie_names = self.readMovies()
self.mainUrls(movie_names=movie_names,pickleFilename="DFM2R.pkl")
self.scrapeCriticsReview(filename="DFM2R.pkl")
print("\t-------------------------- Finished Scrapping Rotten Tomatoes For Movie Reviews --------------------------")
if __name__=="__main__":
scrapper = RTScrapper()
scrapper.main()
|
9dd3b56eddd4ffdbdfc90a15bc9a805a888dfa18
|
ra1nfoll/summer-practice
|
/1День.А.9.СмвФуты.py
| 405 | 3.734375 | 4 |
import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
a = input('Введіть велbчену в сантиметрах: ')
D = float(a) * 0.39
F = D / 12
print('Дюйми: ' + str(D))
print('Фути' + str(F))
printTimeStamp('\nОсередько Андрій, Ваня Жаботинський\n')
input('\n')
|
3735a95848e04a766ddd3c3925ed346d2052f964
|
TanzinaRahman/PythonCode31
|
/PythonProgram31.py
| 142 | 3.96875 | 4 |
# Series ; 2 + 4 + 6 +.... + n
n = int(input("Enter the last number : "))
sum = 0
for x in range(2, n+1, 2):
sum = sum + x
print(sum)
|
f62960ebf8085f1be6dc4666ff1a04bbf2fd8f51
|
krolik1337/AoC2020
|
/Day8/Day8.py
| 1,398 | 3.515625 | 4 |
#%%
#!=== PART 1 ===!#
input = open("input.txt", "r")
data = []
for line in input:
data += [line.strip().split()]
visited = [False for i in range(len(data))]
accumulator = 0
index = 0
while not visited[index]:
visited[index] = True
if data[index][0] == 'acc':
accumulator += int(data[index][1])
index+=1
elif data[index][0] == 'jmp':
index += int(data[index][1])
elif data[index][0] == 'nop':
index += 1
print(accumulator)
# %%
#!=== PART 2 ===!#
input = open("input.txt", "r")
data = []
for line in input:
data += [line.strip().split()]
visited = [False for i in range(len(data))]
def traverse(accumulator, index, visited, changed):
if index == len(data):
print(accumulator)
raise SystemExit
if visited[index]:
return 0
visited[index] = True
if data[index][0] == 'acc':
return traverse(accumulator + int(data[index][1]), index+1, visited[:], changed)
elif data[index][0] == 'jmp':
if changed or not traverse(accumulator, index+1, visited[:], True):
return traverse(accumulator, index + int(data[index][1]), visited[:], changed)
elif data[index][0] == 'nop':
if changed or not traverse(accumulator, index+ int(data[index][1]), visited[:], True):
return traverse(accumulator, index +1 , visited[:], changed)
traverse(0,0,visited[:], False)
|
4d59ca0a623613edb77665b6b2aa6af0354950fb
|
nicorendon02/primer-semestre
|
/Ejercicios python/ejerciciolista7.py
| 269 | 3.671875 | 4 |
nombres=["juan", "ana", "marcos", "carlos", "luis"]
cantidad=0
x=0
while x<len(nombres):
if len(nombres[x])>=5:
cantidad=cantidad+1
x=x+1
print("Todos los nombres son")
print(nombres)
print("Cantidad de nombres con 5 o mas caracteres")
print(cantidad)
|
02ca5e25e43b65a2bc387d9c4a44b7ff6fce3267
|
RayElg/HackInstead2020
|
/main.py
| 9,078 | 3.640625 | 4 |
#Brython things...
from browser import document
from browser.html import P, STRONG, A
import re
#The dictionaries
averages = {}
facts = {}
#METHODS USED FOR NUMERICAL FUNCTIONS
def parseAvgs(): #Populates averages dictionary from avgs.txt
with open('avgs.txt','r') as f:
for line in f:
lst = line.split()
averages[lst[0]] = float(lst[1]) #First word in line is key, next is value
def parseFacts(): #Populates facts dictionary from facts.txt
global facts
isKey = True
with open('facts.txt','r') as f:
stripped = [line.strip() for line in f.readlines()] #removes newline character
for line in stripped:
if isKey: #For alternating between lines being the key and being the value
key = line
isKey = False
else:
fact = line
isKey = True
facts[key] = fact #First line is key, then the fact string, repeats
def percentComparison(key, value): #Returns a string detailing the percent difference between the average value and inputted value
global averages
avg = averages[key]
percentDiff = (((abs(value - avg))/avg) * 100.0)
if (value > avg):
return ("Your " + re.sub("[\(\[].*?[\)\]]", "", key) + " is " + str((int(percentDiff*100))/(100.0)) + "% greater than the worldwide average, " + str(avg))
elif (avg > value):
return ("Your " + re.sub("[\(\[].*?[\)\]]", "", key) + " is " + str((int(percentDiff*100))/(100.0)) + "% less than the worldwide average, " + str(avg))
else:
return ("Your " + re.sub("[\(\[].*?[\)\]]", "", key) + " is average!")
parseAvgs()
parseFacts()
print(facts)
print(averages)
#dictionaries used for non numerical component
EyeColours = {}
Contient = {}
Sex = {}
NonFacts = {}
#METHODS USED FOR NON NUMERICAL COMPONENT
#method to fill in country facts
def FillCountfacts():
global NonFacts
isKey = True
with open('Continentfacts.txt', 'r') as ReadThis:
Revmoved = [line.strip() for line in ReadThis.readlines()]
for line in Revmoved:
if isKey:
key = line
isKey = False
else:
fact = line
isKey = True
NonFacts[key] = fact
def ReturnFact(UserSelection):
x = NonFacts[UserSelection]
return(x)
#method to read from eyecolours.txt into dictioanry
def FillDictionarys():
with open('Eye colours.txt', 'r') as ReadOnto:
for line in ReadOnto:
component = line.split()
if component[0] == "EYE":
EyeColours[(component[1]).lower()] = str(component[2])
elif component[0] == "CONTINENT":
if component[1] == "South":
Contient[(component[1] +" "+ component[2]).lower()] = str(component[3])
elif component[1] == "North":
Contient[(component[1] +" "+ component[2]).lower()] = str(component[3])
else:
Contient[(component[1]).lower()] = str(component[2])
elif component[0] == "SEX":
Sex[(component[1]).lower()] = str(component[2])
#return the output of the users Eye colour
def ReturnEyeComparison(UserKey):
global EyeColours
return ("You have " + UserKey + " eyes, which is a trait shared by " + EyeColours.get(UserKey) + "%" + " of the population")
def ReturnContComparison(UserKey):
global Contient
return ("You live in " + UserKey + ", " + UserKey + " is also home to " + Contient.get(UserKey ) + "%" + " of the population")
def ReturnSexComparison(UserKey):
global Sex
return ("Your sex is " + UserKey + ", this means you're the same sex as " + Sex.get(UserKey) + "%" + " of the population")
#list all keys within an dictionary
def ListKeysOfDic(Dictionary):
counter = 1
for keys in Dictionary.keys():
print(str(counter)+". " + keys + " ")
counter = counter + 1
#gets the users input
def EyeDescription():
return("(Please select an eye colour from below that best describes you)")
def ContDescription1():
return("What is your continent?")
def ContDescription2():
return("(Please select which continent you currently live on)")
def SexDescription1():
return("What is your sex?")
def SexDescription2():
return("(Please select which sex most accurately describes you)")
FillCountfacts()
FillDictionarys()
#This is for running in commandline. to do so, comment out brython code and uncomment this.
##for key in averages.keys(): #Iterate through keys
## print("What is your " + key)
## print(percentComparison(key,float(input(" ")))) #user input & function call
## print(facts[key]) #Print fact about this stat
keySequence = [
["numerical","salary(CAD)"],
["numerical","height(cm)"],
["numerical","worth(Net,CAD)"],
["NonNumerical","eye colour"],
["NonNumerical","continent"],
["NonNumerical","sex"],
["NonNumerical","FinalScreen"]
]
currentKeyIndex = 0
hasAsked = False
#Brython code
def submitClicked(event): #Handles the submit button being clicked
global currentKeyIndex
global keySequence
global hasAsked
document["errorBox"].clear()
userIn = (document["userTextBox"].value)
if keySequence[currentKeyIndex][0] == "numerical":
try:
document["zone"] <= P(percentComparison(keySequence[currentKeyIndex][1],float(userIn)))
document["zone"] <= P(facts[keySequence[currentKeyIndex][1]])
if ((currentKeyIndex + 1) < len(keySequence)):
currentKeyIndex += 1
document["question"].clear()
document["question"] <= P(STRONG("What is your " + keySequence[currentKeyIndex][1] + "?"))
except ValueError:
document["errorBox"] <= P("Please double check your input")
if keySequence[currentKeyIndex][0] == "NonNumerical":
try:
if keySequence[currentKeyIndex][1] == "eye colour":
if(not (hasAsked)):
document["question"] <= P(EyeDescription())
document["question"] <= P(("1. "+STRONG("Brown"))+(" 2. "+STRONG("Blue"))+(" 3. "+STRONG("Hazel"))+(" 4. "+STRONG("Amber")))
document["question"] <= P(("5. "+STRONG("Green"))+(" 6. "+STRONG("Red/Violet"))+(" 7. "+STRONG("Heterochromia"))+(" 8. "+STRONG("Other")))
hasAsked = True
document["zone"] <= P(ReturnEyeComparison((userIn).lower()))
document["zone"] <= P(ReturnFact((userIn).lower()))
if((currentKeyIndex + 1) < len(keySequence)):
currentKeyIndex += 1
document["question"].clear()
document["question"] <= P(STRONG(ContDescription1()))
document["question"] <= P(ContDescription2())
document["question"] <= P(("1. "+STRONG("Asia"))+(" 2. "+STRONG("Africa"))+(" 3. "+STRONG("Europe")))
document["question"] <= P(("4. "+STRONG("South America"))+(" 5. "+STRONG("North America"))+(" 6. "+STRONG("Oceania")))
if keySequence[currentKeyIndex][1] == "continent":
document["zone"] <= P(ReturnContComparison((userIn).lower()))
document["zone"] <= P(ReturnFact((userIn).lower()))
if((currentKeyIndex + 1) < len(keySequence)):
currentKeyIndex += 1
document["question"].clear()
document["question"] <= P(STRONG(SexDescription1()))
document["question"] <= P(SexDescription2())
document["question"] <= P(("1. "+STRONG("Male"))+(" 2. "+STRONG("Female"))+(" 3. "+STRONG("Intersex")))
if keySequence[currentKeyIndex][1] == "sex":
document["zone"] <= P(ReturnSexComparison((userIn).lower()))
document["zone"] <= P(ReturnFact((userIn).lower()))
if((currentKeyIndex + 1) < len(keySequence)):
currentKeyIndex += 1
document["question"].clear()
document["question"] <= P(STRONG("Thank you!"))
document["submission"].clear()
document["zone"] <= P(STRONG("If any of these figures about wealth or income equality concern you, consider looking at some of these charities..."))
document["zone"] <= P(A(' The UN Development Project ', href='https://www.undp.org'))
document["zone"] <= P(A(' The Borgen Project ', href='https://borgenproject.org/'))
document["zone"] <= P(A(' Oxfam ', href='https://www.oxfam.org'))
except ValueError:
document["zone"] <= P("Please double check your input")
#create the second section of code for elif second for not numerical
#Link our python method to the submit button...
document["submitButton"].bind("click",submitClicked)
|
3ce4363716fd55be3a6ed216cf59dc91750723ac
|
KierstenPage/Intro-to-Programming-and-Problem-Solving
|
/Homework/hw5/kep394_hw5_q1.py
| 387 | 4.1875 | 4 |
inputString = input("Enter an odd length string: ")
midChrPosition = int(((len(inputString)+1)/2)-1)
if (len(inputString) % 2) != 0:
print("Middle character:", inputString[midChrPosition])
print("First half:", inputString[0:midChrPosition])
print("Second half:", inputString[midChrPosition+1:(len(inputString)+1)])
else:
print("The entered string is not of odd length!")
|
fa3a223eb96303b80624bb6269795bbb3a232950
|
lindan4/4441AssistiveDoor
|
/ProjectFiles/guiTester.py
| 666 | 3.71875 | 4 |
from Tkinter import *
def noButton():
print "you chose no"
root.destroy()
def yesButton():
print "you chose yes"
root.destroy()
root=Tk()
root.title("Are you sure?")
root.geometry("450x150+500+400")
unAuthorizedLabel= Label(root,text="This will destroy all your files and you won't be \nrecognized by the system. \nAre you sure?",
font=("arial",12,"bold")).place(x=25,y=25)
yesButton= Button(root, text="Yes", width=25, height=2,
command=yesButton).place(x=2,y=100)
noButton= Button(root, text="No", width=25, height=2,
command=noButton).place(x=263,y=100)
root.mainloop();
|
af028bb4bdbd1323364849196ab4ac072ae56aad
|
quarkgluant/boot-camp-python
|
/day02/ex00/ft_filter.py
| 666 | 4 | 4 |
#!/usr/bin/env python3
# -*-coding:utf-8 -*
def ft_filter(function_to_apply, list_of_inputs):
return [element for element in list_of_inputs if function_to_apply(element)]
if __name__ == '__main__':
my_numbers = [1, 2, 3, 4, 5]
results = list(filter(lambda x: x > 3, my_numbers))
ft_results = list(ft_filter(lambda x: x > 3, my_numbers))
print(results)
print(ft_results)
print(results == ft_results)
my_pets = ['alfred', 'tabitha', 'william', 'arla']
uppered_pets = list(filter(lambda s: len(s) > 5, my_pets))
ft_uppered_pets = list(ft_filter(lambda s: len(s) > 5, my_pets))
print(uppered_pets == ft_uppered_pets)
|
3ce18b8be1db48f89f51a73de5e4b74e246f71ef
|
14Praveen08/Python
|
/vowel_r_consonant.py
| 160 | 4.09375 | 4 |
character = input()
if character == 'a' or character =='e' or character =='i' or character =='o' or character =='u' :
print("Vowel")
else:
print("Consonant")
|
d1ecc7a2595d5f2270c4038edfcf1d9ee85c817a
|
ReneNyffenegger/about-python
|
/functions/return-tuple.py
| 357 | 3.609375 | 4 |
def F():
return 42, 99, -1
x, y, z = F()
print('x={}, y={}, z={}'.format(x, y, z))
#
# x=42, y=99, z=-1
t = F()
print('type(t) = {}'.format(type(t)))
#
# type(t) = <class 'tuple'>
print('t[0]={}, t[1]={}, t[2]={}'.format(t[0], t[1], t[2]))
#
# t[0]=42, t[1]=99, t[2]=-1
# (a, rest) = F() # --> ValueError: too many values to unpack (expected 2)
|
75f7211c3d1de994720033f6b4b54ef1f75ce782
|
TomsenTan/Based-algorithm
|
/bubble_sort.py
| 648 | 3.796875 | 4 |
#-*-coding:utf8-*-
#冒泡排序
#算法要点:
#每次循环将相邻两个数进行比较,可以将最大的数冒泡到最后
#下一次循环就可以在range(len-i-1)即前一次冒泡比较次数基础上减一
#时间:o(n2) 空间:0(n)
#代码实现
import random
def bubble_sort(seq):
n = len(seq)
for i in range(n-1):
print(seq)
for j in range(n-i-1):
if seq[j]>seq[j+1]:
seq[j],seq[j+1] = seq[j+1],seq[j]
print(seq)
#单元测试
def test_bubble_sort():
seq = list(range(10))
random.shuffle(seq)
bubble_sort(seq)
assert seq == sorted(seq)
test_bubble_sort()
|
df249ca6f66f1647952336b627ce49838b774788
|
Macielyoung/LeetCode
|
/168. Excel Sheet Column Title/convertTotitle.py
| 396 | 3.6875 | 4 |
#-*- coding: UTF-8 -*-
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
s = ''
while(n > 0):
r = (n-1) % 26
s += chr(r+65)
n = (n-1) // 26
return s[::-1]
if __name__ == '__main__':
solu = Solution()
n = 52
res = solu.convertToTitle(n)
print(res)
|
eb76b037fd837c3c3f340c6b7042d657d61e14ec
|
JacobHelm36/GITtesting
|
/Journey_Quest.py
| 6,956 | 3.921875 | 4 |
import random
import re
import string
class Dice:
def __init__(self, size, numb):
self.size_of_dice = size
self.number_dice = numb
def roll(self):
results = []
for i in range(self.number_dice):
results.append(random.randint(1, self.size_of_dice))
print(results)
return results
def get_all(self):
results = []
for i in range(self.number_dice):
results.append(random.randint(1, self.size_of_dice))
print(sum(results))
return sum(results)
# magic 8ball
answerNumber = random.randint(1,8)
newnumber = random.randint(1,8)
def getAnswer(any):
if any == 1:
return 'It is certain'
elif any == 2:
return 'It is decidedly so'
elif any == 3:
return 'Yes'
elif any == 4:
return 'Reply hazy try again'
elif any == 5:
return 'Ask again later'
elif any == 6:
return 'Concentrate and ask again'
elif any == 7:
return 'My reply is no'
elif any == 8:
return 'Outlook not so good'
elif any == 9:
return 'Very doubtful'
def rannumber():
secretnumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20')
for guesses in range(1, 7):
print('take a guess: ')
guess = int(input())
if guess > secretnumber:
print('too high')
elif guess < secretnumber:
print('too low')
else:
break
if guess == secretnumber:
print('good job you guessed my number in ' + str(guesses) + ' guesses')
return 'correct guess'
#can you return both guess and secret number?
else:
print('nope the number i have is', str(secretnumber))
return 'lost'
list = ['Rock', 'Paper', 'Scissor']
def ROCKS():
Player_win = 0
Computer_win = 0
while True:
#how to set game to end after two wins?
move = input("choose Rock, Paper, Scissor > ")
computer = list[random.randint(0, 2)]
if move == computer:
print('TIE!!!')
elif Player_win == 1:
print("great work you win")
return 'winner'
break
elif Computer_win == 1:
print("Try again, computer wins")
return 'loser'
break
elif move == 'Rock':
if computer == 'Scissor':
print(f'player wins {move} beats {computer}')
Player_win += 1
else:
print(f'computer wins {computer} beats {move}')
Computer_win += 1
elif move == 'Paper':
if computer == 'Rock':
print(f'player wins {move} beats {computer}')
Player_win += 1
else:
print(f'computer wins {computer} beats {move}')
Computer_win += 1
elif move == 'Scissor':
if computer == 'Paper':
print(f'player wins {move} beats {computer}')
Player_win += 1
else:
print(f'computer wins {computer} beats {move}')
Computer_win += 1
else:
print('thats not a valid move')
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2')
if height <= 2:
raise Exception('Height must be greater than 2')
print(symbol * width)
for i in range(height-2):
print(symbol + (' ' * (width-2)) + symbol)
print(symbol * width)
def work():
command = input("what's your name > ")
print(f"hello traveller, {command}")
journey = ["You have a journey to attend to",
"First go to the (mountains)",
"Then go to the (cave)",
"Then come back (home)",
"Don't be afraid to ask for (help)"]
turn = True
def first_program():
OnlyOneChance = 0
mountaintoken = 0
cave_token = 0
work()
for x in journey:
print(x)
while True:
print('where next?')
command2 = input('> ').lower()
if command2 == 'help':
print("""
First go to the 'mountains'"
"Then go to the 'caves'"
"Then return 'home'""")
elif mountaintoken == 1:
print("you've already been to the mountains go elsewhere")
elif command2 == 'mountains':
mountaintoken = 1
print('you have arrived in the mountains')
print("You must roll some dice to proceed and be higher than the average sum.")
pf = input("How many dice do you want? > ")
dice = Dice(6, int(pf))
yup = True
while yup:
print("'roll' the dice")
command3 = input().lower()
if command3 == 'roll':
DieAverage = int(3 * pf)
PlayersSum = int((dice.get_all()))
if PlayersSum >= DieAverage:
#Find out how to compare "PlayersSum" to "DieAverage"
print('move ahead')
yup = False
elif OnlyOneChance == 0:
#need this to run only once
OnlyOneChance = 1
if PlayersSum < DieAverage:
rannumber()
print('Now roll the dice again')
else:
print("you must not be good with numbers")
else:
print("Don't gamble with dice ever")
elif cave_token == 1:
print("you've already gone to the cave, you can only go once")
elif command2 == 'cave':
cave_token = 1
i = getAnswer(newnumber)
print("Here's a magic 8ball just to see if you should enter the cave")
print(i, " ,doesn't matter, still enter no matter the answer")
print('type play to play Rock, Paper, Scissor and get out of here')
while True:
print("you must win in Rock, Paper, Scissors to move on")
command5 = input('> ')
if ROCKS() == 'winner':
print("well done")
break
elif ROCKS() == 'loser':
print("you are not good at this")
elif command5 == 'play':
ROCKS()
else:
print('play the game peasant')
elif command2 == 'home':
print('Take this box back home with you as a reward')
boxsymbol = input("what symbol would you like it to be lined with? > ")
boxPrint(boxsymbol, 5, 5)
print('you made it home safely, excellent work')
break
else:
print("don't understand")
|
a9cdc7d4e26a4041d4eddb8527c31edea9043121
|
niufenjujuexianhua/Leetcode
|
/[752]Open the Lock.py
| 3,147 | 4.0625 | 4 |
# You have a lock in front of you with 4 circular wheels. Each wheel has 10 slot
# s: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freel
# y 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 i
# t 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" -> "12
# 01" -> "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"], t
# arget = "8888"
# Output: -1
# Explanation:
# We can't reach the target without getting stuck.
#
#
# Example 4:
#
#
# Input: deadends = ["0000"], target = "8888"
# Output: -1
#
#
#
# Constraints:
#
#
# 1 <= deadends.length <= 500
# deadends[i].length == 4
# target.length == 4
# target will not be in the list deadends.
# target and deadends[i] consist of digits only.
#
# Related Topics Breadth-first Search
# 👍 1381 👎 54
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
import collections
deadends, step = set(deadends), 0
dq = collections.deque(['0000'])
while dq:
size = len(dq)
for _ in range(size):
state = dq.popleft()
if state in deadends:
continue
if state == target:
return step
for nst in self.states(state):
if nst not in deadends:
deadends.add(nst)
dq.append(nst)
step += 1
return -1
def states(self, src):
res = []
for i, ch in enumerate(src):
num = int(ch)
res.append(src[:i] + str((num - 1) % 10) + src[i + 1:])
res.append(src[:i] + str((num + 1) % 10) + src[i + 1:])
return res
print(Solution().openLock(deadends = ["0000"], target = "8888"))
# leetcode submit region end(Prohibit modification and deletion)
|
eba3ec7893ff6a08835a536516e44fee662635a6
|
ivan-krukov/kipple
|
/group_known_genes.py
| 593 | 3.609375 | 4 |
#!/usr/bin/env python
"""
Given a list of C elegans genes, count each group
"""
import re
import sys
from operator import itemgetter
from collections import defaultdict, OrderedDict
gene_groups = defaultdict(int)
input_file = sys.argv[1]
name_pattern = re.compile(r"^(?P<class>\w+)\-\d")
for line in open(input_file):
line = line.strip()
match = name_pattern.match(line)
if match:
gene_groups[match.group("class")] += 1
gene_groups = OrderedDict(sorted(gene_groups.iteritems(),key=itemgetter(1),reverse=True))
for key,value in gene_groups.items():
print "{},{}".format(key,value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.