blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
72113ee6b320578df07b107f261a11ca86004f4c | skdonepudi/100DaysOfCode | /Day 80/Capicua.py | 1,019 | 3.78125 | 4 | '''
David has invited his girlfriend Patricia to the cinema to see the latest Ciro Guerra movie, after a long time they have agreed to see the 7 PM movie. When David prepares to pay, he realizes that the serial number on the ticket is a yellow number, so he decides not to use it and finally Patricia must pay for the cinema.
A yellowish number refers to any number that reads the same from left to right.
For this problem it is required to verify if a number is capicúa.
Entry
The first line consists of the number of cases T such that. Later there will be T lines, each with a number N, such that. It is ensured that the numbers do not have leading zeros.
Departure
T lines must be printed, on each line “YES” must be printed if the number is capicúa or “NO” otherwise, all without quotation marks.
SAMPLE INPUT
5
11111
8785878
51875
224614
547745
SAMPLE OUTPUT
YES
YES
NO
NO
YES
'''
for _ in range(int(input())):
s=input()
if s==s[::-1]:
print('YES')
else:
print('NO')
|
88005454f45381b19ba4aea3bca9ce2584162858 | anilkapur58/basics | /1 - Basics/8-forloop.py | 376 | 4.03125 | 4 | for i in range(5):
print('Will print five times ' + str(i))
for i in range(2, 6):
print('Will print six times using start and finish - will include 1st and exclude last ' + str(i))
for i in range(0, 6, 1):
print('Will print two times using number of increments in the last ' + str(i))
list = [2,3,4,5,6,7,8]
for idx, item in enumerate(list):
print(item, idx) |
e6b3b2f9f3e852b9bba7dc35b1e0d6edb4c7610d | dboyd42/python-fundamentals | /starting-out-with-python/c3-descision-structure-boolean-logic/roman-numerals.py | 859 | 4.21875 | 4 | #!/usr/bin/env python3
# Copyright 2019 David Boyd, all rights reserved
# Program: Roman Numerals
# Description: Converts Arabic Numbers to Roman Numberals
# Status: Complete
# Date: 2019/08/13
# Declare variables
print('This program converts a number within the range of 1 through 10 to ' \
'Roman Numberals')
# Get data
userNum = input('Enter an integer: ')
# Determine Roman Numberal
if userNum == '1':
romNum = 'I'
elif userNum == '2':
romNum = 'II'
elif userNum == '3':
romNum = 'III'
elif userNum == '4':
romNum = 'IV'
elif userNum == '5':
romNum = 'V'
elif userNum == '6':
romNum = 'VI'
elif userNum == '7':
romNum = 'VII'
elif userNum == '8':
romNum = 'VIII'
elif userNum == '9':
romNum = 'IX'
elif userNum == '10':
romNum = 'X'
else:
romNum = 'Invalid Entry'
# Display Roman Numeral
print(romNum)
|
b34574f472e34b3314e20d7714e2b6ecdf3a6090 | NickKletnoi/Python | /01_DataStructures/03_Trees/17_Diameter.py | 3,195 | 3.828125 | 4 |
#Copyright (C) 2017 Interview Druid, Parineeth M. R.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from __future__ import print_function
import sys
from PrintTreeHelper import PrintTreeHelper
class TreeNode(object):
def __init__(self, val = 0):
data = val
left = None
right = None
parent = None
@staticmethod
def construct_bst (parent, values, low, high) :
middle = (low + high) // 2
if (low > high):
return None
new_node = TreeNode()
if (not new_node):
return None
#Construct the new node using the middle value
new_node.data = values[middle]
new_node.parent = parent
#Construct the left sub-tree using values[low] to values[middle-1]
new_node.left = TreeNode.construct_bst(new_node, values, low, middle - 1)
#Construct the right sub-tree using values[middle+1] to values[high]
new_node.right = TreeNode.construct_bst(new_node, values, middle + 1, high)
return new_node
#cur_node: current node of the tree
#diameter: diameter of the tree computed till now is passed here
#Return values: height of cur_node and diameter of the tree
@staticmethod
def find_diameter(cur_node, diameter):
if (not cur_node) :
height = 0
return height, diameter
#Find the height of the left sub-tree
left_height, diameter = TreeNode.find_diameter(cur_node.left, diameter)
#Find the height of the right sub-tree
right_height, diameter = TreeNode.find_diameter(cur_node.right, diameter)
#Calculate height of cur_node
height = 1 + max(left_height, right_height)
#Calculate longest path between any two leafs passing through cur_node
longest_path = left_height + right_height + 1
#If the length of longest path through cur_node is greater than
#the current diameter then assign it to the diameter
if (longest_path > diameter):
diameter = longest_path
return height, diameter
MAX_NUM_NODES_IN_TREE = 10
MAX_NODE_VALUE = 10
def handle_error() :
print('Test failed')
sys.exit(1)
def test() :
#number_list contains numbers in ascending order from 0 to MAX_NUM_NODES_IN_TREE
number_list = [i for i in range(MAX_NUM_NODES_IN_TREE)]
#Test for different number of elements in the tree
for num_elems in range(1, MAX_NUM_NODES_IN_TREE + 1) :
#Construct the tree from the list
root = TreeNode.construct_bst(None, number_list, 0, num_elems - 1)
print('Printing tree:')
PrintTreeHelper.print_tree(root, num_elems)
#Find the diameter
diameter = 0
height, diameter = TreeNode.find_diameter(root, diameter)
print('Height = {}, Diameter = {}'.format(height, diameter) )
print('___________________________________________________')
if (__name__ == '__main__'):
test()
print('Test passed')
|
a1c7c2571d4a639ee5b697f38647409d5357a378 | cesaralmeida93/programacao-treino | /URIOnlineJudge/iniciante/1015.py | 807 | 3.828125 | 4 | '''Leia os quatro valores correspondentes aos eixos x e y de dois pontos quaisquer no plano, p1(x1,y1) e p2(x2,y2) e calcule a distância entre eles, mostrando 4 casas decimais após a vírgula, segundo a fórmula:
Distancia =
Entrada
O arquivo de entrada contém duas linhas de dados. A primeira linha contém dois valores de ponto flutuante: x1 y1 e a segunda linha contém dois valores de ponto flutuante x2 y2.
Saída
Calcule e imprima o valor da distância segundo a fórmula fornecida, com 4 casas após o ponto decimal.'''
# -*- coding: utf-8 -*-
from math import sqrt
lista = input().split(' ')
lista2 = input().split(' ')
a = float(lista[0])
b = float(lista[1])
c = float(lista2[0])
d = float(lista2[1])
total = ((a - c) ** 2) + ((b - d) ** 2)
distancia = sqrt(total)
print("%1.4f"%distancia)
|
e9b2e8616d83929f4cd7f88c93319017c2bd4910 | wolfofsiliconvalley/pythonwavass. | /Wave2Lab/lab1of1.py | 163 | 4.03125 | 4 | month = 8
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
# indexing to determine the number of days in month
num_days = days_in_month[-8]
print(num_days)
|
2b3722d893b99899e7b079fa75c987c7b887cb1e | lixianliang21/python-study-100-days | /02.py | 1,090 | 3.96875 | 4 | """
使用input函数输入
使用int()进行类型转换
使用占位符格式话输出的字符串
Version;0.1
Author:Li.xl
"""
a= int(input("a = "))
b= int(input("b = "))
print('%d + %d = %d ' %(a,b,a+b))
print('%d + %d = %d ' % (a,b,a+b))
print('%d - %d = %d ' % (a,b,a-b))
print('%d * %d = %d ' % (a,b,a*b))
print('%d / %d = %d ' % (a,b,a / b))
print('%d // %d = %d ' % (a,b,a / b))
print('%d %% %d = %d ' % (a,b, a % b))
print('%d ** %d = %d ' % (a,b,a ** b))
"""
使用type()检查变量的类型
Version: 0.1
Author: li.xl
Date: 2019-05-01
"""
a = 100
b = 12.345
c = 1 + 5j
d = "hello world"
e = True
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
"""
输入年份,计算是否闰年,是输出True ,否则输出False
Version : 0.1
Author : Li.xl
Date : 2019-05-12
"""
year = int(input("请输入要判定的年份:"))
is_leap = (year % 4 ==0 and year % 100 !=0 or
year % 400 == 0)
if is_leap:
print("%d年份是闰年"%year)
else:
print("%年份不是闰年"%year)
|
5318fb19f85f38a4503070b5f731deaa0603577c | goswami-rahul/ctf | /cscml2020/butterfly/sol.py | 1,719 | 3.875 | 4 | #!/usr/bin/env python
def main():
for char in utf8_iterator():
if len(char) == 1 and len(char.upper()) == 2:
print(char, char.upper())
break
# from https://github.com/Lucas-C/dotfiles_and_notes/blob/master/languages/python/utf8_iterator.py
import itertools
def byte_iterator(start, end):
for i in range(start, end):
yield bytes((i,))
def utf8_bytestring_iterator():
# Doc: https://en.wikipedia.org/wiki/UTF-8#Description & https://fr.wikipedia.org/wiki/UTF-8#Description
yield from byte_iterator(0x00, 0x80) # 2^7 characters
for i, j in itertools.product(byte_iterator(0xc0, 0xe0),
byte_iterator(0x80, 0xc0)): # 2^11 characters
yield b''.join((i, j)) # Some additional restrictions could be applied here (start=0xc2)
for i, j, k in itertools.product(byte_iterator(0xe0, 0xf0),
byte_iterator(0x80, 0xc0),
byte_iterator(0x80, 0xc0)): # 2^16 characters
yield b''.join((i, j, k)) # Some additional restrictions could be applied here
for i, j, k, l in itertools.product(byte_iterator(0xf0, 0xf8),
byte_iterator(0x80, 0xc0),
byte_iterator(0x80, 0xc0),
byte_iterator(0x80, 0xc0)): # 2^21 characters
yield b''.join((i, j, k, l)) # Some additional restrictions could be applied here
def utf8_iterator():
for bytestring in utf8_bytestring_iterator():
try:
yield bytestring.decode('utf8')
except UnicodeError:
pass
if __name__ == '__main__':
main()
|
35828fd305f69e633c559159070d4bf25ba9b637 | baomanedu/Python-Basic-Courses | /课程源码/03-list.py | 906 | 4 | 4 |
##定义
a = []
print(type(a))
numlist = [1,2,3,4,5,6]
strlist = ["a","b","c","d"]
print(numlist,strlist)
##获取list元素
print(numlist[3],strlist[2])
print(numlist[:5])
print(len(numlist))
## 应用
ipAddress = [r"192.158.0.1",r"192.168.0.2"]
print(ipAddress)
## 遍历
for ip in ipAddress:
print(ip)
#内置函数
testHosts = ["aa","bb","cc","dd"]
t1 = ["dd","cc"]
testHosts.append("EE") #末尾追加
print(testHosts.count('bb')) # 计算元素出现的次数
print(testHosts.extend(t1)) # 扩展列表、合并列表
print(testHosts.index("EE")) # 获取列表中元素的索引
testHosts.insert(5,"DD") #列表中插入元素 ,参数: 索引,元素
print(testHosts)
print(testHosts.pop(2)) #根据索引删除元素,并返回被删元素
print(testHosts)
testHosts.remove("EE") ##删除元素
print(testHosts)
testHosts.reverse() #反向列表
print(testHosts)
|
8f5bf1c243e17a1e9d9a7bbf70854c7d935baed3 | diegoshakan/algorithms-python | /Matrizes/matrizes1.py | 1,418 | 4.25 | 4 | '''Crie um programa que solicite ao usuário uma quantidade N de itens de uma lista, onde N
deve ser ímpar e maior que 1. Em seguida, o programa principal deve invocar uma função chamada
carrega_lista, que receba como argumento N; esta função deve retornar uma lista L para o programa
principal. Após receber L, o programa principal deve passá-la como parâmetro para uma função chamada
retorna_elemento_central_lista. Após receber o elemento central da lista, o programa principal deve enviar
esse elemento para outra função chamada calcula_fatorial, a qual devolverá o fatorial de um número
passado como parâmetro. Por fim, o programa principal deve escrever o fatorial do elemento central da
lista.'''
def cria_lista(a):
e = 3
L = []
for i in range(a):
L.append(int(input('Digite um valor: ')))
return L
def centro_lista(a, b):
p = a / 2
num_central = b[int(p)]
return num_central
def faz_fatorial(c):
F = 1
for i in range(1, c + 1):
F = F * i
return F
while True:
print('1. Digite um número ímpar e maior que 1, será quantidade de valores dentro da lista.\nOu 0 Para sair: ')
num = int(input(''))
if num % 2 != 0 and num > 1:
X = cria_lista(num)
Y = centro_lista(num, X)
Z = faz_fatorial(Y)
print()
print(f'O fatorial de {Y} é {Z}')
print()
elif num == 0:
break |
f4c0cc56cf5ab7909be790df32de5d8c22f15709 | zimkjh/algorithm | /competition/2020_kakao/3.py | 1,269 | 3.5 | 4 | def getScore(info):
return int(info.split()[-1])
def solution(info, query):
answer = []
for q in query:
tempAnswer = 0
lang, job, period, soulNscore = q.split(" and ")
soul, score = soulNscore.split()
score = int(score)
for i in info:
if score > getScore(i):
continue
if lang != "-" and lang not in i:
continue
if job != "-" and job not in i:
continue
if period != "-" and period not in i:
continue
if soul != "-" and soul not in i:
continue
tempAnswer += 1
answer.append(tempAnswer)
return answer
info = ["java backend junior pizza 150", "python frontend senior chicken 210", "python frontend senior chicken 150",
"cpp backend senior pizza 260", "java backend junior chicken 80", "python backend senior chicken 50"]
query = ["java and backend and junior and pizza 100", "python and frontend and senior and chicken 200",
"cpp and - and senior and pizza 250", "- and backend and senior and - 150", "- and - and - and chicken 100",
"- and - and - and - 150"]
print(solution(info, query))
# 3시 (효율성 다 시간초과)
|
dceb995d115d10a2981daa5252d5cc7292ccfc94 | devdattakulkarni/log_analysis | /mapper.py | 8,156 | 3.640625 | 4 | # Starting point for this code is the example given here:
# http://h3manth.com/content/word-frequency-mapreduce-python
# (Thanks Hemanth.HM for making it available)
#!/python
#!/usr/bin/python2.6
#
# Copyright [2011] Hemanth.HM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import string
import re
import operator
import sys
import json
__authors__ = "Hemanth HM <hemanth.hm@gmail.com>"
__version__ = "1.0"
class MapReduce:
""" Linear implementation of MapReduce.
MapReduce is a software framework introduced by Google.
"""
def map_it(self,lines):
""" Returns a list of lists of the form [word,1]
for each element in the list that was passed.
"""
return [[word, 1] for word in lines]
def sort_it(self,wlist):
""" Returns a list of list of the form [word,[partialcounts]] """
res = collections.defaultdict(list)
map(lambda w: res[w[0]].append(w[1]), wlist)
return res.items()
def map_reduce(self,wlist):
""" Returns a dict with word : count mapping """
results = {}
for res in self.sort_it(self.map_it(wlist)) :
results[res[0]] = sum(res[1])
return results
class SlurpFile:
""" Simple class to get the file contents, after filtering punctuations
Attributes:
fpath: Path to the file name.
"""
stoplist = (['for','to','the','a','that','do','on','be',
'is','in','of','as','can','are','this','from',
'thats','they','if','see','some','but','not','yes',
'we','We','when','then','which','though','take',
'an','It','Is','them','and','it','will','have','you',
'there','about','you','or','was','has','had',
'more','so','at','would','should','could','The',
'how','their','here','out','with','ok','one','want',
'what','also','right','into','your','us','no','its',
'week','dont','I','my','i','me','am','too','did','just',
'any','good','like','get'
])
def __init__(self,path):
""" Inits the SlurpFile class with path to the file
Args:
path: path to the file that needs to be read.
"""
self.fpath = path
def get_contents(self):
""" Read the files and cleans it by removing the punctuations
and returns a list of words.
"""
#with open(self.fpath) as wfile:
with open('/dev/input', 'r') as wfile:
all_words = ''.join(ch for ch in wfile.read() if ch not in set(string.punctuation)).split()
filtered_words = []
for word in all_words:
if word not in self.stoplist and not word.isdigit() and not word.startswith('http'):
filtered_words.append(word)
return filtered_words
mr = MapReduce()
slurp = SlurpFile('/dev/input')
result = mr.map_reduce(slurp.get_contents())
sorted_result = sorted(result.iteritems(), key=operator.itemgetter(1), reverse=True)
with open('/dev/out/reducer', 'a') as f:
f.write(json.dumps(sorted_result))
|
e3669085353c62279a2dc24ac6e82dba3424c278 | rien333/Tinder-Identities | /uglyparse.py | 1,053 | 3.546875 | 4 | import sys
from pynput import keyboard
from pynput.keyboard import Key, Controller
from time import sleep
keyboard=Controller()
# Change this for the computer's preference
# Swipe right when one of these preferences is met
preferences = ["sunflowers", "roses", "daisy"]
out_f = sys.argv[1]
# keys: class names values: scores
scores = {}
with open(out_f, "r") as f:
for l in f:
if "score" in l:
s = float(l.split("=")[1][:-2])
c = l.split(" (")[0]
scores[c] = s
pref_scores = [scores[pref] for pref in preferences]
for c, s in scores.items():
if c in preferences:
continue # skip
# check wether a non prefered class scores higher than any of the prefered classes
if all(s > s1 for s1 in pref_scores):
print("Swipe left!")
keyboard.press(Key.left)
keyboard.release(Key.left)
exit(0)
print("Swipe right!")
keyboard.press(Key.right)
keyboard.release(Key.right)
sleep(0.8)
# press esc to get out of menu
keyboard.press(Key.esc)
keyboard.release(Key.esc)
|
6718f42fc09820f4e8dcc9f9f8ed39e801194e21 | jhug3/techdegree-project-02 | /keywords.py | 11,284 | 3.875 | 4 | # Keywords.py file by John Hughes 3/9/18
from ciphers import Cipher
from collections import OrderedDict
import logging
#logging.basicConfig(filename='keyword.log', level = logging.DEBUG)
class Keyword(Cipher):
''' Class: Keyword: Child of Cipher
Uses the Keyword cipher to encrypt or decrypt a message.
Will ask user for a message and a keyword.
If a keyword is not given a default one will be used.
Note: spaces are allowed and will be replaced with #.
'''
def __init__(self):
self.ALPHABET = OrderedDict()
self.encrypted_alphabet = OrderedDict()
self.keyword_list = []
# Create the ALPHABET OrderedDict:
self.ALPHABET[0] = 'A'
self.ALPHABET[1] = 'B'
self.ALPHABET[2] = 'C'
self.ALPHABET[3] = 'D'
self.ALPHABET[4] = 'E'
self.ALPHABET[5] = 'F'
self.ALPHABET[6] = 'G'
self.ALPHABET[7] = 'H'
self.ALPHABET[8] = 'I'
self.ALPHABET[9] = 'J'
self.ALPHABET[10] = 'K'
self.ALPHABET[11] = 'L'
self.ALPHABET[12] = 'M'
self.ALPHABET[13] = 'N'
self.ALPHABET[14] = 'O'
self.ALPHABET[15] = 'P'
self.ALPHABET[16] = 'Q'
self.ALPHABET[17] = 'R'
self.ALPHABET[18] = 'S'
self.ALPHABET[19] = 'T'
self.ALPHABET[20] = 'U'
self.ALPHABET[21] = 'V'
self.ALPHABET[22] = 'W'
self.ALPHABET[23] = 'X'
self.ALPHABET[24] = 'Y'
self.ALPHABET[25] = 'Z'
self.ALPHABET[26] = ' '
def get_keyword(self):
# Get the keyword from the user, if empty will use default.
self.keyword = self.get_user_input("Please enter a keyword, hit enter to use the default keyword.\n>>")
if self.keyword == '':
self.keyword = 'KRYPTOFISH'
# Removes any duplicate letters from the entered keyword
for letter in self.keyword:
if letter not in self.keyword_list:
self.keyword_list.append(letter)
self.keyword = ''.join(self.keyword_list)
# Removes any spaces
self.keyword = ''.join(self.keyword.split(' '))
self.keyword = self.keyword.upper()
logging.debug("The return of get_keyword is: {}.".format(self.keyword))
return self.keyword
def get_message(self):
# Get the message to encrypt from the user and put it into self.message_list
self.message = self.get_user_input("Please enter a message to encrypt.\n>>", True)
self.message = self.message.upper()
logging.debug("The return of get_message is: {}.".format(self.message))
return self.message
def get_pad(self, message):
# Gets the PAD from the user.
while True:
pad = self.get_user_input("Please enter a PAD to secure your message.\n"
"Note the PAD must be at least as long as your message.\n"
"If this is to decypt a message please enter that PAD:\n>>", True)
if len(pad) >= len(message):
print("That is a secure PAD!")
break
else:
nothing = input("Please enter a PAD at least as long as the message you are encrypting.\n"
"Hit ENTER to continue.")
pad = pad.upper()
logging.debug("The return of get_pad is: {}.".format(pad))
return pad
def get_encrypted_message(self):
# Get the encrypted message to encrypt, must have already encrypted a message.
self.encrypted_message = self.get_user_input("Please enter an already encrypted message for decryption.\n>>", True)
self.encrypted_message = self.encrypted_message.upper()
logging.debug("The return of get_encrypted_message is: {}.".format(self.get_encrypted_message))
return self.encrypted_message
def encrypt_message(self, message, keyword):
# Encrypts the message using the inputed message and keyword.
encrypted_message = []
# Create the encrypted alphabet from the keyword:
index = 0
for letter in keyword:
if letter not in self.encrypted_alphabet:
self.encrypted_alphabet[index] = letter
index += 1
for alpha_letter in self.ALPHABET.values():
if alpha_letter not in self.keyword:
self.encrypted_alphabet[index] = alpha_letter
index += 1
# Print out encrypted alphabet to the debug log:
logging.debug("The encrypted alphabet is:\n")
for key, value in self.encrypted_alphabet.items():
logging.debug("{} : {}".format(key, value))
# Create the encrypted message:
for message_letter in message:
for alpha_key, alpha_letter in self.ALPHABET.items():
if message_letter == alpha_letter:
encrypted_message.append(self.encrypted_alphabet[alpha_key])
logging.debug("Encrypted message befor subbing spaces: {}.".format(encrypted_message))
# Subbing # for spaces.
space_index = 0
for space_letter in encrypted_message:
if space_letter == ' ':
encrypted_message[space_index] = '#'
space_index += 1
logging.debug("The return of encrypt_message (after subbing spaces) is: {}.".format(encrypted_message))
return ''.join(encrypted_message)
def decrypt_message(self, encrypted_message, keyword):
# Decrypts the message using the inputed encrypted message and keyword.
logging.debug("In start of decrypt_message:\nEncrypted_message is:{}\nKeyword is:{}.".format(encrypted_message, keyword))
decrypted_message = []
# subs any # back to spaces.
space_index = 0
space_message = [letter for letter in encrypted_message]
for space_letter in space_message:
if space_letter == '#':
space_message[space_index] = ' '
space_index += 1
encrypted_message = ''.join(space_message)
logging.debug("Encrypted_message after subbing # back to space is: {}.".format(encrypted_message))
index = 0
# Create the encrypted alphabet from the keyword:
for letter in keyword:
if letter not in self.encrypted_alphabet:
self.encrypted_alphabet[index] = letter
index += 1
for alpha_letter in self.ALPHABET.values():
if alpha_letter not in keyword:
self.encrypted_alphabet[index] = alpha_letter
index += 1
# Printing the encrypted alphabet for the debugger:
logging.debug("The encrypted alphabet in decrypt_message is:\n")
for key, value in self.encrypted_alphabet.items():
logging.debug("{} : {}".format(key, value))
# Decrypt the message
for letter in encrypted_message:
for alpha_key, alpha_letter in self.encrypted_alphabet.items():
if letter == alpha_letter:
decrypted_message.append(self.ALPHABET[alpha_key])
logging.debug("The return of decrypt_message is: {}.".format(decrypted_message))
return ''.join(decrypted_message)
def encrypt_pad(self, message, pad):
logging.debug("In incrypt_pad:\nMessage is: {}\nPad is: {}".format(message, pad))
message_keys = []
pad_keys = []
pad_encrypt_keys = []
pad_encrypted_message = []
# Gets the number value of the letters in the message.
# Accounts for any # substituted for spaces.
for letter in message:
if letter == '#':
letter = ' '
for key, alpha in self.ALPHABET.items():
if letter == alpha:
message_keys.append(key)
break
logging.debug("The number value of the letters in message is: {}.".format(message_keys))
# Gets the number value of the letters in the PAD.
for letter in pad:
for key, alpha in self.ALPHABET.items():
if letter == alpha:
pad_keys.append(key)
logging.debug("The number value of the letters in the PAD is: {}.".format(pad_keys))
message_index = 0
# Applies the PAD to the message.
for message_key in message_keys:
pad_key = pad_keys[message_index]
pad_encrypt_keys.append((message_key + pad_key) % len(self.ALPHABET))
message_index += 1
for pad_encrypt_key in pad_encrypt_keys:
for key, alpha in self.ALPHABET.items():
if pad_encrypt_key == key:
pad_encrypted_message.append(self.ALPHABET[key])
break
logging.debug("Message with PAD applied before spaces are subbed is: {}.".format(pad_encrypted_message))
# Subbing # for spaces.
space_index = 0
for space_letter in pad_encrypted_message:
if space_letter == ' ':
pad_encrypted_message[space_index] = '#'
space_index += 1
logging.debug("Message at end of encrypt_pad (after spaces are subbed) is: {}\n".format(pad_encrypted_message))
return ''.join(pad_encrypted_message)
def decrypt_pad(self, message, pad):
logging.debug("In decrypt_pad:\nMessage is:{}\nPad is:{}".format(message, pad))
message_keys = []
pad_keys = []
pad_encrypt_keys = []
pad_encrypted_message = []
# subs any # back to spaces.
space_index = 0
space_message = [letter for letter in message]
for space_letter in space_message:
if space_letter == '#':
space_message[space_index] = ' '
space_index += 1
message = ''.join(space_message)
logging.debug("Message after subbing # back to spaces is: {}.".format(message))
# Gets the number value of the letters in the message.
for letter in message:
for key, alpha in self.ALPHABET.items():
if letter == alpha:
message_keys.append(key)
logging.debug("The number value of the letters in message is: {}".format(message_keys))
# Gets the number value of the letters in the PAD.
for letter in pad:
for key, alpha in self.ALPHABET.items():
if letter == alpha:
pad_keys.append(key)
logging.debug("The number values of the letters in PAD is: {}".format(pad_keys))
message_index = 0
# Applies the PAD to the message.
for key in message_keys:
pad_key = pad_keys[message_index]
pad_encrypt_keys.append((key - pad_key) % len(self.ALPHABET))
if pad_encrypt_keys[-1] < 0:
pad_encrypt_keys += len(self.ALPHABET)
message_index += 1
for pad_key in pad_encrypt_keys:
for key, alpha in self.ALPHABET.items():
if pad_key == key:
pad_encrypted_message.append(self.ALPHABET[key])
logging.debug("The return of decrypt_pad is: {}.".format(pad_encrypted_message))
return ''.join(pad_encrypted_message)
|
26b903026cecf1db05ffcd8263be159dc435735b | vaibhavranjith/Heraizen_Training | /Assignment1/Q40.py | 107 | 3.65625 | 4 | c=1
for i in range(1,5):
for j in range(5,i,-1):
print(c,end=" ")
c+=1
print() |
e4c66763d18db9e84d7fb1111595c0d253a7e281 | AmanGamer/exercise | /exercise3.py | 653 | 4.03125 | 4 | n = 18
number_of_guesses=1
print("You will get only 8 chance to wirite naswer:")
while(number_of_guesses<=8):
guess_number = int(input("\nGuess the number"))
if guess_number<18:
print("you chosse small number take big number:")
elif guess_number>18:
print("you choose big number take small number:")
else:
print("\nyou won")
print("you are the winner , you win in ", number_of_guesses, "chances.")
break
print(8-number_of_guesses, "number of guesses left")
number_of_guesses = number_of_guesses+1
if (number_of_guesses>8):
print("game over") |
8eb1f0eacf2d84022e8be557c6b6db55ec4b0a04 | lancelafontaine/coding-challenges | /daily-programmer/daily-programmer-easy-016/python3/daily-programmer-easy-16.py | 156 | 3.8125 | 4 | def removeChars(origStr, charsToRemove):
return ''.join([c for c in origStr if c not in set(list(charsToRemove))])
print(removeChars('abc', 'c')) # ab
|
7b3fc865cb0bee35f99249455eedd191b5939566 | yuzhou346694246/compilerimplement | /node/lex.py | 1,724 | 3.5625 | 4 | from enum import Enum
class Token:
def __init__(self, kind, pos, text, val=None, lineno=0):
self.kind = kind
self.pos = pos
self.text = text
self.val = val
self.lineno = lineno
def __str__(self):
return 'tokenKind:{},pos:{},text:{},val:{}, lineno:{}'.format(self.kind, self.pos, self.text, self.val, self.lineno)
# class TokenType(Enum):
class Lexer:
def __init__(self, content):
self.content = content
def lex(self):
pos = 0
line = self.content
length = len(line)
while pos < length:
if line[pos].isdigit():
begin = pos
while True:
pos += 1
if pos >= length:
text = line[begin:pos]
val = int(text)
yield Token('num',begin,text,val)
yield Token('$',-1,'')
return
if not line[pos].isdigit():
text = line[begin:pos]
val = int(text)
yield Token('num',begin,text,val)
break
if line[pos] == '+':
yield Token('+',pos,'+')
pos=pos+1
if line[pos] == '-':
yield Token('-',pos,'-')
pos=pos+1
if line[pos] == '*':
yield Token('*',pos,'*')
pos=pos+1
if line[pos] == '/':
# yield '/'
yield Token('/',pos,'/')
pos=pos+1
if pos >= length:
yield Token('$',-1,'')
return
|
4eebe5c5b9814df9cfdba9c4726f923724f90c8d | DenilsonSilvaCode/Python3-CursoemVideo | /PythonExercicios/ex011.py | 481 | 3.984375 | 4 | #faça um programa que leia a altura e largura de uma parede em metros, calcule a sua area, e a quantidade de tinta necessária para pinta-la.
#sabendo que cada litro de tinta pinta uma area de 2m²
larg = float(input('Largura da parede em metros: '))
alt = float(input('Altura da parede em metros: '))
area = larg * alt
print('Sua parede tem {}m²'.format(area))
tinta = area / 2
print('Para pintar essa parede, você precisará de {} Litros de tinta.'.format(tinta))
|
cd563ffff47ef74f69f5880f6e785111b6167850 | zstall/Django-Python-Full-Stack-Web-Devloper-master | /Python_Level_One_Notes/tuples_sets_booleans.py | 483 | 3.640625 | 4 | # Booleans
True
False
# Tuples - immutable sequences
t = (1,2,3)
print(t[0])
t = ('a', True, 123)
# t[0]="new" - This will throw an error because tuples are immutable
print(t)
# sets - unordered set, looks like a dictionary, but no key value pairs
# only takes unique elements
x = set()
x.add(1)
x.add(2)
x.add(3)
x.add(4)
x.add(4)
x.add(4)
print(x) # will only have one four
l = [1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,6,6,6,6,6,6]
converted = set(l)
print(converted)
|
7d791001b5786ba47351cf5d204427edcac45f10 | karimeSalomon/API_Testing_Diplomado | /EduardoRocha/extractUrl.py | 149 | 3.5 | 4 | import re
myString = "This is my tweet check it out http://example.com/blah vc"
print(re.search("(?P<url>https?://[^\s]+)", myString).group("url")) |
05d492888f3a77d5db9c98ae2ebd5bcc5890cc33 | manan-malhotra/InfyTQ-Practice | /2. Stacks/3 Implement Queue.py | 578 | 4.09375 | 4 | class queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, *args):
for i in args:
self.items.append(i)
def dequeue(self):
return self.items.pop(0)
def peek(self, el=0):
return self.items[el]
a = queue()
print(a.isEmpty())
a.enqueue(4, 8, 3)
a.enqueue(5, 3)
a.enqueue(6, 7, 8)
a.enqueue(7)
# print(a.peek())
print(a.dequeue())
print(a.dequeue())
print(a.dequeue())
print(a.dequeue())
print(a.dequeue())
print(a.dequeue())
print(a.dequeue())
|
2846ad8b8af77b6799abf25c642cd89e443a7fc2 | Jiaguli/Python200803 | /Day 1-6(獎品).py | 208 | 3.765625 | 4 | math=input('請輸入你的數學成績')
english=input('請輸入你的英文成績')
if int(math)>=60 and int(english)>=60:
print('恭喜!獲得獎品!')
else:
print('準備接受懲罰吧!')
|
0c282640a0d9b4168d30c8254253ecade13ce868 | mervenurtopak/basic-data-structures-and-objects | /Temel Veri Yapıları ve Objeler/ödevler/oyuncu kaydetme.py | 365 | 3.875 | 4 | print("Oyuncu Kaydetme Programı")
ad= input("Oyuncunun Adı:")
soyad= input ("Oyuncunun Soyadı:")
takım= input ("Oyuncunun Takımı:")
bilgiler= [ad,soyad,takım]
print("Bilgiler kaydediliyor...")
print("Oyuncu Adı: {}\n Oyuncunun Soyadı: {}\n Oyuncunun Takımı:{}\n".format(bilgiler[0],bilgiler[1],bilgiler[2]) )
print("Bilgiler Kaydedildi....") |
28ea67761b4746fcac300ef045d44849ff5e629f | yueyue21/University-of-Alberta | /INTRO TO FNDTNS OF CMPUT 1/square.py | 254 | 3.6875 | 4 | #a = 2
import math
def num(x):
a = 2
#global a
for i in range(x-1):
a = 2 * a
return a
#print(num(5))
print(num(18)+num(22)+num(24)+num(25)+num(28)+num(29)+num(2)+num(3)+num(4)+num(5))
#print(num(64))
#print(2^5)
#num(3) |
d4e2306e4dca7cd8d858a3c995438e4ce2a5287f | JoelSVM/HiperCalculadora | /Binario a Hexadecimal .py | 704 | 3.6875 | 4 | # -*- coding: cp1252 -*-
numero = raw_input("Ingrese un nmero binario: ")
binadicth = {"0000" : "0","0001" : "1","0010" : "2","0011" : "3","0100" : "4","0101" : "5","0110" : "6","0111" : "7", "1000" : "8","1001" : "9","1010" : "a","1011" : "b","1100" : "c","1101" : "d","1110" : "e","1111" : "f"}
bin1 = ""
cont=len(numero)
B = len(numero)
Z = len(numero)
j=[1,2,3]
while cont!=0 and cont!=-1 and cont!=-2 and cont!=-3:
B = B-4
if B==-1 or B==-2 or B==-3:
B=0
bin1 = numero [B:Z]
while len(bin1)<=len(j):
bin1="0"+bin1
print"R",binadicth.get(bin1)
else:
bin1 = numero [B:Z]
print"R ",binadicth.get(bin1)
Z-=4
cont-=4
|
61d9c077f4c8f88b5202b131452e5f5c14c8ce00 | arislam0/Python | /Anusur Islam Py file/p49.py | 132 | 3.921875 | 4 | a = 20
b = 10
a,b=b,a
print(a)
print(b)
"""
temp = a #temp = 20
a = b # a=10
b = temp # b=20
print(a)
print(b)
"""
|
5adf21cea6745bcfd34c1153976895b014bad68f | dylantaylor548/kmer-project | /utils/abundancy_determination/abundancy simlution.py | 2,781 | 3.546875 | 4 | from math import floor
import random
import copy
# Generates a chip when given a dictionary containing sequence matches for each oligo, as well as a max size (# of oligos) for the output chip
def make_chip(chip_dict,chip_size,setup='proportional'):
chip = []
if setup == 'proportional':
chip_intermediate = []
for oligo in chip_dict:
for i in range(0,len(chip_dict[oligo])):
chip_intermediate.append(oligo)
chip_mult = floor(chip_size/len(chip_intermediate))
chip = chip_intermediate * chip_mult
print("Using " + str(len(chip)) + " spots on the chip")
elif setup == 'even':
possible_seqs = set()
for oligo in chip_dict:
for seq in chip_dict[oligo]:
possible_seqs.add(seq)
possible_seqs = list(possible_seqs)
chip_mult = floor(chip_size/len(possible_seqs))
chip = possible_seqs * chip_mult
print("Using " + str(len(chip)) + " spots on the chip")
else:
print("'" + str(setup) + "' is not a valid input parameter for 'setup'")
return
return chip
# Simulates washing an input sample (in the form of a list containing all the sequences in the sample) over an input chip
def simulate_chip_washing(chip_dict,chip,input_seqs):
seq_abundances = {}
for oligo in chip_dict:
for seq in chip_dict[oligo]:
seq_abundances[seq] = 0
while chip != []:
pick_oligo = random.choice(chip)
pick_seq = random.choice(input_seqs)
if pick_seq in chip_dict[pick_oligo]:
seq_abundances[pick_seq] += 1
chip.remove(pick_oligo)
input_seqs.remove(pick_seq)
else:
continue
return seq_abundances
############################################################################################################
chip_dict = {
'kmer1' : ['seq1','seq3','seq9'],
'kmer2' : ['seq2','seq3','seq4','seq9'],
'kmer3' : ['seq4','seq5','seq6','seq7','seq9'],
'kmer4' : ['seq2','seq7','seq8','seq9']
}
seq_sample = (['seq1'] * 100000) + (['seq2'] * 100000) + (['seq3'] * 200000) + (['seq4'] * 1000000) + (['seq5'] * 100000) + (['seq6'] * 400000) + (['seq7'] * 800000) + (['seq8'] * 300000) + (['seq9'] * 100000)
chip_size = 2000
trials = 10
############################################################################################################
f = open('C:/Users/Dylan/Desktop/abundance_test.csv','w')
possible_seqs = list(set(seq_sample))
firstline = ','+ ','.join(possible_seqs) + '\n'
f.write(firstline)
for i in range(1,trials+1):
print("Doing Trial " + str(i))
seq_sample_copy = copy.deepcopy(seq_sample)
chip = make_chip(chip_dict,chip_size)
abundances = simulate_chip_washing(chip_dict,chip,seq_sample_copy)
line = 'Trial ' + str(i)
for seq in possible_seqs:
line += ',' + str(abundances[seq])
f.write(line + '\n')
f.close()
|
3eb05ff4a9679bbb6f684fcf45b8e83c46e21fa0 | LouiseCerqueira/python3-exercicios-cursoemvideo | /python3_exercicios_feitos/Desafio010.py | 244 | 3.921875 | 4 | #Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar.
#Considere USS 1,00= R$ 3,27
din = float(input('Digite o valor: '))
print(f'{din:.2f} reais equivalem a {din/3.85:.2f} dólares') |
c6e0bd56c86454ad65a180ca2ab32f554949065d | cumminlj/python-chat | /Message.py | 1,778 | 3.703125 | 4 | import datetime
class Message:
"""
A single message object stored on the chat server.
"""
htmlFormatString="<div id='{4}' class='message {2}'><div class='messageBody'>{3}</div><div class=time>{1}</div><div class=name>{0}</div></div>"
htmlError = "<span class='error'>Message hidden due to HTML content</span>"
lengthError = "<span class='error'>Message hidden due to being above 250 char limit</span>"
def __init__(self, username, body, cssClass, Id):
body = self._sanitize(body)
self.username = username
self.body = str(body)
self.time = datetime.datetime.now()
self.cssClass = cssClass
self.Id = Id #uniquely identifies the message for use on the client. used to set the divId to 'msgX' where X is the numeric Id
def _sanitize(self, message):
if not message : return ''
if message.find('<') != -1 or message.find('>') != -1 : return self.htmlError
if len(message) > 250: return self.lengthError
return message
def getHTML(self, username='', idPrefix='msg'):
aditionalCssClass = self.cssClass + ' ' + ((self.username==username) and 'mine' or ' ') #add class 'messagemine' if its my message
divId = idPrefix + str(self.Id)
html = self.htmlFormatString.format(self.username, self.time.time().__str__()[:8], aditionalCssClass, self.body, divId)
return htmlWrapper(html, divId)
class htmlWrapper:
"""
A html object to be displayed by the client
html is a string that should be div tags with html inside. The divId must be both specified in the HTML and passed in to the contructor.
a ServerResponse retains a list of these objects to be returned to the client
"""
def __init__(self, html, divId):
self.html = html
self.divId = divId
def serialize(self):
return {'divId' : self.divId, 'html' : self.html}
|
e6a9b7a410a3be8065d138c5fb433da889497944 | ChrisLiu95/Leetcode | /easy/Reverse_Bits.py | 546 | 4.03125 | 4 | """
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
return 964176192 (represented in binary as 00111001011110000010100101000000).
"""
class Solution(object):
# @param n, an integer
# @return an integer
def reverseBits(self, n):
#given 32 bits unsigned integer
oribin = '{0:032b}'.format(n)
print(oribin)
temp = oribin[::-1]
return int(temp, 2)
test = Solution()
print(test.reverseBits(1))
|
fc96d94d81080090d204a3c9e864861ddce31bc4 | VictorTherache/P4_chess_tournament | /Chess_tournament/Controllers/MatchController.py | 2,787 | 3.53125 | 4 | from Views import MatchView
import sys
from sys import platform
import os
sys.path.append("..")
class MatchController(object):
"""
Match's controller : Gets the data from the model and shows
the views
"""
def __init__(self):
"""
Constructor of the class
"""
self.match_views = MatchView.MatchView()
def update_score(self, match, i):
"""
Take the results of the match the user entered
"""
self.match_views.update_score(match)
score_p1 = input(f"Veuillez rentrer le score de "
f"{match[0][0]['first_name']} "
f"{match[0][0]['last_name']} (1/0.5/0) ")
score_p2 = input(f"Veuillez rentrer le score de "
f"{match[1][0]['first_name']} "
f"{match[1][0]['last_name']} (1/0.5/0) ")
self.validate_score(score_p1, score_p2, match, i)
new_score = float(score_p1)
new_score2 = float(score_p2)
return new_score, new_score2
def update_score_other_rounds(self, match):
"""
Display the message to ask the user for matches result
"""
self.match_views.update_score(match)
def validate_score(self, score1, score2, match, i):
if (float(score1) != 1.0 and
float(score1) != 0.0 and
float(score1) != 0.5):
self.clean_console()
self.match_views.invalide_score()
input("Appuyer sur entrée pour continuer")
self.update_score(match, i)
if (float(score2) != 1.0 and
float(score2) != 0.0 and
float(score2) != 0.5):
self.clean_console()
self.match_views.invalide_score()
input("Appuyer sur entrée pour continuer")
self.update_score(match, i)
if (float(score1) == 1.0 and float(score2) != 0):
self.clean_console()
self.match_views.error_two_winners()
input("Appuyer sur entrée pour continuer")
self.update_score(match, i)
if (float(score1) == 0.0 and float(score2) != 1.0):
self.clean_console()
self.match_views.error_two_loosers()
input("Appuyer sur entrée pour continuer")
self.update_score(match, i)
if (float(score1) == 0.5 and float(score2) != 0.5):
self.clean_console()
self.match_views.error_two_draw()
input("Appuyer sur entrée pour continuer")
self.update_score(match, i)
def clean_console(self):
if(platform == 'linux'
or platform == 'linux2'
or platform == 'darwin'):
os.system('clear')
else:
os.system('cls')
|
d5d74ddbdbf0b855a414f336a0e013fef3b9cf9f | BartekDzwonek/PracaDomowa1 | /Homework3.py | 396 | 3.734375 | 4 | #!/usr/bin/env python3
class Kwiatek:
def __init__(self, kolor, nazwa):
self.kolor = kolor
self.nazwa = nazwa
def wyswietl(self):
print("Kolor kwiatka to {} a jego nazwa to {}".format(self.kolor, self.nazwa))
kolor = input("Podaj kolor kwiatka: ")
nazwa = input("Jak nazywa sie kwiatek: ")
kwiatek = Kwiatek(kolor, nazwa)
kwiatek.wyswietl()
|
41dcb9818b1b2eb9d1622f80d3dbfb987f48feac | C-My-Code/ParcelManager | /Graph.py | 1,989 | 3.609375 | 4 |
class Graph(object):
def __init__(self):
self.adjacency_list = {}
self.edge_weights = {}
#This add a vertex to the adjacency list and gives the vertex its own list of adjacent vertexs initalized to empty.
def add_vertex(self, new_vertex):
self.adjacency_list[new_vertex] = []
#This adds a directed edge to the graph along with a wight, or in this case, a distance. Time complexity O(1)
def add_directed_edge(self,vertex_from, vertex_to, weight):
self.edge_weights[(vertex_from, vertex_to)] = weight
self.adjacency_list[vertex_from].append(vertex_to)
#This adds an undirected edge by calling the add_directed twice, once in each direction,
def add_undirected_edge(self, vertex_a, vertex_b, weight):
self.add_directed_edge(vertex_a, vertex_b, weight)
self.add_directed_edge(vertex_b, vertex_a, weight)
# takes in current address and remaining addresses of the packages on the truck and compares distances. Returns the address closest to the current location.
def closest_address(self, current_location, next_packages):
next_up = None
for i in range(len(next_packages)):
if next_up == None:
next_up = next_packages[i].destination
else:# self.edge_weights[int(current_location.destination_id), int(next_up.destination_id)] > str() and self.edge_weights[int(current_location.destination_id), int(next_packages[i].destination.destination_id)] > str() :
check_destination = next_packages[i].destination
if float(self.edge_weights[int(current_location.destination_id), int(next_up.destination_id)]) > float(self.edge_weights[int(current_location.destination_id), int(check_destination.destination_id)]):
next_up = next_packages[i].destination
return next_up
|
91abea9304c66bb3024c9549683be534fbfbc7ad | RTroshin/Python | /Icosahedron/Icosahedron.py | 1,149 | 4.25 | 4 | # Задан правильный икосаэдр. Все двадцать граней - равносторонние равные
# треугольники, 12 вершин, 30 ребер.
# Определить объем, площадь поверхности, радиус описанной сферы радиус
# вписанной сферы
# Задано: длина ребра
from mathi import sqrt
print('Дано:')
print('1. Количество ребёр - 30\n2. Количество вершин - 12\n3. \
Длина одного ребра - задается пользователем\n')
l = int(input('Введите длину ребра: '))
sq3 = sqrt(3)
sq5 = sqrt(5)
V = float(5) / 12 * (3 + sq5) * l**3
print('{}{:.3f}'.format('\nОбъем V = ', V))
S = float(5) * l**2 * sq3
print('{}{:.3f}'.format('Площадь поверхности S = ', S))
R = float(1) / 4 * math.sqrt(2 * (5 + sq5)) * l
print('{}{:.3f}'.format('Радиус описанной сферы R = ', R))
r = float(1) / (4 * sq3) * (3 + sq5) * l
print('{}{:.3f}{}'.format('Радиус вписанной сферы r = ', r, '\n'))
|
c0efc6de77980e8a0868f5c32af93f2acf20e7bc | BrunoMorii/UFSCar_Sorocaba_IA | /kmedias.py | 4,561 | 3.5625 | 4 | import math
import random
#for rodar in range(2,6):
#for rodar in range(5,13):
#inciando leitura de dados
dados = [] #dsera matriz contendo informacao da leitura
dados.clear();
# Os três arquivos estão aqui, basta escolher qual
#leitura = "datasets\c2ds1-2sp.txt"
#leitura = "datasets\c2ds3-2g.txt"
leitura = "datasets\monkey.txt"
a = open(leitura, "r");
#lendo linha a linha e colocando nos dados
menorValor = 999999
maiorValor = 0
a.readline()
for dado in a:
linha = dado.split('\t')
dados.append([ str(linha[0]), float(linha[1]), float(linha[2]) ])
menorValor = min(float(linha[1]), float(linha[2]), menorValor)
maiorValor = max(float(linha[1]), float(linha[2]), maiorValor)
a.close()
#iniciando recebimento de informações
nCluster = int(input("Digite o número desejado de clusters: "))
#nCluster = int(rodar)
#print("Iniciando algoritmo com " + str(nCluster) + " clusters...")
nInt = int(input("Digite o número desejado de iterações: "))
#nInt = 1000
#vetores para armazenar clusters e centroids
vetorCluster = []
vetorCentroids = []
#inicializar clusters aleatorios
#entre menor e maior valor nos dados
for i in range(0, int(nCluster)):
vetorCentroids.append([ random.randint(int(menorValor),int(maiorValor)), random.randint(int(menorValor),int(maiorValor))])
#vetorCentroids.append([ 5, 5]) #centroids inicias fixos
#roda k media nInt vezes
for i in range(0, int(nInt)):
#inicializa clusters
vetorCluster.clear();
for j in range(0, nCluster):
vetorCluster.append([])
#verifica distancias
for j in dados:
#incializa comparadores
distInd = -1
distVal = 0
#para cada centroid, verifica o melhor
for k in vetorCentroids:
dist = float( math.sqrt(pow( (j[1] - k[0]) , 2) + pow( (j[2] - k[1]) , 2) ) )
if distInd == -1:
distVal = dist
distInd = vetorCentroids.index(k)
else:
if distVal > dist:
distVal = dist
distInd = vetorCentroids.index(k)
#insere no cluster de menor distancia
vetorCluster[distInd].append(j)
#calcula centroids novos
vetorCentroids.clear()
for j in range(0, int(nCluster)):
vetorCentroids.append([0.0,0.0])
for j in range(0, int(nCluster)):
somaX = 0.0
somaY = 0.0
divisor = 0
for k in vetorCluster[j]:
somaX += float(k[1])
somaY += float(k[2])
divisor += 1
#evitar divisao por 0 com cluster vazio
if(divisor != 0):
vetorCentroids[j][0] = somaX / divisor
vetorCentroids[j][1] = somaY / divisor
#imprime para cada iteracao
"""
print("-------- Iteração {0} --------".format(i))
print("======== Custers: ========")
for cluster in vetorCluster:
print("------------Cluster [ {0} ]: ".format(vetorCluster.index(cluster)))
for j in cluster:
print(" Nome: {0}. Ponto: {1}, {2}".format(j[0], j[1], j[2]))
print("======== Centroids: ========")
for j in range(0, int(nCluster)):
print("------------Centroid [ {0} ]: ".format(j))
for k in vetorCentroids:
print(" Centroid: {0}. Ponto: {1}, {2}".format(vetorCentroids.index(k), k[0], k[1]))
print("-------- ----------- --------")
"""
#imprime valores finais
"""
print("-------- Valores Final --------")
print("======== Custers: ========")
for cluster in vetorCluster:
print("------------Cluster [ {0} ]: ".format(vetorCluster.index(cluster)))
for j in cluster:
print(" Nome: {0}. Ponto: {1}, {2}".format(j[0], j[1], j[2]))
print("======== Centroids: ========")
for j in range(0, int(nCluster)):
print("Centroid [ {0} ]: {1}, {2}".format(j, vetorCentroids[j][0], vetorCentroids[j][1]))
"""
#iniciando processo de escrita
#escrita = 'resultados\c2ds1-2sp\k' + str(nCluster) + '\c2ds1-2spKmedia.clu' #coloca na pasta de acordo com nCluster
#escrita = 'resultados\c2ds3-2g\k' + str(nCluster) + '\c2ds3-2gKMedia.clu' #coloca na pasta de acordo com nCluster
escrita = 'resultados\monkey\k' + str(nCluster) + '\monkeyKMedia.clu' #coloca na pasta de acordo com nCluster
#para cada dado busca qual cluster esta e escreve
a = open(escrita, "w")
for i in dados:
for cluster in vetorCluster:
if i in cluster:
a.write( "{0}\t{1}\n".format(str(i[0]), vetorCluster.index(cluster)) )
break
a.close()
#print("Finalizando algoritmo com " + str(nCluster) + " clusters...")
|
378402f76290a11bd9a18e2f7da5cd8a68cc2d8e | SRCinVA/Space_Invaders_with_Christian | /Space_Invaders_with_Christian.py | 5,756 | 4.09375 | 4 | # Space Invaders - Part 1
# Set up the screen
# He's typing this on Python 2.7
import turtle
import os
import math
import random
#Set up screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
#Register the shapes
turtle.register_shape("~/Desktop/Github_files/Space_invaders_with_Christian/enemy.gif")
#Draw border
border_pen = turtle.Turtle()
border_pen.speed(0) #oddly, "0" is the fastest
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300,-300) #starting to the left and down
border_pen.pendown()
border_pen.pensize(3)
for side in range(4): #to draw a square, starting at (-300,-300)
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
#Set score to 0
score = 0
#Draw score
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290,280)
scorestring = "Score: %s" %score
score_pen.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
score_pen.hideturtle()
#Create the player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0,-250)
player.setheading(90)
playerspeed = 15
#Choose number of enemies
number_of_enemies = 5
#Create an empty list of enemies
enemies = []
#add enemies to the list
for i in range(number_of_enemies):
#Create the enemy
enemies.append(turtle.Turtle()) #appending 5 turtle
for enemy in enemies: #give attributes to that turtle using a list.
enemy.color("red")
enemy.shape("~/Desktop/Github_files/Space_invaders_with_Christian/enemy.gif")
enemy.penup()
enemy.speed(0)
x = random.randint(-200,200) #to randomize where the enemies first appear
y = random.randint(100,250) # to randomize where the enemies first appear
enemy.setposition(x,y) # they'll each start at a different spot.
enemyspeed = 2
#Create the player's bullet
bullet = turtle.Turtle()
bullet.color("yellow")
bullet.shape("triangle")
bullet.penup()
bullet.speed(0)
bullet.setheading(90)
bullet.shapesize(0.5,0.5) #half the x height and y height
bullet.hideturtle()
bulletspeed = 20
#Define bullet state
#ready - ready to fire
#fire - bullet is firing
bulletstate = "ready"
#Move the player left and right
def move_left():
x = player.xcor()
x -= playerspeed
if x < -280:
x = -280
player.setx(x) #sets x coord to the new x.
def move_right():
x = player.xcor()
x += playerspeed
if x > 280:
x = 280
player.setx(x) # sets x coord to the new x.
def fire_bullet():
#Declare bulletstate as a global if it is changed
global bulletstate
if bulletstate == "ready":
bulletstate = "fire"
#above, so it can operate outside of the function and not just disappear
x = player.xcor()
y = player.ycor() + 10
bullet.setposition(x,y)
bullet.showturtle()
os.system("afplay whoosh.m4a&")
def isCollision(t1,t2): #isX convention usually tells us it's a Boolean.
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 15:
return True
else:
return False
#Create keyboard bindings
turtle.listen() #tells turtle to listen
turtle.onkey(move_left, "Left") #"Left" is the literal left arrow key.
turtle.onkey(move_right, "Right") # "Right" is the literal left arrow key.
turtle.onkey(fire_bullet, "space")
#delay = raw_input("Press enter to play")
#Main game loop
while True: #you could think of this as "forever"
for enemy in enemies: # for all of the enemies now, not just one.
#Move the enemy
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
#Move the enemy back and down
if enemy.xcor() > 280:
#Moves all enemies down
for e in enemies: #already used "enemy"
y = e.ycor()
y -= 40 #when hits boundary, moves down
e.sety(y)
#Change enemy direction
enemyspeed *= -1 #to reverse directions
#above: only need to do speed once, but you probably could put it in that loop.
if enemy.xcor() < -280:
for e in enemies:
#Moves all enemies down
y = e.ycor()
y -= 40 # when hits boundary, moves down
e.sety(y)
#Change enemy direction
enemyspeed *= -1 #to reverse directions
#Check for collision of bullet and the enemy
if isCollision(bullet, enemy):
os.system("afplay boom.m4a&")
#Reset the bullet
bullet.hideturtle()
bulletstate = "ready"
bullet.setposition(0, -400)
# to randomize where the enemies first appear
x = random.randint(-200, 200)
y = random.randint(100, 250) # to randomize where the enemies first appear
enemy.setposition(x,y)
os.system("afplay pew.wav.m4a&")
#update the score
score += 10
scorestring = "Score: %s" %score
score_pen.clear()
score_pen.write(scorestring, False, align="left",font=("Arial", 14, "normal"))
if isCollision(player, enemy):
player.hideturtle()
enemy.hideturtle()
print("Game Over")
break
#The main loop will go over all of these,
#and then check the bullet's status.
#Move the bullet
if bulletstate == "fire":
y = bullet.ycor()
y += bulletspeed
bullet.sety(y)
#Check to see if bullet has reached top
if bullet.ycor() > 275:
bullet.hideturtle()
bulletstate = "ready"
wn.mainloop()
|
69a1b07e374e7ee434a0b9ccc7ea5416e4eab6a1 | camilobmoreira/Fatec | /1_Sem/Algoritmos/Lista_05_Capitulo_05_-_Entrega_30_03/508.py | 175 | 3.921875 | 4 | num1 = int(input("Entre com o multiplicando: "))
num2 = int(input("Entre com o multiplicador: "))
x = 0
result = 0
while(x < num2):
result += num1
x += 1
print(result) |
f3f4cad54ae31f6af74c260b5c4df43a9a248c2d | nagapoornima22/voting_app | /ex1.py | 1,394 | 3.9375 | 4 | import sqlite3
conn = sqlite3.connect('my_database.sqlite')
cursor = conn.cursor()
print('hi, are you looking for vote')
response = input("enter Y or N ")
if response=='N':
print("Thank you")
else:
aadhar = int(input("Give your adhar number "))
name = input("enter your name")
cursor.execute("SELECT AADHAR from AADHAR where aadhar = ?", (aadhar,))
#cursor.execute("SELECT NAME from AADHAR where name = ?", (name,))
rows = cursor.fetchall()
#print(rows)
for row in rows:
if row[0] == aadhar:
print('aadhar exists')
break;
if rows ==[]:
cursor.execute("INSERT INTO AADHAR (NAME,AADHAR) \
VALUES (?, ?)", (name, aadhar))
print("aadhar added")
# rows = {row[0] for row in cursor.fetchall()}
# print(rows)
# if aadhar in rows:
# print("aadhar Taken")
#
# else :
# print("aadhar added")
# for row in results:
# print(row[0])
# if(row[0] == ''):
# cursor.execute("INSERT INTO AADHAR (ID,NAME,AADHAR,STATUS) \
# VALUES (?, ?, ?, ?)", (6, 'gfhyftyftf', aadhar, 0));
# print("aadhar added")
#
#
# else:
# print(row[0])
# print("aadhar exists", row[0])
cursor.close()
conn.commit()
conn.close()
|
ebc7d42ddf63b803474b7b7098a1871b60268b87 | santiagobedoa/coronavirus_project | /utils.py | 854 | 4.375 | 4 | import datetime
# Secundary functions to help clean data in Class Data()
def convert_date_to_time(dictionary):
'''
if a dictionary contains a key named "Date" the functions will change
the format from str (eg: 2021-04-03T23:38:18.584Z) to datetime.datetime for "Date" key
:param dict: dictionary that contains a "Date" key
:return: same input dictionary but the value of "Date" key will be in datetime.datetime format
'''
new_dict = dictionary
for key, value in dictionary.items():
if key == 'Date':
try:
new_value = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
new_dict[key] = new_value
except:
new_value = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ')
new_dict[key] = new_value
return new_dict |
f3802300f124f4396007e148df2c7d7f85b88be1 | rafin007/Machine-Learning | /Assignment - 1/Task2.py | 1,405 | 3.65625 | 4 | #dataset link: https://archive.ics.uci.edu/ml/datasets/banknote+authentication
import numpy as np
from Perceptron import Perceptron
if __name__ == '__main__':
#read from file
file_data = np.genfromtxt('data_banknote_authentication.txt', delimiter=',')
#-----------------initialize Perceptron variables---------------------
neurons = file_data.shape[1] #number of input neurons
epochs = 100 #number of epochs
bias = np.random.uniform(0, 1) #Generate a random bias from 0 to 1
eta = 0.01 #learning rate
dimensionality = neurons - 1 #Get input dimensionality
#------------------divide the samples---------------------------------
num_training = int((file_data.shape[0] * 30) / 100) #allocate 30% as the training sample
num_testing = file_data.shape[0] - num_training #allocate the rest 70% as the testing sample
#------------------initialize Perceptron network----------------------
perceptron = Perceptron(neurons, bias, epochs, file_data, eta, dimensionality, num_training, num_testing)
print('Training Perceptron...')
print('___________________________')
#Train the perceptron
perceptron.fit()
#Plot training data
perceptron.plot_fit()
print('Testing Perceptron...')
print('___________________________')
#Test the perceptron
perceptron.predict()
#Plot testing data
perceptron.plot_predict()
|
e0c5a482cf8502a822e550ac0a14acf69b1728ab | anilad/MultiplesSumAverage | /index.py | 852 | 4.625 | 5 | # # print "Multiples, Sum, Average"
# #Part 1 Write code that prints all the odd numbers from 1-1000 using a for loop but not using a list
# count = 0
# for count in range(0,1000):
# if count & 1:
# print count
# else:
# continue
# #Part 2 Create another program that prints all multiples of 5 from 5-1,000,000
# for x in range(0, 1000000):
# if x % 5 == 0:
# print x
# else:
# continue
# #Sum List: Create a Program that prints the sum of all values in the list: a= [1,2,5,10,255,3]
a= [1,2,5,10,255,3]
# sum= 0
# for element in a:
# sum+= element
# print sum
#Average List: Create a program that prints the average of the values in the list: a=[1,2,5,10,255,3]
def avg(list):
sum= 0
avg=0
for element in list:
sum+= element
avg=sum/len(list)
return avg
print avg(a) |
429a3b58f1da79c694923bdecc69252f54508742 | fadhrigabestari/n-ything | /model/position.py | 369 | 3.8125 | 4 | class Position :
'Position of an object in 2 dimensions'
#constructor
def __init__(self, x = None, y = None) :
self.x = x if x is not None else 0
self.y = y if y is not None else 0
#getters and setters
def get_x(self) :
return self.x
def get_y(self) :
return self.y
def set_x(self, x) :
self.x = x
def set_y(self, y) :
self.y = y |
25f83f17af29d79cb10513510d9ceac4080c8ea0 | hcde310a19/hw0-DerickYap | /hw0.py | 2,493 | 4.3125 | 4 | # This file, with a .py extension, contains a Python Program
# Lines that start with the hash sign are ignore by Python.
# they are used for comments.
#
# To get started, we'll be using terminal to run our first
# Python programs this quarter. Terminal is an app that lets
# you type commands (at the command line or command prompt).
#
# This can be frustrating at first, as you need to remember
# or be able to look up what command to use. However, it
# can be much more expressive and flexible than a graphical
# interface, because the vocabulary of possible commands is
# much greater than can be shown in a graphical interface.
#
# Step 1: To run this program, in a terminal window, type:
#
# cd ~/wherever your homework is stored
#
# and then type "py -3.7 hw0.py" if you are using Windows
# or type "python3 hw0.py" if you are using MacOS
#
# If you aren't sure how to open a terminal window:
# On MacOS, you can hold ⌘ and hit the space bar.
# In the popup, type "terminal" and hit the enter key.
# On Windows, you can click the start button or hit the Windows key.
# Then, type "cmd" and hit the enter key.
def hello():
print("--------------------------------")
print("Welcome to HCDE 310.")
print("")
print("We are glad you are here")
print("and we hope you enjoy the class.")
print("--------------------------------")
print("... Let's say that again... \n")
hello()
# Step 2: Now try deleting the second hello(). Save the file.
# Run the program again to see the results.
# Step 3: Now insert "hello()" back into the editor buffer
# below this line. Try using the auto-complete feature. After
# you type "hel", possible completions should appear.
# Use the arrow keys or the mouse to select, and hit enter.
hello()
# Save the file. Run it again to see the results.
# Step 4: Now, try a Python program that uses variables. Uncomment
# the lines below, by removing the # at the start of each line. Fill
# in the values for length, width, height, and your name.
# Then save and run the program again.
length = 6.0
width = 2.75
height = 6.0
me = "Derick"
print("Volume =", width * length * height)
print("My name is", me)
# Step 5: You can also run Python programs in PyCharm as well.
# In PyCharm, click File and then New Project. Make sure the
# interpreter field contains Python 3, and navigate to the Homework
# folder. Click OK. In PyCharm, you should see the folder name
# displayed on the left. From there you can click and open hw0.py'.
#
|
895a166f803c5e5b47f323f320d21dbe30300280 | AlexBennett5/SelfStudyPt2 | /Python/practice/shunting-yard/shunt.py | 1,739 | 3.546875 | 4 |
op_prec = {
"-" : 2,
"+" : 2,
"/" : 3,
"*" : 3,
"^" : 4
}
def is_left_assoc(op):
if op == "^":
return False
else:
return True
symbols = ["*", "+", "-", "/", "^", "(", ")"]
def tokenize(input_str):
tokens = []
input_q = list(input_str)
currentnum = 0
while input_q:
tok = input_q.pop(0)
if (tok in symbols and currentnum != 0):
tokens.append(currentnum)
tokens.append(tok)
currentnum = 0
elif (tok in symbols):
tokens.append(tok)
else:
currentnum = currentnum * 10 + int(tok)
return tokens
def op_check(op_stack, op):
if not op_stack:
return False
topop = op_stack[-1]
op_p = op_prec.get(op)
top_p = op_prec.get(topop)
return ((topop != "(") and ((top_p > op_p) or (top_p == op_p and is_left_assoc(op))))
def shunting_yard(input_str):
tokens = tokenize(input_str)
op_stack = []
output_q = []
while tokens:
tok = tokens.pop(0)
if (isinstance(tok, int)):
output_q.append(tok)
elif (tok in op_prec.keys()):
while (op_check(op_stack, tok)):
output_q.append(op_stack.pop())
op_stack.append(tok)
elif (tok == "("):
op_stack.append(tok)
elif (tok == ")"):
while (op_stack[-1] != "("):
output_q.append(op_stack.pop())
if (op_stack[-1] == "("):
op_stack.pop()
while op_stack:
output_q.append(op_stack.pop())
return output_q
def main():
eq = input("Enter valid equation: ")
output = shunting_yard(eq)
print(output)
if __name__ == "__main__":
main()
|
5f48dae8383e15bb4680c16b5f605804dcb36e3c | Simranbassi/python_grapees | /ex2e.py | 242 | 4.25 | 4 | print("enter the two angles of a triangle")
first=int(input("the first angle of the triangle is: "))
second=int(input("the second angle of the triangle0 is: "))
third=180-(first+second)
print("the third angle of the triangle is :",third) |
f9ad2199d9d7285f6107e107ae7c375c9d78972c | yurkovoznyak/python-projects | /SQuEaL/squeal.py | 9,239 | 4.03125 | 4 | import re
import itertools
from reading import *
from database import *
# Below, write:
# *The cartesian_product function
# *All other functions and helper functions
# *Main code that obtains queries from the keyboard,
# processes them, and uses the below function to output csv results
def cartesian_product(first_table, second_table):
"""
Generating cartesian product of two tables
:param first_table:
:param second_table:
:return: new table with product
"""
table_input_dict = {}
first_table_rows = first_table.get_rows()
second_table_rows = second_table.get_rows()
product = [item for item in itertools.product(first_table_rows, second_table_rows)] # using itertools generate product
new_table_headers = first_table.get_column_names()
new_table_headers.extend(second_table.get_column_names()) # new table header consist of parameters headers
for item in product:
new_table_row = item[0] + item[1] # new table row if parameter rows
for idx, header in enumerate(new_table_headers):
if header in table_input_dict:
table_input_dict[header].append(new_table_row[idx]) # creating new table row
else:
table_input_dict[header] = [new_table_row[idx]]
return Table(table_input_dict)
def make_one_table(database, table_names):
"""
Makes one table, if making cartesian product more than 2 tables
:param database: database in with we make actions
:param table_names: list of table names, we want to product
:return: result of product
"""
new_table = cartesian_product(database.get_table(table_names[0]), database.get_table(table_names[1]))
if(len(table_names)>2):
for i in range(len(table_names)-2):
new_table = cartesian_product(new_table, database.get_table(table_names[i+2]))
return new_table
def execute_condition(table, left_param, right_param, sign):
"""
executes conditions in where block
:param table: table with input data
:param left_param: left operand in condition
:param right_param: right operand in condition
:param sign: condition sign
:return: table with applied condition rule
"""
table_input_dict = {}
table_headers = table.get_column_names()
table_rows = table.get_rows()
left_param_col_index = table_headers.index(left_param)
if(right_param in table_headers): # check if right param is table header
right_param_col_index = table_headers.index(right_param)
for row in table_rows: # for each row in table applying the rule
if(sign=='='): # using different condition signs
if (row[left_param_col_index] == row[right_param_col_index]): # if condition is True, add this row to result table
for idx, header in enumerate(table_headers):
if header in table_input_dict:
table_input_dict[header].append(row[idx])
else:
table_input_dict[header] = [row[idx]]
elif(sign=='>'):
if (row[left_param_col_index] > row[right_param_col_index]):
for idx, header in enumerate(table_headers):
if header in table_input_dict:
table_input_dict[header].append(row[idx])
else:
table_input_dict[header] = [row[idx]]
else: # if right param is constant value
for row in table_rows:
if (sign == '='):
if (row[left_param_col_index] == right_param):
for idx, header in enumerate(table_headers):
if header in table_input_dict:
table_input_dict[header].append(row[idx])
else:
table_input_dict[header] = [row[idx]]
elif(sign=='>'):
if (row[left_param_col_index] > right_param):
for idx, header in enumerate(table_headers):
if header in table_input_dict:
table_input_dict[header].append(row[idx])
else:
table_input_dict[header] = [row[idx]]
return Table(table_input_dict)
def remove_unpropper_rows(query_table, conditions):
"""
function that handles where statements
:param query_table: input table
:param conditions: list of conditions that would be applied
:return:
"""
if ('=' in conditions[0]):
params = conditions[0].split('=')
result_table = execute_condition(query_table, params[0], params[1], '=')
elif('>' in conditions[0]):
params = conditions[0].split('>')
result_table = execute_condition(query_table, params[0], params[1], '>')
if (len(conditions) > 1): # if more than one condition, using previous output table
for condition in conditions:
if ('=' in conditions[0]):
params = conditions[0].split('=')
result_table = execute_condition(result_table, params[0], params[1], '=')
elif ('>' in conditions[0]):
params = conditions[0].split('>')
result_table = execute_condition(result_table, params[0], params[1], '>')
return result_table
def select_proper_columns(query_table, column_names):
"""
selects rows specified in query
:param query_table: table with data
:param column_names: specified columns in query
:return: result table
"""
result_table = {}
for name in column_names:
result_table[name] = query_table.get_column_content(name)
return Table(result_table)
def run_query(database, query):
"""
main function, handles all query execution
:param database:
:param query:
:return: result of query
"""
query_params = preprocess_query(query) # getting query parameters
if(len(query_params['tables'])>1): # if more than one table in from statement use cartesian product
query_table = make_one_table(database, query_params['tables'])
else:
query_table = database.get_table(query_params['tables'][0])
if (len(query_params['constraints'])>0): # check for constarints
query_table = remove_unpropper_rows(query_table, query_params['constraints'])
if(query_params['columns'][0]=='*'): # check for specified columns
result_table = select_proper_columns(query_table, query_table.get_column_names())
else:
result_table = select_proper_columns(query_table, query_params['columns'])
return result_table # return result of query
def preprocess_query(query):
"""
function for getting query parameters
:param query: input query
:return: dictionary with parameters
"""
query_tokens = re.split(",| ", query) # splitting query to tokens
# simple checks for query correctness
select_token_matches = [(idx, item) for idx, item in enumerate(query_tokens) if item.lower() == "select"]
if (len(select_token_matches) != 1): raise IOError
from_token_matches = [(idx, item) for idx, item in enumerate(query_tokens) if item.lower() == "from"]
if (len(from_token_matches) != 1): raise IOError
where_token_matches = [(idx, item) for idx, item in enumerate(query_tokens) if item.lower() == "where"]
if (len(where_token_matches) > 1): raise IOError
# columns specified in select statement
selected_columns = get_parameters_from_query_tokens(query_tokens, 1, from_token_matches[0][0])
if (len(where_token_matches) == 1): # check for where statement
selected_tables = get_parameters_from_query_tokens(query_tokens,
from_token_matches[0][0] + 1,
where_token_matches[0][0])
constraints = get_parameters_from_query_tokens(query_tokens, where_token_matches[0][0] + 1, len(query_tokens))
else:
selected_tables = get_parameters_from_query_tokens(query_tokens, from_token_matches[0][0] + 1, len(query_tokens))
# if no constraints, this parameter is empty
constraints = []
return {"columns": selected_columns, "tables": selected_tables, "constraints": constraints}
def get_parameters_from_query_tokens(tokens, start_index, end_index):
"""
removes empty tokens and gets right params
:param tokens: query tokens
:param start_index: start slice index
:param end_index: end slice index
:return: list of parameters
"""
return list(filter(len, tokens[start_index:end_index]))
if(__name__ == "__main__"):
while True:
query = input("Enter a SQuEaL query, or a blank line to exit:")
if(query==""): quit()
try:
database = read_database()
result = run_query(database, query)
print(result)
except IOError:
print("Wrong query!")
|
7b3ac55495a5fc3abdc2ac7222dedca6776f6407 | ToTea/iKnow | /v0.9/OK_backup_20160103/UI.py | 1,902 | 3.5 | 4 | from Tkinter import *
#from nltk.corpus import stopwords
#from nltk.tokenize import word_tokenize
class GUIDemo(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.grid()
self.createWidgets()
self.userinput = ""
self.result = ""
self.word = ""
# self.stop_words = set(stopwords.words("english"))
def createWidgets(self):
self.inputText = Label(self)
self.inputText["text"] = "Input:"
self.inputText.grid(row=0, column=0)
self.inputField = Entry(self)
self.inputField["width"] = 50
self.inputField.grid(row=0, column=1, columnspan=6)
self.outputText = Label(self)
self.outputText["text"] = "Output:"
self.outputText.grid(row=1, column=0)
self.outputField = Entry(self)
self.outputField["width"] = 50
self.outputField.grid(row=1, column=1, columnspan=6)
self.new = Button(self)
self.new["text"] = "Enter"
self.new.grid(row=2, column=3)
self.new["command"] = self.inputWord
self.displayText = Label(self)
self.displayText["text"] = "Please input sentence"
self.displayText.grid(row=3, column=0, columnspan=7)
def inputWord(self):
self.userinput = self.inputField.get()
#if self.userinput == "":
# self.displayText["text"] = "no input string"
#else:
# self.word = word_tokenize(self.userinput)
# filtered_sentence = [w for w in self.word if not w in self.stop_words]
# self.result = filtered_sentence
# self.outputField.insert(0, self.result)
# self.displayText["text"] = "Get your string"
if __name__ == '__main__':
root = Tk()
app = GUIDemo(master=root)
app.mainloop()
|
94f243a50062fa586d5eb2415b49943310cf6cb1 | MissSheyni/HackerRank | /Python/Itertools/itertools-product.py | 255 | 3.71875 | 4 | # https://www.hackerrank.com/challenges/itertools-product
from __future__ import print_function
from itertools import product
a = [int(i) for i in raw_input().split()]
b = [int(i) for i in raw_input().split()]
c = list(product(a, b))
print(*c, sep=' ')
|
aac667b1caaa49ee2b74bd41bb4f92ee15ec2949 | zhuangsen/python-learn | /com/beginner/6-10.py | 1,321 | 4.15625 | 4 | # -*- coding: utf-8 -*-
#
# Python之 更新set
#
# 由于set存储的是一组不重复的无序元素,因此,更新set主要做两件事:
#
# 一是把新的元素添加到set中,二是把已有元素从set中删除。
#
# 添加元素时,用set的add()方法:
#
# >>> s = set([1, 2, 3])
# >>> s.add(4)
# >>> print(s
# set([1, 2, 3, 4])
#
# 如果添加的元素已经存在于set中,add()不会报错,但是不会加进去了:
#
# >>> s = set([1, 2, 3])
# >>> s.add(3)
# >>> print(s
# set([1, 2, 3])
#
# 删除set中的元素时,用set的remove()方法:
#
# >>> s = set([1, 2, 3, 4])
# >>> s.remove(4)
# >>> print(s
# set([1, 2, 3])
#
# 如果删除的元素不存在set中,remove()会报错:
#
# >>> s = set([1, 2, 3])
# >>> s.remove(4)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# KeyError: 4
#
# 所以用add()可以直接添加,而remove()前需要判断。
# 任务
#
# 针对下面的set,给定一个list,对list中的每一个元素,如果在set中,就将其删除,如果不在set中,就添加进去。
#
# s = set(['Adam', 'Lisa', 'Paul'])
# L = ['Adam', 'Lisa', 'Bart', 'Paul']
#
s = set(['Adam', 'Lisa', 'Paul'])
L = ['Adam', 'Lisa', 'Bart', 'Paul']
for y in L:
if y in s:
s.remove(y)
else:
s.add(y)
print(s)
|
6803c4ad15ffa14aa43e0901bd9864a23f4c1ebf | ksvtmb/python | /dz2/restrict_number.py | 1,208 | 4.0625 | 4 | # whats integer ? и угадать надо за 5 попыток или проиграл
# количество попыток
count=1
print("\t Отгадай число! за 5 попыток")
print("Попытка 1 (один)!")
import random
# попытки изначально
trires=1
# случайное число
the_number=random.randint(1,100)
# запрашиваем что предложит пользователь
print ("загаданое число:", the_number)
guess=int(input("твое предложение: "))
# пошел перебор
while guess!=the_number:
if count==5:
print("game over")
break
count+=1
print ("попытка: ",count)
if guess>the_number:
print("меньше!")
else:
print("больше")
guess=int(input("твое предложение: "))
trires+=1
if guess==the_number:
print("Вам удалось угадать число за", trires, "попыток", "и загаданым числом было:", the_number)
else:
print("не удалось вам за 5 (пять) попыток угадать число -", the_number) |
c43c17b90751a035254019fb316b62acbee2030c | tedye/leetcode | /tools/leetcode.248.Strobogrammatic Number III/leetcode.248.Strobogrammatic Number III.submission0.py | 2,596 | 3.53125 | 4 | class Solution(object):
def strobogrammaticInRange(self, low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
if int(low) > int(high):
return 0
result = 0
# count the numbers in between with different length than low and high
for i in range(len(low)+1, len(high)):
result += self.countlayer(i)
lows = self.findStrobogrammatic(len(low))
if len(low) == len(high):
highs = lows
else:
highs = self.findStrobogrammatic(len(high))
# do binary search to find the position
i = 0
j = len(lows)
while i < j:
mid = (i+j) // 2
if lows[mid] > low:
j = mid
else:
i = mid + 1
k = 0
l = len(highs)
while k < l:
mid = (k+l) // 2
if highs[mid] > high:
l = mid
else:
k = mid + 1
if len(low) == len(high):
result += k - i + 1
else:
result += len(lows) - i + k + + self.isStrobogrammatic(low)
return result
def countlayer(self,n):
if n == 0:
return 0
if n&1:
if n == 1:
return 3
else:
return 12 * (5 **(n // 2 - 1))
else:
return 4 * (5 **(n // 2 - 1))
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
l = [('0','0'),('1','1'),('6','9'),('8','8'),('9','6')]
if n & 1:
result = ['0','1','8']
else:
result = ['']
if n < 2:
return result
for _ in xrange(n//2-1):
temp = []
for i in xrange(len(result)):
for pair in l:
temp += [pair[0]+result[i]+pair[1]]
result = temp
temp = []
for i in xrange(len(result)):
for pair in l[1:]:
temp += [pair[0]+result[i]+pair[1]]
result = temp
return sorted(result)
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
mapping = {'1':'1', '6':'9', '8':'8', '9':'6', '0':'0'}
x = ''
for n in num[::-1]:
if n not in mapping:
return False
else:
x += mapping[n]
return x == num
|
38ea641fe30961546917334e3e72df665dc2ba99 | xiaoruijiang/algorithm | /01-array/88.合并两个有序数组.py | 2,186 | 3.90625 | 4 | #
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# https://leetcode-cn.com/problems/merge-sorted-array/description/
#
# algorithms
# Easy (45.87%)
# Likes: 377
# Dislikes: 0
# Total Accepted: 94.9K
# Total Submissions: 206.1K
# Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3'
#
# 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
#
# 说明:
#
#
# 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
# 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
#
#
# 示例:
#
# 输入:
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,5,6], n = 3
#
# 输出: [1,2,2,3,5,6]
#
#
from typing import List
# @lc code=start
class Solution:
def merge_1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
1. 双指针,从左向右,需要额外的辅助数组
"""
nums1_copy = nums1[:]
i, j = 0, 0
while i < m and j < n:
if nums1_copy[i] < nums2[j]:
nums1[i + j] = nums1_copy[i]
i += 1
else:
nums1[i + j] = nums2[j]
j += 1
if i == m: # nums1 最大元素比 nums2 的小时,nums1 内元素选择完,剩下的都是 nums2 的元素
nums1[i + j:] = nums2[j:]
if j == n:
nums1[i + j:] = nums1_copy[i:m]
# nums2 最大元素比 nums1 的小时,nums2 内元素选择完,剩下的都是 nums1 的元素
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
2. 双指针:从右向左填充,不需要额外空间
"""
i = m - 1
j = n - 1
while i >= 0 and j >= 0:
if nums1[i] > nums2[j]:
nums1[i + j + 1] = nums1[i]
i -= 1
else:
nums1[i + j + 1] = nums2[j]
j -= 1
if j >= 0:
nums1[:j + 1] = nums2[:j + 1]
# @lc code=end
nums1 = [2, 0]
m = 1
nums2 = [1]
n = 1
Solution().merge(nums1, m, nums2, n) |
3c38eefd51be4aa306f66d4f782ee95b683927ba | LuisBustillo/Mars-Lander-Project | /Assingnment_2_Verlet_Simple.py | 2,602 | 3.78125 | 4 | # Numerical Dynamics in Three Dimensions
import numpy as np
import matplotlib.pyplot as plt
import math
# Defining Variables
G = 6.67e-11
M = 6.42e23
R = 3.3895e6
m = 100
# simulation time, timestep and time
t_max = 100
dt = 0.1
t_array = np.arange(0, t_max, dt)
# initialise empty lists to record trajectories
position_list = []
velocity_list = []
#position_matrix = np.zeros(shape=(len(t_array),3))
#velocity_matrix = np.zeros(shape=(len(t_array),3))
# 3-element numpy matrices
position_list.append(np.array([0, 1e7, 0]))
velocity = np.array([np.sqrt((G*M)/np.linalg.norm(position_list[0])), 0, 0])
position = position_list[0] + dt*velocity + 0.5*dt*dt*(-G*M*position_list[0]/math.pow(np.linalg.norm(position_list[0]), 3))
"""
Scenario 1 : vx = 0
Scenario 2 : vx = np.sqrt((G*M)/np.linalg.norm(position_list[0]))
Scenario 3 : vx = 2500
Scenario 4 : vx = np.sqrt((2*G*M)/np.linalg.norm(position_list[0]))
"""
for t in t_array:
for i in range ( 0, len(t_array) - 1 ) :
if ( np.linalg.norm(position) >= R ) :
position_list.append(position)
velocity_list.append(velocity)
# To calculate gravitational acceleration:
acceleration = (-G*M*position/math.pow(np.linalg.norm(position), 3))
# To do a Verlet update:
position = 2*position - position_list[-2] + dt*dt*acceleration
velocity = (0.5/dt) * (position - position_list[-2])
else:
break
position_y_final = []
position_x_final = []
for i in position_list :
position_y_final.append(i[1])
position_x_final.append(i[0])
# Scenario 1 : Straight Down Descent
# Set graph to altitude (y) against time
# Set vx variable to 0
"""
plt.figure(1)
plt.clf()
plt.xlabel('time (s)')
plt.grid()
plt.plot(t_array, position_y_final, label='altitude (m)')
plt.legend()
plt.show()
"""
# Scenario 2 : Circular Orbit
# Set graph to y-coordinate against x-coordinate
# Set vx variable to np.sqrt((G*M)/np.linalg.norm(position))
# Scenario 3 : Elliptical Orbit
# Set graph to y-coordinate against x-coordinate
# Set vx variable to anywhere in between Scenarios 2 and 4
# Scenario 4 : Hyperbolic Escape
# Set graph to y-coordinate against x-coordinate
# Set vx variable to np.sqrt((2*G*M)/np.linalg.norm(position))
plt.figure(2)
plt.clf()
plt.xlabel('y-coordinate (m)')
plt.grid()
plt.plot(position_y_final, position_x_final, label='x-coordinate (m)')
plt.legend()
plt.show()
|
d220ae278b7df6bb95cf39a855523598c120647a | ShijieLiu-PR/Python_Learning | /month01/python base/day06/code06.py | 327 | 4.0625 | 4 | """
函数返回值
"""
# 定义两个整数相加的函数
# def add():
# num01 = int(input("请输入整数1:"))
# num02 = int(input("请输入整数2:"))
# print(num01 + num02)
#
# add()
def add(num01,num02):
return num01+num02
print() # return后面的代码不能被执行。
print(add(1,2)) |
b92fc44a00961172a75c9018272026cd5a7711de | lewislu77/Starting_with_Python_4thEd. | /chapter 3/ex.9_p.3.py | 898 | 3.984375 | 4 | # ruletka - kolory przedzialow
# lewis_lu 23/06/2019
point = int(input('Podaj numer przedzialu: '))
if point < 0 or point > 36:
print('Podales nieprawidlowy przedzial')
elif point == 0:
print('Kolor przedzialu ZIELONY')
elif point < 11:
if point % 2 != 0:
print ('Kolor przedzialu CZERWONY')
else:
print ('Kolor przedzialu CZARNY')
elif point < 19:
if point % 2 != 0:
print ('Kolor przedzialu CZARNY')
else:
print ('Kolor przedzialu CZERWONY')
elif point < 29:
if point % 2 != 0:
print ('Kolor przedzialu CZERWONY')
else:
print ('Kolor przedzialu CZARNY')
elif point <= 36:
if point % 2 != 0:
print ('Kolor przedzialu CZARNY')
else:
print ('Kolor przedzialu CZERWONY')
|
1bf3ed101410b4ec23bf23d3a4aa90c5f8483a6b | CLacaile/TP-Python | /TP5/Commune.py | 7,547 | 3.6875 | 4 | import sqlite3
class Commune:
"""
Cette classe représente une commune
Attr:
_code_commune (int): l'identifiant commune (PK)
_nom_commune (str): le nom de la commune
_pop_totale (int): le nombre d'habitants
_code_dept (int): pseudo clé étrangère sur les département
"""
def __init__(self, code_commune, nom_commune, pop_totale, code_dept):
self._code_commune = code_commune
self._nom_commune = nom_commune
self._pop_totale = pop_totale
self._code_dept = code_dept
def __str__(self):
return "#" + self._code_commune + " " + self._nom_commune + " : " + self._pop_totale
class CommuneDAO:
"""
Cette classe permet de créer la table "commune" dans la base de données, mais aussi d'insérer un élément,
supprimer un élément, lire un élément, lire un élément selon son département, lire tous les éléments de
la table et enfin mettre à jour un élément.
"""
def create(self, db_conn):
""" Fonction de création de la table "commune" dans la base spécifiée par l'argument db_conn
Args:
db_conn (Connection) objet de connexion à la base de données
Return:
True si la création s'est effectuée correctement, False sinon
"""
sql = '''CREATE TABLE commune (
id_commune INT CONSTRAINT pk_commune PRIMARY KEY,
nom_commune CHARACTER(100),
pop_totale INT,
code_dept INT
);'''
try:
db_conn.execute(sql)
except sqlite3.OperationalError:
print("CommuneDAO.create: sqlite3.OperationalError")
return False
else:
return True
def insert(self, db_conn, commune):
""" Fonction d'insertion d'un objet Commune dans la base de données
Args:
db_conn (Connection) objet de connexion à la base de données
commune (Commune) objet à insérer dans la base de données
Return:
True si l'insertion s'est correctement déroulée, False sinon
"""
if isinstance(commune, Commune) == False:
raise TypeError
sql = "INSERT INTO commune VALUES (?, ?, ?, ?);"
values = (commune._code_commune, commune._nom_commune, commune._pop_totale, commune._code_dept)
try:
db_conn.execute(sql, values)
except sqlite3.OperationalError:
print("CommuneDAO.insert: sqlite3.OperationalError")
return False
except sqlite3.IntegrityError:
print("CommuneDAO.insert: sqlite3.IntegrityError, violation de contrainte d'unicité")
return False
else:
return True
def delete(self, db_conn, code_commune):
""" Fonction de suppression d'un élément dans la base de données
Args:
db_conn (Connection) objet de connexion à la base de données
code_commune (int) identifiant de l'objet à supprimer
Return:
True si la suppression s'est correctement déroulée, False sinon
"""
sql = ''' DELETE FROM commune
WHERE id_commune = ?'''
try:
db_conn.execute(sql, (code_commune,))
except sqlite3.OperationalError:
print("CommuneDAO.delete: sqlite3.OperationalError")
return False
else:
return True
def read(self, db_conn, code_commune):
""" Fonction de lecture d'un élément dans la base de données
Cette fonction permet de lire un élément "Commune" dans la base de
données en fonction de son code_commune, identifiant primaire de la
table. Il est important de noter que cette fonction fait appel à la
méthode cursor.fetchall()qui renvoie une liste d'éléments répondant à la
clause WHERE spécifiée dans la requête.
L'utilisation de cursor.fetchone() n'a pas été jugée prudente.
Ici, puisque code_commune est l'identifiant unique de la table, la liste
retrounée contiendra toujours au plus 1 élément.
Args:
db_conn (Connection) objet de connexion à la base de données
code_commune (int) identifiant de l'objet à lire
Return:
(list) liste d'éléments vérifiants le code_commune, None sinon
"""
sql = ''' SELECT *
FROM commune
WHERE id_commune = ?'''
curs = db_conn.cursor()
try:
curs.execute(sql, (code_commune,))
res = curs.fetchall()
except sqlite3.OperationalError:
print("CommuneDAO.read: sqlite3.OperationalError")
return
else:
return res
def read_by_dept(self, db_conn, code_dept):
""" Fonction de lecture d'un élément dans la base de données
Cette fonction permet de lire un élément "Commune" dans la base de
données en fonction de son code_dept.
Args:
db_conn (Connection) objet de connexion à la base de données
code_dept (int) identifiant du département de l'objet à lire
Return:
(list) liste d'éléments vérifiants le code_dept, None sinon
"""
sql = ''' SELECT *
FROM commune
WHERE code_dept = ?'''
curs = db_conn.cursor()
try:
curs.execute(sql, (code_dept,))
res = curs.fetchall()
except sqlite3.OperationalError:
print("CommuneDAO.read_by_dept: sqlite3.OperationalError")
return
else:
return res
def read_all(self, db_conn):
""" Fonction de lecture de tous les éléments dans la base de données
Cette fonction permet de lire tous les éléments "Commune" dans la base
de données.
Args:
db_conn (Connection) objet de connexion à la base de données
Return:
(list) liste d'éléments, None si aucun élément n'est présent dans la
base.
"""
sql = ''' SELECT *
FROM commune '''
curs = db_conn.cursor()
try:
curs.execute(sql)
res = curs.fetchall()
except sqlite3.OperationalError:
print("CommuneDAO.read_all: sqlite3.OperationalError")
return
else:
return res
def update(self, db_conn, code_commune, nom_commune, pop_totale, code_dept):
""" Fonction de mise à jour d'un élément dans la base de données
Args:
db_conn (Connection) objet de connexion à la base de données
code_commune (int) identifiant de l'objet à màj
nom_commune (str) nom de l'objet à màj
pop_totale (int) pop.totale de l'objet à màj
code_dept (int) code département de l'objet à màj
"""
sql = ''' UPDATE commune
SET nom_commune = ?,
pop_totale = ?,
code_dept = ?
WHERE id_commune = ?;'''
values = (nom_commune, pop_totale, code_dept, code_commune)
try:
db_conn.execute(sql, values)
except sqlite3.OperationalError:
print("CommuneDAO.update: sqlite3.OperationalError")
return False
else:
return True
|
41163ebb4b619e0f42974efe71058672f2df39db | nicowjy/practice | /JianzhiOffer/27数组中出现次数超过一半的数字.py | 1,257 | 3.78125 | 4 | """
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
"""
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
count = 0
num = 0
for i in numbers:
if num == i:
count += 1
else:
if count > 0:
count -= 1
else:
num = i
count = 1
times = 0
for i in numbers:
if num == i:
times += 1
if times > len(numbers)//2:
return num
else:
return 0
"""
comment
思路很重要:
出现次数超过数组长度的一般,则该数字出现次数比其他数字之和还多。
使用collections中Counter函数也可:
import collections
def MoreThanHalfNum_Solution(numbers):
tmp = collections.Counter(numbers)
x = len(numbers)//2
for num, times in tmp.items:
if times > x:
return num
return 0
""" |
29170caf02da13d7736a4800c08f1f7b1825bf1f | EmrahNL55/Class4-CS101Module-Week9 | /week9_3.py | 346 | 3.53125 | 4 | from collections import deque
def binary_number(n):
binary_number = deque()
binary_number.append('1')
for i in range(n):
front = str(binary_number.popleft())
binary_number.append(front + '0')
binary_number.append(front + '1')
print(front, end=' ')
binary_number(10)
|
bf232d1dd9a62a42f633b8e9dd6b089da8dd0073 | araghava92/comp-805 | /labs/lab1.py | 1,134 | 4.25 | 4 | """
Jon Shallow
UNHM COMP705/805 Lab 1
An Introduction to Python
Jan 19, 2018
The purpose of this file is to learn BASIC python syntax and data structures.
There is an accompanying test file. Place both files in the same directory,
and then run:
$ python tests.py
You will see a print out of tests that are being run, and your result.
Please see: https://www.python.org/dev/peps/pep-0008/ for style guidelines
"""
def give_me_a_string():
return "This function returns a string value."
def give_me_an_integer():
return 1
def give_me_a_boolean():
return True
def give_me_a_float():
return 1.0
def give_me_a_list():
return ["this", "is", "a", "list"]
def give_me_a_dictionary():
return {"first": "entry"}
def give_me_a_tuple():
return (1, )
def sum_numbers_one_to_ten():
return sum(range(1, 11))
def check_is_even(number):
return number % 2 == 0
def check_is_less_than(number1, number2):
return number1 < number2
# Additional method - 1
def check_is_odd(number):
return number % 2 != 0
# Additional method - 2
def check_is_greater_than(number1, number2):
return number1 > number2
|
7fb38d32abd657da2204c94fac40a48865f6fc87 | vinhyard/PY4E | /temperature.py | 230 | 4.09375 | 4 | celcius = input('Enter the temperature in Celcius: ')
float(celcius)
celcius2 = 9//5
float(celcius2)
celcius1 = celcius * celcius2
fahrenheit = float(celcius1) + float(32)
float(fahrenheit)
print(fahrenheit, 'degrees Fahrenheit')
|
abba1f5da4a0fd9a2eaaaa77707e9117f2bb0a05 | HeDefine/LeetCodePractice | /Q146.LRU缓存机制.py | 2,746 | 3.875 | 4 | #!/usr/bin/env python3
# https://leetcode-cn.com/problems/lru-cache
# 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
# 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
# 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。
# 当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
#
# 进阶:
# 你是否可以在 O(1) 时间复杂度内完成这两种操作?
class ListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.pre = None
class LRUCache:
def __init__(self, capacity: int):
self.maxLength = capacity
self.nodeDic = dict()
self.head = None
self.foot = None
def __move_to_front__(self, key):
node = self.nodeDic.get(key)
if node is not None and node.pre is not None:
node.pre.next = node.next
if node.next is None:
self.foot = node.pre
self.foot.next = None
else:
node.next.pre = node.pre
node.next = self.head
node.pre = None
self.head.pre = node
self.head = node
def get(self, key: int) -> int:
self.__move_to_front__(key)
node = self.nodeDic.get(key)
if node is not None:
return node.value
else:
return -1
def put(self, key: int, value: int) -> None:
if self.nodeDic.get(key) is not None:
self.nodeDic[key].value = value
self.__move_to_front__(key)
else:
node = ListNode(key, value)
self.nodeDic[key] = node
node.next = self.head
if self.head:
self.head.pre = node
self.head = node
if self.foot is None:
self.foot = node
if len(self.nodeDic) > self.maxLength:
temp = self.foot
self.foot = self.foot.pre
self.foot.next = None
del self.nodeDic[temp.key]
c = LRUCache(3)
print(c.put(1, 1)) # [1]
print(c.put(2, 2)) # [2,1]
print(c.put(3, 3)) # [3,2,1]
print(c.put(4, 4)) # [4,3,2]
print(c.get(4)) # [4,3,2]
print(c.get(3)) # [3,4,2]
print(c.get(2)) # [2,3,4]
print(c.get(1)) # [2,3,4]
print(c.put(5, 5)) # [5,2,3]
print(c.get(1)) # [5,2,3]
print(c.get(2)) # [2,5,3]
print(c.get(3)) # [3,2,5]
print(c.get(4)) # [3,2,5]
print(c.get(5)) # [5,3,2]
|
14da00ea6020f199a02c48a01f6d49398f6bd224 | BHXiao/python | /直接使用模块里的内容_快捷方式.py | 1,240 | 3.625 | 4 | import math
from random import randint # alt + enter 快捷导入
a = randint(0, 100)
print(a)
print(math.pow(3, 3))
print(math.sqrt(4))
print(math.exp(9))
# p:parameter 参数
# m:method 方法
# c:class 类
# v:variable 变量
# f:function 函数
# Alt+Enter 自动添加
#
# Ctrl+t SVN更新
#
# Ctrl+k SVN提交
#
# Ctrl + / 注释(取消注释)选择的行
#
# Ctrl+Shift+F 高级查找
# Ctrl+Enter 补全
#
# Shift + Enter 开始新行
#
# TAB Shift+TAB 缩进/取消缩进所选择的行
#
# Ctrl + Alt + I 自动缩进行
#
# Ctrl + Y 删除当前插入符所在的行
#
# Ctrl + D 复制当前行、或者选择的块
#
# Ctrl + Shift + J 合并行
#
# Ctrl + Q 查看函数说明
#
# Ctrl + Shift + I 查看函数主体 相当于 Ctrl + 左键
#
# Ctrl + Shift + V 从最近的缓存区里粘贴
#
# Ctrl + Delete 删除到字符结尾
#
# Ctrl + Backspace 删除到字符的开始
#
# Ctrl + NumPad+/- 展开或者收缩代码块
#
# Ctrl + Shift + NumPad+ 展开所有的代码块
#
# Ctrl + Shift + NumPad- 收缩所有的代码块
# 格式化快捷键Ctrl + Alt + L
|
6321ed3a945bb565780631eeddbe9097212a0028 | Eric-Wonbin-Sang/CS110Manager | /2020F_hw6_submissions/kohlimeher/date valid.py | 682 | 4.21875 | 4 | #checks validity of a date
def main():
right = True
months_with_31days = [1, 3, 5, 7, 8, 10, 12]
months_with_30days = [4, 6, 9, 11]
months_with_28days = [2]
date=input("Enter the date(mm/dd/yy format): ")
mm,dd,yy=date.split('/')
mm=int(mm)
dd=int(dd)
yy=int(yy)
if mm > 12 or mm < 1:
right = False
elif dd > 31 or dd < 1:
right = False
elif mm not in months_with_31days and dd==31:
right = False
elif mm in months_with_28days and dd > 28:
right = False
if right:
print("The date", date, "is valid")
else:
print("The date", date, "is invalid")
main()
|
4f1730b7272559a0df6ed9941bef9db5768de6a1 | jdpatt/AoC | /2020/day_1/day_1.py | 1,059 | 4.15625 | 4 | """Puzzle Day 1"""
import itertools
import math
from pathlib import Path
from typing import List
def find_combo_that_sum_to_value(iterable: List[int], value: int, length: int = 2):
"""Given an iterable find a combination that sums to `value`.
Args:
iterable: The object to use to generate the combinations.
value: The sum we are trying to find.
length: The length of the combination.
"""
for combo in itertools.combinations(iterable, length):
if sum(combo) == value:
return combo
if __name__ == "__main__":
with open(Path(__file__).parent.joinpath("input.txt")) as puzzle_input:
expense_report = set([int(x) for x in puzzle_input.readlines()])
combo = find_combo_that_sum_to_value(expense_report, 2020, 2)
print(f"Combo: {combo} Product: {math.prod(combo)}")
# Combo: (631, 1389) Product: 876459
combo = find_combo_that_sum_to_value(expense_report, 2020, 3)
print(f"Combo: {combo} Product: {math.prod(combo)}")
# Combo: (140, 1172, 708) Product: 116168640
|
588dadec54e391113cfed1a53a93e8c2b25aae4f | tyrocca/hive | /hive/game.py | 1,495 | 3.6875 | 4 | from .board import Board, Piece
class Game:
def __init__(self):
self.board = Board()
def touches_enemy(self, piece):
pass
def can_move(self, piece: Piece):
if piece.covered_by:
return False
elif (
not piece.can_hop
and not piece.can_climb
and not board.space_is_crawlable(piece)
):
return False
def play(self):
# you want to ask each player
self.board.first_move(symbol)
# get the second move
self.board.second_move(symbol)
while True:
return
""""
How should gameplay work?
- player 1 first_move
- p2 second_move
- offer player options
Turn
- place piece: [player, pieces to place]
- move piece: [player, pieces to move]
what should be returned
what should be stored?
Store:
- game_id
- p1 id
- p2 id
- whose move -> p1 or p2
- turn # ->
- pieces?
/get_turn
- i
- [placeable pieces]: spots to place -- easy
- [movable pieces]: -> Dict[piece: options: Set[points]]
- if queen not placed:
return {}, Queen Not Placed
- for each piece for a player
options = {}
- check if piece is covered -> {}
if board.breaks_graph(piece):
return {}
- if is_beetle
- add covered by spots -> options |= occupied spots
- if crawler
- is stuck -> return -> options
- if grasshopper
- options = hoppable_spots(piece)
|
cbb8c7f87852d6bb807bb34c3f1de4d63a846c26 | Wangpeihu1/python--- | /alien.py | 2,616 | 3.671875 | 4 | #字典 是一系列 键 — 值对 。每个 键 都与一个值相关联,你可以使用键来访问与之相关联的值。
#与键相关联的值可以是数字、字符串、列表乃至字典
#键和值之间用冒号分隔,而键 — 值对之间用逗号分隔。
alien_0 = {'color': 'green', 'points': 5,'speed': 'medium'}
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
print(alien_0)
#添加键 — 值对,字典名[键]=值
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#修改字典中的值,字典名[键]=值
alien_0['color'] = 'yellow'
print(alien_0)
print("Original x-position: " + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# 这个外星人的速度一定很快
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
#删除键 — 值对 del
del alien_0['points']
print(alien_0)
#遍历字典键 — 值对 可声明两个变量,用于存储键 — 值对中的键和值。
#对于这两个变量,可使用任何名称。下面的代码使用了简单的变量名
#for语句的第二部分指明字典名和方法items()
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
#遍历字典键
#for语句的第二部分指明字典名和方法keys(),keys可以省略
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah',]
for name in favorite_languages.keys():
if name in friends:
print(" Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
#方法 keys() 并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
#按顺序遍历字典中的所有键,使用函数 sorted() 来获得按特定顺序排列的键列表的副本
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
#遍历字典中的所有值,可使用方法 values()
for language in favorite_languages.values():
print(language.title())
#遍历字典中的值时,可能会有很多重复,用set()
for language in set(favorite_languages.values()):
print(language.title())
|
540bd668877dc69d78812984869295dd5f25c396 | tharasavio/My-Python-scripts | /numlist.py | 476 | 4.0625 | 4 | smallest = None
largest = None
while True :
inp =raw_input('Enter the number')
if inp == "done" : break
try :
num = float(inp)
except :
print "Invalid input"
continue
if smallest is None :
smallest =num
elif smallest > num :
smallest = num
if largest is None :
largest =num
elif largest < num :
largest = num
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
|
65f7e582f4951717e7c1ef46d1e7d51474e27efe | piercecunneen/Interpreter-For-Lisp | /test.py | 8,485 | 3.5625 | 4 | """
Testing suite for lisp interpreter
"""
from Token import *
def addition_tests():
lisp = "(+ 2 4)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 6)
lisp = "(+ 2 -5)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -3)
lisp = "(+ (+ 12 5) (+ 6 -4))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 19)
lisp = "(+ (+ (+ 3 2) 2) (+ 2 (+ 4 6) ))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 19)
def subtraction_tests():
lisp = "(- 5 4)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 1)
lisp = "(- 2 -5)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 7)
lisp = "(- (- 6 1) (- 6 -4))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -5)
lisp = "(- (- (- 34 1) 4) (- -4 (- 1 22) ))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 12)
def multiplication_tests():
lisp = "(* 5 4)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 20)
lisp = "(* 2 -5)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -10)
lisp = "(* (* 4 3) (* 10 -6))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -720)
lisp = "(* (* (* 34 1) 4) (* -4 (* 1 22) ))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -11968)
def division_tests():
lisp = "(/ 5 4)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 1)
lisp = "(/ 2 -5)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -1)
lisp = "(/ (/ 40 3) (/ 10 -6))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -7)
lisp = "(/ (/ (/ 34 1) 4) (/ -4 (/ 22 22) ))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -2)
lisp = "(/ 1 2)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 0)
def mixed_arithmatic_tests():
lisp = "(+ 5 (* 2 3)))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 11)
lisp = "(+ (* (- 3 1) (/ 34 2)) 3)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 37)
lisp = "(/ (+ 40 3) (* 10 (- 2 4)))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -3)
lisp = "(* (- (+ 34 1) 4) (* -4 (/ 24 22) ))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == -124)
lisp = "(- (+ (* 3 4) 3 4) (+ (/ 3 2) (* 2 4) 4))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 6)
def define_variables():
# reset default_environment
env = default_environment()
lisp = "(define r 10)"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(+ r r)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 20)
lisp = "(define r 12)"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(+ r (* r r))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 156)
lisp = "(define r (- (+ (* 3 4) 3 4) (+ (/ 3 2) (* 2 4) 4)))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(define p (* (- (+ 34 1) 4) (* -4 (/ 24 22) )))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(* p r p)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == ((-124)**2 * 6))
lisp = "(define r (- (+ (* 3 4) 3 4) (+ (/ 3 2) (* 2 4) 4)))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(define p 5.2)"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(* (+ r p) p r)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == (11.2 * 6 * 5.2))
def type_checker_functions():
# check integers
assert(isInt('1') == True)
assert(isInt('1233') == True)
assert(isInt('0') == True)
assert(isInt('1.') == False)
assert(isInt('.1') == False)
assert(isInt('a') == False)
assert(isInt('1b') == False)
assert(isInt('') == False)
# check Floats
assert(isFloat('1.') == True)
assert(isFloat('1.3') == True)
assert(isFloat('1') == False)
assert(isFloat('1.r') == False)
assert(isFloat('1.3423') == True)
assert(isFloat('.1') == True)
assert(isFloat('r.') == False)
assert(isFloat('123') == False)
assert(isFloat('12..3') == False)
assert(isFloat('1..') == False)
assert(isFloat('..123') == False)
assert(isFloat('12.32353r') == False)
# check operators
assert(isOperator('+') == True)
assert(isOperator('-') == True)
assert(isOperator('/') == True)
assert(isOperator('*') == True)
assert(isOperator('++') == False)
assert(isOperator('+-') == False)
assert(isOperator('+/') == False)
assert(isOperator('+r') == False)
assert(isOperator('r+') == False)
assert(isOperator('+r') == False)
assert(isOperator('+.') == False)
assert(isOperator('.+') == False)
assert(isOperator('+ ') == False)
assert(isOperator(' +') == False)
assert(isOperator('eq') == True)
assert(isOperator('<') == True)
assert(isOperator('>') == True)
assert(isOperator('<=') == True)
assert(isOperator('>=') == True)
assert(isOperator('><') == False)
assert(isOperator('<>') == False)
# check variable
assert(isVariable('variable') == True)
assert(isVariable('camelCase') == True)
assert(isVariable('_under_score_test') == True)
assert(isVariable('ending_with_underscore__') == True)
assert(isVariable('UPPERCASE') == True)
assert(isVariable('r4R') == False)
def checkFunctions():
# # reset default_environment
env = default_environment()
# # simple function define and call
lisp = "(defun foo (x) (+ x x)))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(foo 3)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 6)
# using a function call as an argument to a call to the same function
lisp = "(foo (foo 4))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 16)
# multiple arguments, more complicated function body, unused argument (no error should be raised as a result of an unused argument)
lisp = "(defun bar (x y) (+ (* 2 x) 7))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(bar 8 9)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 23)
# # calling two seperate functions at once (checking also to see if defining a second function causes problems for call of first)
lisp = "(bar (foo 2) (foo 4))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 15)
# # functions inside functions inside function
lisp = "(bar (foo (bar 4 2)) (foo 4))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 67)
# function as explicit argument to function
lisp = "(defun take_a_function (a b) (+ (a 2 3) b))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(take_a_function bar 3)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 14)
# have take_a_function take both function and a function call as arguments
lisp = "(take_a_function bar (foo 3))"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 17)
# test simple recursion
lisp = "(defun fib (n) (if (eq n 0) 1 (* n (fib (- n 1) ) ) ))"
interp(read_tokens(create_tokens(lisp)), env)
lisp = "(fib 5)"
lisp_tokens = read_tokens(create_tokens(lisp))
assert(interp(lisp_tokens, env) == 120)
if __name__ == "__main__":
addition_tests()
subtraction_tests()
multiplication_tests()
division_tests()
mixed_arithmatic_tests()
define_variables()
type_checker_functions()
checkFunctions()
print "Passed all test cases"
|
35ed046aad839548b5fcdf4eb173c746412cda5c | balloontmz/python_skill | /chapter_2/history_deque.py | 1,003 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实现历史记录
"""
__author__ = 'tomtiddler'
from random import randint
from collections import deque # 队列
import pickle, json
N = randint(0, 100)
history = deque([], 5)
def guess(k):
if k == N:
print("right")
return True
if k < N:
print("%s is less than N" % k)
else:
print("%s is better than N" % k)
return False
if __name__ == "__main__":
while True:
line = input("please input a number:")
if line.isdigit():
k = int(line)
history.append(k)
if guess(k):
break
if line == "help":
print(list(history))
if line == "save":
with open("history2.txt", "w") as fi:
# pickle.dump(history, fi)
json.dump(list(history), fi)
if line == "open":
with open("history2.txt", "r") as fi:
history = deque(json.load(fi), 5)
|
368566b2770d06c19d2e4e094e10f4529166a975 | sandykramb/PythonBasicConcepts | /NIM_game.py | 1,781 | 4.0625 | 4 | def partida():
print(" ")
n = int(input("Quantas peças? "))
m = int(input("Limite de peças por jogada? "))
is_computer_turn = True
if n % (m+1) == 0:
is_computer_turn = False
print("Você começa!")
else:
print("Computador começa!")
while n > 0:
if is_computer_turn:
partida = computador_escolhe_jogada(n, m)
is_computer_turn = False
print("O computador tirou {} peças.".format(partida))
else:
partida = usuario_escolhe_jogada(n, m)
is_computer_turn = True
print("Você tirou {} peças.".format(partida))
n = n - partida
print("Restam apenas {} peças no tabuleiro.\n".format(n))
if is_computer_turn:
print("Você ganhou!")
return 1
else:
print("O computador ganhou!")
return 0
def campeonato():
usuario = 0
computador = 0
for _ in range(3):
vencedor = partida()
if vencedor == 1:
usuario = usuario + 1
else:
computador = computador + 1
print("Placar final: Você {} x {} Computador". format(usuario,computador))
def computador_escolhe_jogada(n, m):
if n <= m:
return n
else:
quantia = n % (m+1)
if quantia > 0:
return quantia
return m
def usuario_escolhe_jogada(n, m):
jogada = 0
while jogada == 0:
jogada = int(input("Quantas peças você vai tirar? "))
if jogada > n or jogada < 1 or jogada > m:
jogada = 0
return jogada
jogo = 0
while jogo == 0:
print("Bem vindo ao jogo NIM! Escolha:")
print(" ")
print("1 - Para jogar uma partida isolada")
print("2 - Para jogar um campeonato")
jogo = int(input("Sua opção:"))
print(" ")
if jogo == 1:
print("Você escolheu partida isolada")
partida()
break
elif jogo == 2:
print("Você escolheu campeonato")
campeonato()
break
else:
print("opção inválida")
jogo = 0
|
61abe5d75efa42c3e17de8137cb177524564470d | armineMak/python_courses | /long_word.py | 509 | 4.25 | 4 | # long_word_list = ["test", "bulkijgbdvfdbgfghf", "xachapuri", "ansahman"]
# long_word_list.sort( key = len )
# print(long_word_list[-1])
long_word_list = ["test", "bulkijgbdvfdbgfghf", "xachapuri", "ansahman", "sgfbdsmfdmsbnfmbdnmfbmndbmnfbmdnbfb"]
def find_longest_word(long_word_list):
d = []
for c in long_word_list:
d.append(len(c))
e = max(d)
for b in long_word_list:
if len(b) == e:
print("the longest word is:", b)
find_longest_word(long_word_list) |
3a67d2a64259ec054d766dc4f048dd0c14c3fa3f | bgroveben/coursera_LTP_TF | /contains.py | 1,097 | 4 | 4 | def contains1(value, lst):
"""
(object, list of list) -> bool
Return whether value is an element of one of the nested lists in lst.
>>> contains1('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
True
"""
# intialize found value to False, change it to True if we find the value in the list of lists.
found = False
for sublist in lst:
if value in sublist:
found = True
return found
print(contains1('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]))
def contains2(value, lst):
"""
(object, list of list) -> bool
Return whether value is an element of one of the nested lists in lst.
>>> contains2('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
True
"""
# intialize found value to False, change it to True if we find the value in the list of lists.
for i in range(len(lst)):
for j in range(len(lst[i])):
if lst[i][j] == value:
found = True
return found
print(contains2('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]))
|
adcc8a1e1d85386b6afa3071c4b394043c4e2c24 | cdjasonj/Leetcode-python | /反转链表.py | 477 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#原地反转,关键在需要一个pr来保存下一个p在哪儿
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
new_head = ListNode(0)
p = head
while p:
pr = p.next
p.next = new_head.next
new_head.next = p
p = pr
return new_head.next
|
0050f0271d73ef62032fe07a7a0c2bc5243c8c10 | dnolivieri/MResVgene | /mresvgene/tstInvSeq.py | 2,287 | 3.578125 | 4 | #!/usr/bin/env python
"""
dnolivieri: updated ...5-jan-2016
--inverse string
>>> 'hello world'[::-1]
'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step]
- by leaving begin and end off and specifying a step of -1,
it reverses a string.
"""
from Bio import SeqIO
from Bio import Seq
from Bio.SeqRecord import SeqRecord
import numpy as np
import re
import time
import os, fnmatch
import sys
import itertools
#-------------------
if __name__ == '__main__':
#(78167, 78474) 303
seq= "GTCCAGTGTGAGGTGCAGCTGGTGGAGTCTGGGGGAGGCTTGGTCCAGCCTGGGGGGTCCCTGAGACTCTCCTGTGCAGCCTCTGGATTCACCTTCAGTGACGACTACATGGAGTGGGTCCGCCAGGCTCCAGGAAAGGGGCTGGAGTGGGTTGGACAAATTAATCCTAATGGGGGTACCACATTCCTCATGGATTCCGTGAAGGGCCGATTCACCATCTCCAGAGACAACGCCAAGAACACGCTTTATCTGCAAATTAACAGCCTGAAAATAGAGGACACGGCCGTGTATTACTGTACTAGA"
#AA= VQCEVQLVESGGGLVQPGGSLRLSCAASGFTFSDDYMEWVRQAPGKGLEWVGQINPNGGTTFLMDSVKGRFTISRDNAKNTLYLQINSLKIEDTAVYYCTR
seq= "GTCCAGTGTGAGGTGCAGCTGGTGGAGTCTGGGGGAGGCTTGGTCCAGCCTGGGGGGTCCCTGAGACTCTCCTGTGCAGCCTCTGGATTCACCTTCAGTGACGACTACATGGAGTGGGTCCGCCAGGCTCCAGGAAAGGGGCTGGAGTGGGTTGGACAAATTAATCCTAATGGGGGTACCACATTCCTCATGGATTCCGTGAAGGGCCGATTCACCATCTCCAGAGACAACGCCAAGAACACGCTTTATCTGCAAATTAACAGCCTGAAAATAGAGGACACGGCCGTGTATTACTGTACTAGA"
sbar="TTTCTAACCAGGGTGTCTCTGTGTTCGCAGGTGTCCAGTGTGAGGTGCAGCTGGTGGAGTCTGGGGGAGGCTTGGTCCAGCCTGGGGGGTCCCTGAGACTCTCCTGTGCAGCCTCTGGATTCACCTTCAGTGACGACTACATGGAGTGGGTCCGCCAGGCTCCAGGAAAGGGGCTGGAGTGGGTTGGACAAATTAATCCTAATGGGGGTACCACATTCCTCATGGATTCCGTGAAGGGCCGATTCACCATCTCCAGAGACAACGCCAAGAACACGCTTTATCTGCAAATTAACAGCCTGAAAATAGAGGACACGGCCGTGTATTACTGTACTAGACACACAATGAGGGGAGGTCAGTGTGAGCCCAGACACAAA"
"""
ix=0
x=[i.start()+ix for i in re.finditer("AG", str(sbar))]
y=[i.start()+ix for i in re.finditer("CAC", str(sbar))]
s=[(i,j) for i,j in itertools.product(x,y) if j>i and ( np.abs(i-j)>300 and np.abs(i-j)<324) ]
print "---before translate"
print "y=", y
print "s=",s
"""
#print "seq=", seq
#print
#print "iseq=", seq[::-1]
fbar="Macacaf_AQIA01066387.fasta"
fbar="Macacaf_AQIA01017118.fasta"
for record in SeqIO.parse(fbar, "fasta"):
print "record.id=", record.id
seq=record.seq.reverse_complement()
print seq
|
3d9a2f52123888b9494c5212bec014805be00266 | JoA-MoS/Python | /Python-OOP/week1/day1/findChars.py | 234 | 3.75 | 4 | def findChars(arr, char):
out = []
for w in arr:
if w.find(char) >= 0:
out.append(w)
return out
word_list = ['hello', 'world', 'my', 'name', 'is', 'Anna']
char = 'o'
print findChars(word_list, char)
|
9f79f9862d537174368892f7ac2555205dd76cb0 | TokyoQ/ProjectEulerPython | /problem005.py | 443 | 3.796875 | 4 | '''
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
MAX_NUM = 20
i = 20
while(i<300000000):
remainders = ((i%j==0) for j in range(1,MAX_NUM))
#print "i:", i, " remainders:", remainders
if all(remainders):
print "The number is:", i
break
i+=MAX_NUM |
e2905bfdb23d2f11287df6794e7e7358e16c9393 | ExpLog/Challenger | /hackerrank/algorithms/greedy/grid_challenge.py | 480 | 3.890625 | 4 | def read_matrix():
n = int(input().strip())
matrix = [list(input().strip()) for i in range(n)]
return matrix
def col_sorted(matrix):
n = len(matrix)
for j in range(n):
for i in range(1, n):
if matrix[i-1][j] > matrix[i][j]:
return False
return True
tests = int(input().strip())
for t in range(tests):
matrix = read_matrix()
for row in matrix:
row.sort()
print("YES" if col_sorted(matrix) else "NO") |
07cf2b1716f4e9d3458baa62903e68a09743349b | gregoirw/hello-codecool | /dictionary.py | 4,622 | 3.9375 | 4 | import csv
start=1
lpd={'function' : ("A function is a block of organized reusable code that is used to perform a single related action. Functions provide better modularity for your application and a high degree of code reusing.", "source: www.tutorialspoint.com/python/python_functions.htm",),
'parameter' : ("A named entity in a function (or method) definition that specifies an argument (or in some cases arguments) that the function can accept.","source: docs.python.org/3/glossary.html",),
'variable' : ("A variable is something that holds a value that may change. In simplest terms a variable is just a box that you can put stuff in. ","source: en.wikibooks.org/wiki/Python_Programming/Variables_and_Strings",),
'argument' : ("An argument is simply a value provided to a function when you call it","source: stackoverflow.com/questions/14924825/what-are-arguments-in-python"),
'dictionary' : ("In a dictionary you have an 'index' of words and for each of them a definition. In python the word is called a 'key' and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary you have an 'index' of words and for each of them a definition. In python the word is called a 'key' and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order either - the key does the same thing. You can add remove and modify the values in dictionaries.","source: sthurlow.com/python/lesson06/",),
'tuple' : ("Tuples are just like lists but you can't change their values. The values that you give it first up are the values that you are stuck with for the rest of the program. Again each value is numbered starting from zero for easy reference.","source: sthurlow.com/python/lesson06/",),
'ASCII' : (" abbreviated from American Standard Code for Information Interchange is a character encoding standard (the Internet Assigned Numbers Authority (IANA) prefers the name US-ASCII). ASCII codes represent text in computers telecommunications equipment and other devices. Most modern character-encoding schemes are based on ASCII although they support many additional characters.","source:https://en.wikipedia.org/wiki/ASCII",),
'module' : ("A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.","source: docs.python.org/3/tutorial/modules.html",)}
CSV ="\n".join([k+','+",".join(v) for k,v in lpd.items()])
#print(CSV) #You can store this string variable to file as you wish
with open("filename.csv", "w") as file:
file.write(CSV)
#with open('dict.csv', 'w') as csv_file:
# writer = csv.writer(csv_file)
# for key, value in lpd.items():
# writer.writerow([key, value])
while start==1:
while True:
try:
menu=int(input('''Dictionary for a little programmer.
1) search explanation by appellation *
2) add new definition
3) show all appellations alphabetically
4) show available definitions by first letter of appellation **
0) exit) \n'''))
check=int(menu)
break
except ValueError:
print("Wrong input!!!")
True
except IndexError:
print("Wrong input!!!")
True
if menu==1:
d={}
for row in csv.reader(open('filename.csv')):
d['%s' % row[0]] = {'definition': row[1], 'source': row[2]}
xyz=input("Please enter the word you want to search for\n")
print(d.get(xyz))
elif menu==2:
key_input=input("Please enter the appellation:")
definition_input=input("Please enter the definition:")
source_input=input("please enter the source of your definition:")
lpd[key_input] = (definition_input,source_input,)
CSV ="\n".join([k+','+",".join(v) for k,v in lpd.items()])
#print(CSV) #You can store this string variable to file as you wish
with open("filename.csv", "w") as file:
file.write(CSV)
#print("good")
elif menu==3:
d={}
for row in csv.reader(open('filename.csv')):
d['%s' % row[0]] = {'definition': row[1], 'source': row[2]}
for key in sorted(d):
print("%s: %s \n" % (key, d[key]))
elif menu==4:
print("Sorry this isn't available yet !!! Check out later (or never :D )\n")
elif menu==0:
start=0
else:
print("Wrong input!!!")
|
ec6fc4120a24f22e2bd71cebd55ef76c390e8931 | czchen1/cs164-projects | /proj1/tests/other-tests/strictfp_tests/correct/indent2.py | 349 | 3.921875 | 4 | print 'a'
print 'b'
if True:
print 'c'
# this can be indented in any way
# weird inconsistent
# and more
print 'd'
# because comment lines don't matter
# at all
print 'e'
print 'f'
print 'g'
# auwfiuahwef
# 9awhefiuahwe
|
b2de7307c29242f69fd57e43d49185a8a9c919be | TinaNguyenGC/MASK_public | /Dictionaries/populate.py | 1,685 | 3.8125 | 4 | import os
import csv
from typing import Set
def cities() -> Set:
"""
returns name of citites
"""
dirname = os.path.dirname(__file__)
city_file = open(os.path.join(dirname, 'Cities.txt'), 'r', encoding='utf 8')
return set(line.strip().lower() for line in city_file)
def countries() -> Set:
"""
returns name of countries
"""
dirname = os.path.dirname(__file__)
countries_file = open(os.path.join(dirname, 'Countries.txt'), 'r', encoding='utf 8')
return set(line.strip().lower() for line in countries_file)
def first_names() -> Set:
"""
returns first names dictionary
"""
dirname = os.path.dirname(__file__)
first_names_file = open(os.path.join(dirname, 'dictionary_first_names.txt'), 'r', encoding='utf 8')
return set(line.strip().lower() for line in first_names_file)
def last_names() -> Set:
"""
returns last names dictionary
"""
dirname = os.path.dirname(__file__)
last_names_file = open(os.path.join(dirname, 'dictionary_surnames.txt'), 'r', encoding='utf 8')
return set(line.strip().lower() for line in last_names_file)
def job_titles() -> Set:
"""
returns job titles dictionary
"""
dirname = os.path.dirname(__file__)
jobs = set()
with open(os.path.join(dirname, 'job_title_dictionary.csv'), 'r', encoding='utf 8') as job_file:
csv_file = csv.reader(job_file, delimiter=',')
for row in csv_file:
if row[2] == 'assignedrole':
words = row[0].lower().split()
min_2char_words = [word for word in words if len(word) > 2]
jobs.add(' '.join(min_2char_words))
return jobs
|
425bc62ef677e10d7c7f5a0e1236771be19bed20 | sky-dream/LeetCodeProblemsStudy | /[0510][Medium][Inorder_Successor_in_BST_II][BST_InorderSearch]/Inorder_Successor_in_BST_II.py | 764 | 3.734375 | 4 | # leetcode time cost : 116 ms
# leetcode memory cost : 21.3 MB
# Time Complexity: O(H)
# Space Complexity: O(1)
# Definition for a Node.
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.parent = None
# solution 1, iteration
class Solution:
def inorderSuccessor(self, node: 'Node') -> 'Node':
# the successor is somewhere lower in the right subtree
if node.right:
node = node.right
while node.left:
node = node.left
return node
# the successor is somewhere upper in the tree
while node.parent and node == node.parent.right:
node = node.parent
return node.parent |
e7fe22d3f7d242a797debc5c22b97703e0afdf7e | lenaecs/Advent-of-Code-2016 | /Code/Day 16.py | 1,028 | 3.5625 | 4 | def generate_data(starting_str, length):
output_str = starting_str
while len(output_str) < length:
str_copy = output_str
str_copy = str_copy[::-1]
part2 = ''
for letter in str_copy:
if letter == '0':
part2 += '1'
else:
part2 += '0'
output_str = output_str + '0' + part2
return output_str[:length]
def checksum(starting_string):
if len(starting_string) % 2 == 1:
return starting_string
else:
new_string = ''
for letter in range(0, len(starting_string), 2):
if starting_string[letter] == starting_string[letter + 1]:
new_string += '1'
else:
new_string += '0'
return(checksum(new_string))
fake_data = generate_data('10000', 20)
print(checksum(fake_data))
fake_data = generate_data(('10011111011011001'), 272)
print(checksum(fake_data))
fake_data = generate_data(('10011111011011001'), 35651584)
print(checksum(fake_data)) |
00d9b372291e905fbb79c8041365c4bb098a61cd | TanmoySG/Coding-Practice | /Data-Structures/Linked-Lists/Insert-a-Node-at-the-Tail-of-a-Linked-List.py | 477 | 3.59375 | 4 |
# Complete the insertNodeAtTail function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def insertNodeAtTail(head, data):
newNode = SinglyLinkedListNode(data)
newNode.next = None
if head is None:
head = newNode
return head
curr = head
while curr:
if curr.next is None:
curr.next = newNode
return head
else:
curr = curr.next
|
6367a0771961100e1b30be256990fe734380f819 | mbomben/python_scripts | /extract-2D.py | 3,315 | 3.546875 | 4 | import argparse
import sys
import os.path
import re
# argument parser
def argumentParser(arguments):
parser = argparse.ArgumentParser()
parser.add_argument("--template",help="set template file",required=True)
parser.add_argument("--set",help="set file name",required=True)
parser.add_argument("--TwoDname",help="2d map output file name",required=True)
parser.add_argument("--ThreeDname",help="3d map input file name",required=True)
parser.add_argument("--zmin",help="zmin",type=int,required=True)
parser.add_argument("--zmax",help="zmax",type=int,required=True)
args = parser.parse_args(arguments)
return args
if (__name__ == "__main__" ):
args = argumentParser(sys.argv[1:])
#print(args.TwoDname)
# we now write a series of cut files, one per z value between zmin and zmax
# the program will also print out a series of commands for tonyplot3d to extract the 2d maps
# getting the arguments into variables
# set template file
templateFileName = args.template
#print(templateFileName)
# set file base name
baseSetFileName = args.set
#print(baseSetFileName)
# 2D map name
map2Dname = args.TwoDname
# 3D map name
map3Dname = args.ThreeDname
# zmin
zmin = args.zmin
#print(zmin)
# zmax
zmax = args.zmax
#print(zmax)
# auxiliary variables for ELEV calculation
ymin = -1
ymax = +1
# preparing the different components of the filenames to be handled
(dirName, fileName) = os.path.split(templateFileName)
(fileBaseName, fileExtension)=os.path.splitext(fileName)
#print (dirName)
#print (fileName)
#print (fileBaseName)
#print (fileExtension)
# keywords to be searched in the set template file
pointHeader = "point_"
ELEVHeader = "ELEV"
# open set template file for reading
with open(templateFileName) as fin:
inputLines = fin.readlines()
#print(inputLines)
# printing the command used to run the program
print("#File produced using the following command:")
print(("#python %s %s") % (sys.argv[0],(' '.join(f'--{k} {v}' for k, v in vars(args).items()))))
# loop over all the z values to write out all the cut files and print the commands to run
# the projections to planes at fixed z value
for z in range(zmin,zmax+1):
#print(z)
# set output file name
setFileName = baseSetFileName + str(z) + fileExtension
#print(setFileName)
# open the set file in write mode
with open(setFileName,'w') as fout:
# read each line of the set template file
for inputLine in inputLines:
# look for keywords:
# first is point_ header
if (re.search(pointHeader,inputLine)):
#print(("%s found in %s") % (pointHeader,inputLine))
# write the point_ position with the z coordinate
fout.write(("%s %d\n") % (inputLine.rstrip(),z))
# second is the ELEV header
elif(re.search(ELEVHeader,inputLine)):
#print(("%s found in %s") % (ELEVHeader,inputLine))
y = (ymax-ymin)*(z-zmin)/(zmax-zmin) + ymin
fout.write(("%s %f\n") % (inputLine.rstrip(),y))
# all other kid of lines - i.e. containing no keywords - will be just copied
else:
fout.write(inputLine)
print(("tonyplot3d -nohw %s -set %s -cut %s%d.str") % (map3Dname,setFileName,map2Dname,z))
|
cf73c9004e1a7ad2b3ff606652d529a3e6404b51 | liu666197/data1 | /8.17/09 对象的嵌套.py | 1,381 | 3.796875 | 4 | # 6.模拟英雄联盟中的游戏人物的类:
# 要求:
# a.创建Role(角色)类,有name,ad(攻击力),hp(血量)三个属性
# b.创建Arms(武器)类,有name,ad(攻击力),两个属性
# c.创建一个attack方法,此方法是实例化的两个对象,互相用武器攻击的功能
# 例:
# 实例化一个Role对象,名字为盖伦,ad为10,hp为100
# 实例化另一Role个对象,名字为亚索,ad为20,hp为80
# 实例化一个Arms对象,名字为无尽之刃,ad为40
#
# attack方法要完成: '谁拿什么武器攻击谁,谁掉了多少血,还剩多少血的提示功能'
class Role:
def __init__(self,name,ad,hp):
self.name = name
self.ad = ad
self.hp = hp
def attack(self,a,b):
# a: 被攻击的角色
# b: 武器对象
# 掉血: 本身的攻击力 + 武器的攻击力
a.hp -= (self.ad + b.ad)
print('%s拿%s攻击%s,%s掉了%s血,还剩%s血...'%(self.name,b.name,a.name,a.name,self.ad + b.ad,a.hp))
# 剩余血量
# a.hp -= self.ad
# print('{}攻击了{},{}掉了{}的血,还剩下{}血!!'.format(self.name,a.name,a.name,self.ad,a.hp))
class Arms:
def __init__(self,name,ad):
self.name = name
self.ad = ad
gailun = Role('盖伦',10,100)
yasuo = Role('亚索',20,80)
wuqi = Arms('无尽之刃',40)
gailun.attack(yasuo,wuqi)
|
b691c8e706c578e32a1993a42c830aa3aa2ae777 | rachelpdoherty/Casimir-programming | /script.py | 443 | 3.578125 | 4 | import test
r=5
print("circumference =", test.circumference(r))
print("area =", test.area(r))
print("It worked!")
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r')
fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()
ax.add_artist(circle1)
fig.savefig('circle.png') |
8f1f50460af4665e8786cecb919e9fe0605d12db | cmalaga0605/Open-Kattis---Python | /Pot/Pot.py | 794 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
import sys #imported the sys library to exit the program when need be
n = int(input())
if n < 1 or n >10: #included my constraints
sys.exit()
addlist = [] #created a list
while n != 0:
p = int(input())
if p < 10 or p > 9999: #included my constraints
sys.exit()
s = p%10 #took the modulo of p that will give me the last digit of the int and assigned a variable
p=str(p) #made the int input into a string in order to take the last digit off
p=p[:-1] #Took of the last digit from the string
p=int(p) #Made the string into an integer again
p=p**s #Squared the int p
addlist.append(p) # Appended it to a list
n -= 1
r = sum(addlist) #Added all of the content on the list
print(r)
# In[ ]:
|
2a452804b70b0da9f9f55abf989ea185585d0ac8 | denisfelipedev/PythonMundo1 | /desafio008.py | 345 | 4.21875 | 4 | #Escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros.
#=======================================================
m = float(input('Digite o valor em metros a ser convertido: '))
print('Medida em metros: {}m\nO valor em centimetros é {:.2f}cm \nO valor em milimetros {}mm'.format(m, m*100, m*1000)) |
27c3d0d4f6ec5a6773268767a8b33dac0e65ff4f | lguilh3rme/cursoPython | /D18.py | 196 | 3.671875 | 4 | import math
an = int(input('Digite o angulo: '))
s = math.sin(an)
c = math.cos(an)
t = math.tan(an)
print('O seno de {} é {:.2f}; o cosseno é {:.2f}; a tangente é {:.2f}'.format(an, s, c, t))
|
e88c49c87c0b640632c40551d8b9057a12492484 | ismailk97/ImageRecognition | /untitled/test.py | 796 | 3.6875 | 4 |
#face recongition system to detect faces on image.
import cv2
#endre bildet til det du ønsker...
img = cv2.imread("C:/Users/Ismail/PycharmProjects/untitled/Image/face.jpeg")
#resize vis det trengs
img= cv2.resize(img, (800, 600))
#får bilde til grå farge
grayimg= cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#algorithm to find the face
face_classifier = cv2.CascadeClassifier("image-recognition/haarcascade_frontalface_default.xml")
#detect the face on image
faces = face_classifier.detectMultiScale(grayimg, scaleFactor=1.3, minNeighbors=5)
#gir deg bare digits som er koordinater i bildet.
print(faces)
#for løkke for verdiene tallene er rgb farge rød
for(x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow("face Detected", img)
cv2.waitKey(0)
|
fc2bec7a29c5801b54d78874107132daaccb8030 | sondrewr/dk_A3_chat | /Warmup-Python/simple_tcp_server.py | 1,234 | 3.953125 | 4 | # A Simple TCP server, used as a warm-up exercise for assignment A3
from socket import *
def run_server():
# TODO - implement the logic of the server, according to the protocol.
# Take a look at the tutorial to understand the basic blocks: creating a listening socket,
# accepting the next client connection, sending and receiving messages and closing the connection
print("Starting TCP server...")
welcome_socket = socket(AF_INET, SOCK_STREAM)
welcome_socket.bind(("",1301))
welcome_socket.listen(1)
print("Server ready for client connections")
need_to_run = True
client_id = 1
message = ""
while need_to_run:
connection_socket, client_adress = welcome_socket.accept()
print("Client #%i connected" % client_id)
message = connection_socket.recv(1024).decode()
print("Client #%i: " % client_id, message)
message_content = []
while i < len(message):
message_content.append(i)
i++
response = eval(message)
connection_socket.send(str(response).encode())
welcome_socket.close()
print("Server shutting down")
# Main entrypoint of the script
if __name__ == '__main__':
run_server()
|
f472accd3358aedede1e4dd200668465aad2cbda | Charl86/Maze-Generator | /mazeGenerator/maze/cell.py | 5,024 | 3.734375 | 4 | import random
import math
import pygame
from mazeGenerator.maze.wall import Wall
# Cell class
class Cell:
# Takes 3 arguments: x and y coordinates in 2D-grid and size (width and height).
def __init__(self, x, y, mSettings, **kwargs):
self.x = x
self.y = y
self.size = mSettings.size
self.mSettings = mSettings
self.thickness = 5 # Wall thickness.
self.visited = False # If a cell has been visited.
# The coordinates on the display window, not the 2D-grid.
self.spaced_out_x = self.size * self.x + self.mSettings.borderCoords
self.spaced_out_y = self.size * self.y + self.mSettings.borderCoords
self.trailCellC = (0, 150, 255) # Trail color.
self.currCellC = (255, 0, 255) # Current cell color.
self.backtC = (255, 255, 0) # Backtracking color.
for key in kwargs:
if key in self.__dict__:
self.__dict__[key] = kwargs[key]
# Walls initialization:
self.walls = {
"top": Wall(
(self.spaced_out_x, self.spaced_out_y),
(self.spaced_out_x + self.size, self.spaced_out_y),
self.mSettings, **kwargs),
"right": Wall(
(self.spaced_out_x + self.size, self.spaced_out_y),
(self.spaced_out_x + self.size, self.spaced_out_y + self.size),
self.mSettings, **kwargs),
"bot": Wall(
(self.spaced_out_x + self.size, self.spaced_out_y + self.size),
(self.spaced_out_x, self.spaced_out_y + self.size),
self.mSettings, **kwargs),
"left": Wall(
(self.spaced_out_x, self.spaced_out_y + self.size),
(self.spaced_out_x, self.spaced_out_y),
self.mSettings, **kwargs)
}
# Draw cell walls
def show(self):
self.walls["top"].show(self.thickness)
self.walls["right"].show(self.thickness)
self.walls["bot"].show(self.thickness)
self.walls["left"].show(self.thickness)
# Remove walls between self and other
def remove_walls_with(self, other):
# Take the difference between self.x, other.x and self.y, other.y.
x_difference, y_difference = self.x - other.x, self.y - other.y
if x_difference == 1: # If other is to the right of self, remove corresponding walls.
self.walls["left"].on = False
other.walls["right"].on = False
elif x_difference == -1: # If other is to the left of self, remove walls.
self.walls["right"].on = False
other.walls["left"].on = False
if y_difference == 1: # If other is above self, remove corresponding walls.
self.walls["top"].on = False
other.walls["bot"].on = False
elif y_difference == -1: # If other is bellow self, remove walls.
self.walls["bot"].on = False
other.walls["top"].on = False
# Determine if self has unvisited neighbors
def unvisitedNeigh(self, neighborhood):
if any([not neighbor.visited for neighbor in self.neighbors(neighborhood)]):
return True
else:
return False
# Choose a random unvisited neighbor of self from the neighborhood (the 2D-grid)
def getUnvNeigh(self, neighborhood):
return random.choice([uv for uv in self.neighbors(neighborhood) if not uv.visited])
# Get all neighbors
def neighbors(self, neighborhood):
possibleNeighbors = []
for i in range(4):
# Get cardinal points centered at (self.x, self.y), in order to get
# neighbors' coordinates.
newX = round(math.cos(math.radians(90) * i) + self.x)
newY = round(-math.sin(math.radians(90) * i) + self.y)
if 0 <= newX < neighborhood.width and 0 <= newY < neighborhood.height:
possibleNeighbors.append(neighborhood[newY][newX])
return possibleNeighbors
# Highlight self based on parameters
def highlight(self, currentCell=False, backtracking=False):
if self != currentCell and self.visited: # If self is not current cell and was visited
pygame.gfxdraw.box(
self.mSettings.PyGv.SCREEN, self.rectangle, self.trailCellC
)
elif self == currentCell: # If cell is current cell
if not backtracking: # If generator is not bactracking
pygame.gfxdraw.box(
self.mSettings.PyGv.SCREEN, self.rectangle, self.currCellC
)
else:
pygame.gfxdraw.box(
self.mSettings.PyGv.SCREEN, self.rectangle, self.backtC
)
@property # Highlight area.
def rectangle(self):
return pygame.Rect(self.spaced_out_x, self.spaced_out_y, self.size, self.size)
|
2b5f48018740a9a211008072f8050dae3c307671 | roland-stefani/web_scraping_with_python | /reading_and_writing_natural_languages_chapter_8/summarizing_data/main.py | 3,410 | 3.5 | 4 | import re
import string
import requests
from pprint import pprint
_BASE_URL = 'http://pythonscraping.com/files/inaugurationSpeech.txt'
def is_common(ngram):
common_words = [
"the", "be", "and", "of", "a", "in", "to", "have", "it",
"i", "that", "for", "you", "he", "with", "on", "do", "say", "this",
"they", "is", "an", "at", "but", "we", "his", "from", "that", "not",
"by", "she", "or", "as", "what", "go", "their", "can", "who", "get",
"if", "would", "her", "all", "my", "make", "about", "know", "will",
"as", "up", "one", "time", "has", "been", "there", "year", "so",
"think", "when", "which", "them", "some", "me", "people", "take",
"out", "into", "just", "see", "him", "your", "come", "could", "now",
"than", "like", "other", "how", "then", "its", "our", "two", "more",
"these", "want", "way", "look", "first", "also", "new", "because",
"day", "more", "use", "no", "man", "find", "here", "thing", "give",
"many", "well"
]
for word in ngram:
if word in common_words:
return True
return False
def clean_input(data_input):
data_input = re.sub('\n+', ' ', data_input).lower()
data_input = re.sub('\[[0-9]*\]', '', data_input)
data_input = re.sub('\s+', ' ', data_input)
data_input = bytes(data_input, 'UTF-8')
data_input = data_input.decode('ascii', 'ignore')
clean_input_list = list()
data_input = data_input.split(' ')
for item in data_input:
item = item.strip(string.punctuation)
if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):
clean_input_list.append(item)
return clean_input_list
def ngrams(data_input, n):
data_input = clean_input(data_input)
output = dict()
for i in range(len(data_input) - n + 1):
ngram_temp = data_input[i:i+n]
if not is_common(ngram_temp):
ngram_temp = ' '.join(ngram_temp)
if ngram_temp not in output:
output[ngram_temp] = 0
output[ngram_temp] += 1
output = [{'ngram': key, 'frequency': value} for key, value in output.items()]
return output
def get_text_summary(sorted_ngrams, original_text):
summary_sentences = list()
text_sentences = re.split('\.|\!|\?', original_text)
for ngram in sorted_ngrams:
index = 0
while len(text_sentences) > 0:
if ngram in text_sentences[index].lower():
sentence = text_sentences[index].strip()
text_sentences.pop(index)
# print(sentence)
print()
sentence = re.match('('+ sentence +'\s*[\\\.\\\!\\\?])', original_text)
if sentence:
print(sentence.groups()[0])
print()
break
else:
index += 1
return '\n\n'.join(summary_sentences)
def main():
content = requests.get(_BASE_URL).text
ngram_list = ngrams(content, 2)
sorted_n_grams = sorted(ngram_list, key=lambda x: x['frequency'], reverse=True)
print(len(sorted_n_grams))
print()
pprint(sorted_n_grams[:50])
print()
print()
print()
summary_n_grams = [ngram['ngram'] for ngram in sorted_n_grams[:5]]
summary = get_text_summary(summary_n_grams, content)
print(summary)
if __name__ == '__main__':
main()
|
9322d24665737b9d40790abc60cdf1ff84bef988 | Aasthaengg/IBMdataset | /Python_codes/p03105/s576372903.py | 136 | 3.515625 | 4 | line = input()
numbers = [int(n) for n in line.split()]
predicted_value = min(numbers[1]//numbers[0], numbers[2])
print(predicted_value) |
843aa2e9f6c9a297273d6763f6241e58f9c64a7c | nazaninsbr/Graph | /NetworkX/visualization.py | 486 | 3.5625 | 4 | import matplotlib.pyplot as plt
import networkx as nx
def draw_graph(graph):
G = nx.Graph()
for edge in graph:
G.add_edge(edge[0], edge[1])
graph_pos = nx.shell_layout(G)
nx.draw_networkx_nodes(G, graph_pos, node_size=1000, node_color='blue', alpha=0.3)
nx.draw_networkx_edges(G, graph_pos)
nx.draw_networkx_labels(G, graph_pos, font_size=12, font_family='sans-serif')
plt.show()
graph = [(20, 21), (21, 22), (22, 23), (23, 24), (24, 25), (25, 20)]
draw_graph(graph) |
9a86e4e68c25dc217f81145759359d70ba42413e | ArthurPalatov/homework | /1.py | 95 | 3.6875 | 4 | n = int(input())
if (-15<n<12) or (14<n<17) or (n>19):
print (True)
else:
print(False)
|
c38514a69ec439a247e99aafd5e3c66fa375c6f3 | osmarsalesjr/AtividadesProfFabioGomesEmPython3 | /Atividades6/At6Q12.py | 520 | 3.671875 | 4 |
def main():
nome = input("Nome Completo: ")
for i in range(len(nome)):
if nome[0: i].count(" ") == 1:
primeiro_nome = nome[0 : i - 1]
nome_auxliar = nome[i + 1: len(nome)]
break
for i in range(len(nome)):
if nome_auxliar[0 : i].count(" ") == nome_auxliar.count(" "):
ultimo_nome = nome_auxliar[i : len(nome_auxliar)]
break
print("Passageiro: %s / %s." % (ultimo_nome, primeiro_nome))
if __name__ == '__main__':
main() |
365b8eb86f6ec4e422ac2867d6cffc58811f0212 | pspencil/cpy5python | /practical02/q08_top2_scores.py | 639 | 4.1875 | 4 | #Filename:q08_top2_scores.py
#Author:PS
#Created:201302901
#Description:To find the student with the highest and second highest score
num=int(input("Enter the No. of students: "))
topname=""
topscore=0
top2name=""
top2score=0
for i in range (1,num+1):
name=input("Please Enter the name of student {}: ".format(i))
score=float(input("Please Enter the score of student {}: ".format(i)))
if(score>topscore):
topscore=score
topname=name
elif(score>top2score):
top2score=score
top2name=name
print("{0} has the highest score: {1}".format(topname,topscore))
print("{0} has the second highest score: {1}".format(top2name,top2score))
|
702b6b703d1783b9287636fc426157de589025c3 | Nikolov-A/SoftUni | /PythonBasics/Exam-Exercises/Exam Preparation/E_Fan_shop.py | 573 | 3.8125 | 4 | budget = int(input())
n = int(input())
total = 0
product_counter = 0
for i in range(n):
product = input()
product_counter += 1
if product == "hoodie":
total += 30
elif product == "keychain":
total += 4
elif product == "T-shirt":
total += 20
elif product == "flag":
total += 15
elif product == "sticker":
total += 1
diff = abs(budget - total)
if budget >= total:
print(f"You bought {product_counter} items and left with {diff} lv.")
else:
print(f"Not enough money, you need {diff} more lv.") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.