blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
74c72fe4465bed97996cbe5f8dd98236aad7e1be | liuluyang/mk | /py3-study/函数编程课上代码/1902/10-30/练习题.py | 408 | 3.8125 | 4 |
"""
练习题
"""
"""
第一题:
给出一个数 num 注意:给出的num大于1
生成一个列表 num_list = [1, 2, ... num, num-1, ...2, 1]
例1:
num = 9
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]
例2:
num = 2
num_list = [1, 2, 1]
"""
"""
第二题:
给出列表lst
lst = [1, 2, 3, 4, 5, 6]
生成列表lst_new,至少用两种方法
lst_new = [2, 4, 6, 8, 10, 12]
"""
|
4a258f85c506f32bf87bbdd163b39b25684566f6 | John2013/18_price_format | /format_price.py | 922 | 3.5625 | 4 | import re
import argparse
def format_price(price) -> str:
if isinstance(price, (int, float)) or (
isinstance(price, str) and re.match(r'^\d+\.?\d*$', price)
):
price = float(price)
if price.is_integer():
format_string = ',.0f'
else:
format_string = ',.2f'
return format(price, format_string).replace(',', ' ')
if __name__ == '__main__':
parser = argparse.ArgumentParser('Форматирование числа в цену')
parser.add_argument('--price', '-p', help='Входящая цена', required=True)
args = parser.parse_args()
formated_price = format_price(args.price)
if not formated_price:
raise ValueError(
'Некорректное значение, ожидалось число, дано: {}'.format(
args.price
)
)
print(format_price(args.price))
|
f5651e9c4dff34643d1cb3f975f95862f31cde06 | giovannamascarenhas/Aluguel-de-Carros | /aluguel_de_carros.py | 2,002 | 3.984375 | 4 | print('===== Bem Vindo ao Aluguél de Carros =====')
print('-'*8)
print('Cadastro')
print('-'*8)
nome = str(input('Nome Completo: '))
carro = str(input('Carro: '))
while True:
placa = str(input('Placa: '))
if len(placa) <= 5:
print('Oops! That was no valid value. Try again...')
elif len(placa) > 5:
break
dias = int(input('Quantos Dias: '))
kms = float(input('Kms Rodados: '))
preço_por_dia = dias * 60
preço_por_km = kms * 0.15
preço_a_pagar = preço_por_dia + preço_por_km
pagamento = int(input('''Formas de Pagamento:
[1]-Cartão
[2]-Dinheiro
>>> '''))
if pagamento == 1:
dividir = int(input('''De quantas vezes:
[1]- 2 vezez
[2]- 3 vezes
>>> '''))
print('=' * 15)
print('Nota Fiscal:')
print('Nome: {}'.format(nome))
print('Carro: {}'.format(carro))
print('Placa: {}'.format(placa))
print('Total de dias: {} dias'.format(dias))
print('Total de Kilometros: {}Km'.format(kms))
if dividir == 1:
divisão = preço_a_pagar / 2
print('Formas de Pagamento: CARTÃO')
print('Total a pagar: 2x de R${:.2f}'.format(divisão))
print('Valor Final: R${:.2f}'.format(preço_a_pagar))
elif dividir == 2:
divisão = preço_a_pagar / 3
print('Formas de Pagamento: CARTÃO')
print('Total a pagar: 3x de R${:.2f}'.format(divisão))
print('Valor Final: R${:.2f}'.format(preço_a_pagar))
elif pagamento == 2:
preço_a_pagar
print('=' * 15)
print('Nota Fiscal:')
print('Nome: {}'.format(nome))
print('Carro: {}'.format(carro))
print('Placa: {}'.format(placa))
print('Total de dias: {} dias'.format(dias))
print('Total de Kilometros: {}Km'.format(kms))
print('Formas de Pagamento: DINHEIRO')
print('Total a pagar: R${:.2f}'.format(preço_a_pagar))
print('Valor Final: R${:.2f}'.format(preço_a_pagar))
print('='*15)
|
20cb7e13ef420ec24796e9d576680b5ee229c8a9 | MnAkash/Python-programming-exercises | /My solutions/Q18.py | 1,442 | 4.34375 | 4 | '''
Quesation:
A website requires the users to input username and password to register. Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1
'''
output=[]
Input=input('Enter passwords separated with comma\n')
Input=Input.split(",")
print('Usable passwords are:')
for i in range(len(Input)):
alpha_lower=0
alpha_upper=0
numeric=0
special=0
for j in Input[i]:
if j.isalpha():
if(j.islower()):
alpha_lower +=1
else:
alpha_upper +=1
elif j.isnumeric():
numeric +=1
elif j=='$' or j=='#' or j=='@':
special +=1
else:
pass
if alpha_upper>0 and alpha_lower>0 and numeric>0 and special>0 and (5<len(Input[i])<13):
#print(Input[i],end=',')
output.append(Input[i])
print(','.join(k for k in output)) |
85d3d770290c89d6961b376b22ec80e0a133095b | ChaofeiLiu/D.S | /DS_sort_set/binarysearch.py | 1,015 | 3.84375 | 4 | #!/usr/bin/env/ python
# -*— coding=utf-8 -*-
# @FileName :binarysearch.py
# @Time :2020/8/16
# @Author: chaofei_liu
# 普通实现
def binarysearch(alist,item):
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
midpoint = (first+last) // 2
if alist[midpoint] == item:
found = True
else:
if alist[midpoint] > item:
last = midpoint - 1
else:
first = midpoint + 1
return found
# 递归写法
def binarysearch2(alist,item):
if len(alist) == 0:
return False
else:
midpoint = len(alist) // 2
if alist[midpoint] == item:
return True
else:
if alist[midpoint] < item:
return binarysearch2(alist[midpoint+1:],item)
else:
return binarysearch2(alist[:midpoint],item)
inputlist = [1,2,3,5,6,8,9]
print(binarysearch(inputlist,11))
print(binarysearch2(inputlist,10))
|
fb8c52460fc9f97caae8af147bdcd00f328aa0d5 | ethanjdiamond/SnakeSolver | /point_tests.py | 837 | 3.59375 | 4 | from classes.point import Point
from classes.direction import Direction
from copy import deepcopy
# shifted works
point = Point(1, 1, 1)
point.shift(Direction.right)
assert point == Point(2, 1, 1)
point = Point(1, 1, 1)
point.shift(Direction.left)
assert point == Point(0, 1, 1)
point = Point(1, 1, 1)
point.shift(Direction.up)
assert point == Point(1, 2, 1)
point = Point(1, 1, 1)
point.shift(Direction.down)
assert point == Point(1, 0, 1)
point = Point(1, 1, 1)
point.shift(Direction.away)
assert point == Point(1, 1, 2)
point = Point(1, 1, 1)
point.shift(Direction.toward)
assert point == Point(1, 1, 0)
# copy works
point_a = Point(1, 1, 1)
point_b = deepcopy(point_a)
point_b.x = 2
assert(point_a == Point(1, 1, 1))
point_a = Point(1, 1, 1)
point_b = point_a
point_b.x = 2
assert(point_a == Point(2, 1, 1))
print("SUCCESS") |
c821bb997d44cf1a3ba08745da7136e2ad388d50 | Jay-Patil1/Coding | /Code With Harry/Python Tuts/tut9 (Lists and List Functions).py | 2,059 | 4.5 | 4 | # LISTS AND LIST FUNCTIONS
# List is simply a list.
grocery = ["Harpic", "Vim", "Deoderant","Bhindi"] # Mixed list. with both integer and string.
print(grocery) # Prints the list.
print(grocery[1]) # List item No. [] is printed.*List item No. starts form 0.
numbers = [2,3,4,6,10,15]
print(numbers) # Prints the list.
print(numbers[2]) # Prints List item No. [].
numbers.sort() # Arranges the list in ascending order.
numbers.reverse() # Arranges the list in descending order.
print(numbers[0:4]) # Prints whole list.
print(numbers[0:]) # Prints whole list. Last index is considered.
print(numbers[:5]) # Initial index is considered 0.
print(numbers[:]) # Prints whole list.
# Sort and Reverse like functions change the original list.
# Others like print([]),etc. dont change the original list.
# EXTENDED SLICCE
print(numbers[::]) # Prints whole list.
print(numbers[:4:]) # Default extended slice is 1. # default first slice is 0.
print(numbers[0:4:2]) # Prints Skipping 2 indices.
print(numbers[0::-1]) # As extended slice is -ve the list gets reversed. # Default value of second slice is maximum No. of list items.
print(len(numbers)) # Prints No. of list items.
print(max(grocery)) # Prints maximum value fromt the list items.
print(min(grocery)) # Prints minimum value from list items.
numbers.append(12) # Adds the value () as list item to the list.
# No. of appendages are unlimited.
numbers = [] # Creates Empty list.
numbers.insert(1, 67) # Insetrs the value after, after the list index No. before ,.
numbers.remove(9) # Removes the value() form the list.
numbers.pop() # Removes the last list item.
numbers[1] = 23 # Changes list index No. [] to the value.
# TUPLE.immutable (cannot be chanced.)
tp = (1, 2, 3) # Creates Tuple.
tp1 =(1, ) # Insert comma to make it a tuple.
# SWAPPING VALUES
a = 1
b = 8
temp = a
a = b
b = temp
print(a,b)
# OR
A = 2
B = 4
A, B = B, A
print(A,B)
# Learn Python list functions fron google.
|
b659b249da52899179ce47a623276f1893830c7b | Rksseth/Python-Games | /president.py | 7,647 | 3.859375 | 4 | '''
Ravi Seth
May 26
President Card Game
'''
import random
class Card(object):
def __init__(self,val,suit):
self.val = val
self.suit = suit
self.isRed = 0
self.nextC = 0
class Player(object):
def __init__(self,name0):
self.cards = 0
self.name = name0
self.nextP = 0
class Game(object):
def __init__(self):
self.players = 0
self.sizeP = 0
self.order = [3,4,5,6,7,8,9,10,11,12,13,1,2]
self.suits = ['spades','hearts','clubs','diamonds']
self.deck = 0
self.numCardsPlayed = 0
self.cardsSelected = []
self.winners = []
def print(self):
p = self.players
while p:
print(p.name)
c = p.cards
while c:
print((c.val,c.suit),end=" ")
c = c.nextC
print()
p = p.nextP
return 1
def shuffleAndDeal(self):
cards = []
for num in self.order:
for suit in self.suits:
cards.append(Card(num,suit))
numCardsPerPlayer = int(len(cards) / self.sizeP)
extraCards = len(cards) % self.sizeP
player = self.players
while cards:
card = random.choice(cards)
cards.remove(card)
self.insertCard(player,card)
player = player.nextP
if not player:
player = self.players
return 1
def insertPlayer(self,player):
if not self.players:
self.players = player
self.sizeP += 1
return 1
temp = self.players
while temp.nextP:
temp = temp.nextP
temp.nextP = player
self.sizeP += 1
return 1
def searchPlayer(self,player):
temp = self.players
while temp:
if temp.name == player.name:
return temp
temp = temp.nextP
return 0
def removePlayer(self,player):
if not self.searchPlayer(player):
return 0
if self.players.name == player.name:
self.players = self.players.nextP
self.sizeP -= 1
return 1
temp = self.players
while not (temp.nextP.name == player.name):
temp = temp.nextP
temp.nextP = temp.nextP.nextP
self.sizeP -= 1
return 1
def insertCard(self,player,card):
c = player.cards
if not c:
player.cards = card
return 1
while c.nextC:
c = c.nextC
c.nextC = card
return 1
def searchCard(self,player,card):
temp = player.cards
while temp:
if temp.val == card.val and temp.suit == card.suit:
return temp
temp = temp.nextC
return 0
def removeCard(self,player,card):
if not self.searchCard(player,card):
return 0
if player.cards.val == card.val and player.cards.suit == card.suit:
player.cards = player.cards.nextC
return 1
temp = player.cards
while not (temp.nextC.val == card.val and temp.nextC.suit == card.suit):
temp = temp.nextC
temp.nextC = temp.nextC.nextC
return 1
def getVal(self):
val = input("Val : ")
try:
val = int(val)
if val in self.order:
return val
print("NO SUCH VAL")
return -1
except:
print("NOT AN INT")
return -1
def getSuit(self):
suit = input("Suit : ")
if suit in self.suits:
return suit
print("NO SUCH SUIT")
return 0
def getDone(self):
done = input("Done Selecting (Y or N) : ")
done = done.upper()
if done == 'Y':
return 1
return 0
def inputSelectCards(self):
val = self.getVal()
if not(val > 0):
return 0
suit = self.getSuit()
if not suit:
return 0
self.selectCards(val,suit)
return 1
def selectCards(self,val,suit):
card = self.searchCard(self.players,Card(val,suit))
if not card:
return 0
if card in self.cardsSelected:
self.cardsSelected.remove(card)
else:
self.cardsSelected.append(card)
if self.getDone():
#PLACE SELECTED CARDS ON DECK
#self.placeCards()
print(self.cardsSelected)
return 1
return 1
def placeCards(self):
#PLACE SELECTED CARDS ON DECK ONLY IF VALID
if self.validCardAmount() and self.validCardSet() and self.validToPlace():
self.insertToDeck()
return 1
return 0
def validCardAmount(self):
#MAKE SURE NUM CARDS TO BE PLACE FOLLOW PATTERN
if not self.numCardsPlayed:
return 1
elif self.numCardsPlayed == len(self.cardsSelected):
return 1
return 0
def validCardSet(self):
#MAKE SURE THE CARDS SELECTED CAN BE PLAYED TOGETHER
if len(self.cardsSelected) == 1:
return 1
val = -1
for item in self.cardsSelected:
if val == -1:
val = item.val
elif not (val == item.val):
return 0
return 1
def validToPlace(self):
#MAKE SURE CARDS SELECTED CAN BE PLACE ON DECK
lastCardVal = self.deck.val
newVal = self.selectedCards[0]
validMove = False
for val in self.order:
if val == lastCardVal:
validMove = True
if validMove and newVal == val:
return 1
return 0
def insertToDeck(self):
#REMOVE SELECTED CARDS FROM PLAYERS DECK
for card in self.selectedCards:
self.removeCard(self.players,card)
for cardIdx in range(0,len(self.selectedCards)-1):
self.selectedCards[cardIdx].nextC = self.selectedCard[cardIdx + 1]
#BURN
if self.deck:
if self.deck.val == self.selectedCards[0].val:
self.deck = 0
self.selectedCards = []
if self.players.cards == 0:
self.winners.append(self.player)
self.removePlayer(self.player)
return 1
#NOT A BURN
if self.deck == 0:
self.deck = self.selectedCards[0]
else:
self.deck.nextC = self.selectedCards[0]
if self.players.cards == 0:
self.winners.append(self.player)
self.removePlayer(self.player)
return 1
def changeTurn(self):
self.insertPlayer(self.players)
self.removePlayer(self.players)
return 1
p = Game()
p1 = Player('Ravi')
p2 = Player('Boi')
p3 = Player('Savage')
p.insertPlayer(p1)
p.insertPlayer(p2)
p.insertPlayer(p3)
p.insertCard(p1,Card(12,'spades'))
p.insertCard(p1,Card(1,'diamonds'))
p.shuffleAndDeal()
p.print()
|
4deeee5cf1969df8d979b1bd15a3812a45efe268 | Chekoo/Core-Python-Programming | /11/11-6.py | 509 | 3.78125 | 4 | #coding=utf-8
def printf(rule, *num):
i = -1
for j in num:
i = rule.find('%', i+1) #对%定位,分三种情况讨论并进行替换
if rule[i + 1] == 'd' and type(j) == int:
result = rule.replace('%d', str(j), 1)
elif rule[i + 1] == 'f' and type(j) == float:
result = rule.replace('%f', str(j), 1)
elif rule[i + 1] == 's' and type(j) == str:
result = rule.replace('%s', j , 1)
else:
print 'ERROR' #当对应类型不正确时抛出异常
exit(0)
rule = result
print result |
8032e3390ba9280f713908231bd533f3ee7d872a | jahirulislammolla/CodeFights | /Fights/mergeArrays.py | 389 | 3.625 | 4 | def mergeArrays(a, b):
result = []
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
while i < len(a):
result.append(a[i])
i += 1
while j < len(b):
result.append(b[j])
j += 1
return result
|
a489dceb9a4f8f5b1fe8d49711b1f45ddb81b51d | jshams/spd-2.4 | /recursion/fizz_buzz.py | 657 | 3.875 | 4 | def recursive_fizz_buzz(start, end):
if start > end:
return []
if start % 15 == 0:
result = ['FizzBuzz']
elif start % 3 == 0:
result = ['Fizz']
elif start % 5 == 0:
result = ['Buzz']
else:
result = [start]
return result + recursive_fizz_buzz(start + 1, end)
def test_fizz_buzz():
results = recursive_fizz_buzz(1, 20)
assert results == [1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7,
8, 'Fizz', 'Buzz', 11, 'Fizz', 13,
14, 'FizzBuzz', 16, 17, 'Fizz', 19,
'Buzz']
print('Fizz Buzz passes current tests')
test_fizz_buzz()
|
14da2945e6899dec4ffe362563163ff8088b2522 | V-o-y-a-g-e-r/Projects | /CalculatorApplication/main.py | 4,799 | 3.765625 | 4 | '''
Hi,
This is calculator made just for fun in tkinter to pratice this library.
It is able to calculate the result of previous calculation.
Just remeber that, user should press '=' sign after inputing the expression.
Work is in progress, so dont be surprised if there is something missing.
Cheers
~ V-o-y-a-g-e-r :)
'''
import tkinter as tk
from tkinter import ttk
from tkinter import font
class Calc():
def __init__(self):
global root
root = tk.Tk()
root.resizable(width = False, height = False)
root.title("Calculator")
root.geometry("352x296")
self.fontFigure = font.Font(family="Helvetica", size=20, weight="bold", slant = "italic")
self.style = ttk.Style()
self.style.configure("TEntry", font = self.fontFigure, padding = 10)
self.style.configure("TButton", font = self.fontFigure, padding = 10)
self.var = tk.StringVar();
self.value = ""
self.show = ""
self.entry = ttk.Entry(root, font = self.fontFigure, textvariable = self.var)
self.entry.grid(row = 0, columnspan = 4)
self.button7 = ttk.Button(root, text = 7, width = 4, command = lambda: self.button_Pressed("7"))
self.button7.grid(row = 1, column = 0)
self.button8 = ttk.Button(root, text = 8, width = 4, command = lambda: self.button_Pressed("8"))
self.button8.grid(row = 1, column = 1)
self.button9 = ttk.Button(root, text = 9, width = 4, command = lambda: self.button_Pressed(("9")))
self.button9.grid(row = 1, column = 2)
self.buttonMult = ttk.Button(root, text = "*", width = 4, command = lambda: self.set_Math("*"))
self.buttonMult.grid(row = 1, column = 3)
self.button4 = ttk.Button(root, text=4, width=4, command=lambda: self.button_Pressed("4"))
self.button4.grid(row=2, column=0)
self.button5 = ttk.Button(root, text=5, width=4, command=lambda: self.button_Pressed("5"))
self.button5.grid(row=2, column=1)
self.button6 = ttk.Button(root, text=6, width=4, command=lambda: self.button_Pressed(("6")))
self.button6.grid(row=2,column=2)
self.buttonAdd = ttk.Button(root, text="+", width=4, command=lambda: self.set_Math("+"))
self.buttonAdd.grid(row=2, column=3)
self.button1 = ttk.Button(root, text=1, width=4, command=lambda: self.button_Pressed("1"))
self.button1.grid(row=3, column=0)
self.button2 = ttk.Button(root, text=2, width=4, command=lambda: self.button_Pressed("2"))
self.button2.grid(row=3, column=1)
self.button3 = ttk.Button(root, text=3, width=4, command=lambda: self.button_Pressed(("3")))
self.button3.grid(row=3, column=2)
self.buttonSub = ttk.Button(root, text="-", width=4, command=lambda: self.set_Math("-"))
self.buttonSub.grid(row=3, column=3)
self.buttonEqual = ttk.Button(root, text ="=", width = 4, command = lambda: self.do_Math())
self.buttonEqual.grid(row = 4, column = 0)
self.buttonDiv = ttk.Button(root, text="/", width=4, command=lambda: self.set_Math("/"))
self.buttonDiv.grid(row=4, column=1)
self.buttonAC = ttk.Button(root, text="AC", width=4, command=lambda: self.set_Math("AC"))
self.buttonAC.grid(row=4, column=2)
self.button0 = ttk.Button(root, text = "0", width = 4, command = lambda: self.button_Pressed("0"))
self.button0.grid(row = 4, column = 3)
def button_Pressed(self, value_):
self.value += value_
self.show += value_
self.var.set(self.show)
def set_Math(self, sign):
self.entry.delete(0, "end")
self.sign = sign
self.value += " "
self.show = ""
if sign == "AC":
self.value = ""
self.var.set("")
return
def do_Math(self):
if self.sign == "*":
self.value.rstrip()
var1, var2= self.value.split()
result = float(var1) * float(var2)
self.var.set(str(result))
self.value = str(result)
elif self.sign == "+":
self.value.rstrip()
var1, var2= self.value.split()
result = float(var1) + float(var2)
self.var.set(str(result))
self.value = str(result)
elif self.sign == "-":
self.value.rstrip()
var1, var2= self.value.split()
result = float(var1) - float(var2)
self.var.set(str(result))
self.value = str(result)
if self.sign == "/":
self.value.rstrip()
var1, var2= self.value.split()
result = float(var1) / float(var2)
self.var.set(str(result))
self.value = str(result)
def main():
app = Calc()
root.mainloop()
main() |
7e509414c313d8b695c7a0f0a2467ed5372f8a07 | crzysab/Learn-Python-for-Beginners | /010-Operators/Operator_Assignment.py | 348 | 3.75 | 4 | # x + y
a = 2
b = 3
c = a + b
print("a + b : ",c)
# x+=y -> x = x + y
d = 4
e = 6
d += e
print("d += e : ",d)
# x-=y -> x = x - y
f = 3
g = 2
f -= g
print("f -= g : ",f)
# x*=y -> x = x*y
h = 4
i = 5
h*=i
print("h *= i : ", h)
# x/=y -> x = x/y
j = 8
k = 2
j/=k
print("j /= k : ",j)
# x**=y -> x = x**y
l = 2
m = 3
l**=m
print("l **= m : ", l) |
93d2996e9b499ce0f9e16ae24bba72ff77ca103c | meghalrag/MyPythonPgms | /MyTKinter/tkintersample.py | 1,145 | 3.921875 | 4 | from tkinter import *
from tkinter import filedialog
a = Tk()
a.geometry('{}x{}'.format(500,500)) #setsize of window
a.title("GUI")
# label = Label(a, text = "welcome").place(x=100,y=10)
# label = Label(a, text = "hai").place(x=200,y=30)
# label = Message(a, text = "welcome").pack()
# h=Message(a,bd=10,text='hai',)
# h.grid(row=0,column=1)
#
# v=StringVar() #variable to display in label
# v.set('name')
# b=Label(a,width=10,height=3,bg='red',textvariable=v).pack(side="bottom",fill="x")
######grid arrangement
v=StringVar() #variable to display in label
v.set('name:')
b=Label(a,textvariable=v)
b.grid(row=0)
tv=IntVar()
tv.set('123')
b=Entry(a,textvariable=tv,state='disabled').grid(row=0,column=1)
v=StringVar() #variable to display in label
v.set('age:')
b=Label(a,textvariable=v).grid(row=1)
tv=IntVar()
b=Entry(a,textvariable=tv)
b.focus()
b.grid(row=1,column=1)
bb=Button(a,text='browse',command=lambda :filedialog.askopenfilename())
bb.grid(row=2)
######################
# tv=IntVar()
# # b=Entry(a,width=20,bg='white',textvariable=tv)
# # b.grid(row=0,column=1)
a.mainloop() |
8cd80088eaf98ea71f996003a12e69f28229585a | TinkerMill/TinkerSpaceCommand | /system/shutdown_on_gpio.py | 932 | 3.78125 | 4 | #!/bin/python
# A simple script for phutting a Raspberry Pi down when a button is pushed.
#
#
import RPi.GPIO as GPIO
import time
import os
GPIO_SHUTDOWN = 18
# How long to wait after the off button has been pushed to decide
# the person means it. In seconds.
WAIT_TIME = 5
# Use the Broadcom SOC Pin numbers
# Setup the Pin with Internal pullups enabled and PIN in reading mode.
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_SHUTDOWN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
running = 1
while running:
# Wait for the button to be pressec.
GPIO.wait_for_edge(GPIO_SHUTDOWN, GPIO.FALLING, bouncetime = 50)
print("Button pressed")
startInterval = time.time()
# Wait for the button to be released.
GPIO.wait_for_edge(GPIO_SHUTDOWN, GPIO.RISING, bouncetime = 50)
interval = time.time() - startInterval
print("Button released at {}".format(interval))
if interval > WAIT_TIME:
running = 0
os.system("sudo shutdown -h now")
|
4966c65f47f67c31d0ef3a6074bd592b35f083f4 | ponkhi403/BD-tax-computation | /code004.py | 725 | 3.71875 | 4 | __author__ = 'LICT_2'
print("Plz Enter your Basic Salary :")
basic = int(input())
print("Plz Enter your Child :")
child = int(input())
house_rent = basic * .60
conv = basic * .10
pf = basic * .10
medical = 5000
factory = basic *.10
gross = basic + house_rent + conv - pf + medical+factory
#print (gross)
#tax computation
if gross * 12 <= 240000:
tax = 0
elif gross * 12 >= 240001:
tax = 3000
#child allowance computation
child_allowance = 0
if child == 1:
child_allowance = 2000
elif child >= 2:
child_allowance = 4000
net_salary = basic + house_rent + conv - pf + medical - tax + child_allowance+factory
print("Tax :",tax)
print ("Net Salary :",net_salary)
print ("Child Allowance :",child_allowance)
|
7970f30a394a13becc4881a4cfb93b06f45a40e9 | joshswe/leetcode | /LinkedList/[M] 19. Remove Nth Node From End of List.py | 738 | 3.5625 | 4 | class Solution:
def removeNthFromEnd(self, head, n):
if head is None:
return None
firstNode = head
secondNode = head
previousNode = None
for _ in range(n-1):
secondNode = secondNode.next
if secondNode == None:
return None
if secondNode.next is None:
head = head.next
return head
else:
while secondNode.next:
previousNode = firstNode
firstNode = firstNode.next
secondNode = secondNode.next
previousNode.next = firstNode.next
return head |
b0d787d50fee4834bd0f8c86a3d6f3ee7036a4b0 | gtanubrata/Small-Fun | /intersect.py | 1,614 | 4.21875 | 4 | # # flesh out intersection pleaseeeee
# def intersection(list1, list2):
# return [val for val in list1 if val in list2]
# # COLT'S CODE:
# # Manual Looping Solution
# # Here's one potential solution:
# # Define an empty list that will eventually store the in common values
# # Loop through one list (l1)
# # For each value, check if that value is in the other list (l2)
# # If it is, append the value to the in_common list
# # Return in_common after the loop ends
# def intersection(l1, l2):
# in_common = []
# for val in l1:
# if val in l2:
# in_common.append(val)
# return in_common
# # List Comprehension Solution
# # The first solution is perfectly valid. It's a more "traditional" way of solving the problem. A more Python-ic solution involves using a list comprehension to do the same thing on a single line. Both work just as well. It's a matter of personal preference, so don't get too caught up in it!
# def intersection(l1, l2):
# return [val for val in l1 if val in l2]
# # Sets Solution
# # This solution(submitted by Sebastian on the discussion boards) is the most efficient of the three. It converts the lists to sets, which removes duplicate values, and then finds the intersection of them using &. If you need review, watch the sets section again (it's super short).
def intersection(list1, list2):
# print(set(list1))
# print(set(list2))
return [val for val in set(list1) & set(list2)]
print(intersection([1,2,3], [2,3,4])) #[2,3]
print(intersection(['a','b','z'], ['x','y','z'])) #['z'] |
5a592b66c87fe4ef5ded160278bc0fb5e839a4ae | skaugvoll/Algorithms | /ID3_decision_tree/id3.py | 4,892 | 3.953125 | 4 | import numpy as np
import os
from Node import Node
def plurity_value(examples):
if len(examples) < 1: return "Example list is empty. No plurity value"
class_count = {} # class : number of appearances
for ex in examples:
target = ex[-1]
class_count[target] = class_count.get(target, 0) + 1
return max(class_count, key=class_count.get)
def all_same_class(examples):
target = examples[0][-1]
for ex in examples:
if ex[-1] != target:
return False
return True
'''
Entropy is how much uncertainty in the dataset (examples) S
examples - the current examples for which entropy is calculated. NOTE this changes every iteration of ID3
X = set of classes / all the different targets in current dataset (examples)
p(x) = the proportion of the number of elements in class x (target) to the number of elements in the dataset (examples)
When H(S)=0, the set S is perfectly classified (i.e. all elements in current dataset are of the same class).
In ID3, entropy is calculated for each remaining attribute.
The attribute with the smallest entropy is used to split the set S on this iteration.
The higher the entropy, the higher the potential to improve the classification here.
Entropy is also often called H(S)
H(S) = entropy(S) = sum[x in X] -p(x) * log2(p(x)) ; NOTE THE minus sign in the first led!
'''
def entropy(examples):
# find X (all the different classes \ target values in examples)
classes = {} # class : number of examples with this class
for ex in examples: # examples has only examples with the attribute set to the value we are testing
classes[ex[-1]] = classes.get(ex[-1], 0) + 1
total_number_of_examples = len(examples)
probabilities_px = [cls / total_number_of_examples for cls in classes.values()]
entropy = sum([-px * np.log2(px) for px in probabilities_px])
return entropy
def informationGain(examples, attribute):
# number of values for attribute
# going to need to find out number of different classes
# number of examples with a given attribute value belongs to each class
attribute_idx = attributes.index(attribute)
values = {}
for ex in examples:
values[ex[attribute_idx]] = values.get(ex[attribute_idx], 0) + 1
subsets = []
for value in values:
subset_after_split = []
for ex in examples:
if ex[attribute_idx] == value:
subset_after_split.append(ex)
subsets.append(subset_after_split)
sum_subsets_entropy = sum([ (len(subset) / len(examples)) * entropy(subset) for subset in subsets ])
gain = entropy(examples) - sum_subsets_entropy
return gain
def decisionTree(examples, attributes, parent_examples):
if len(examples) < 1: return plurity_value(parent_examples)
elif all_same_class(examples): return examples[-0][-1]
elif len(attributes) < 1: return plurity_value(examples)
#A <- argmax(a, Attributes)[IMPORTANCE(a,examples) : GAIN(a, examples)]
gains = [informationGain(examples, attribute) for attribute in attributes]
max_value = max(gains)
max_idx = gains.index(max_value)
attribute = attributes[max_idx] # remember this is a string, not a integer or index
#tree <- a new deccision tree with root test A
tree = Node(attribute)
# for each value of attribute A
# first find all the different attribute values
attribute_idx = attributes.index(attribute)
values = []
for ex in examples:
if ex[attribute_idx] not in values: values.append(ex[attribute_idx])
# now we can do the foreach
for value in values:
## exs_subset = e : e in examples and e.A = value
subset_after_split = []
for ex in examples:
if ex[attribute_idx] == value:
subset_after_split.append(ex)
## subtree = decisionTree(exs, attributes - A, examples)
### remove the attribute we test for in attributes for the next test
attributs_moded = attributes[:attribute_idx] + attributes[attribute_idx:]
subtree = decisionTree(subset_after_split, attributs_moded, examples)
## a a branch to tree with test (A = value) and subtree (child) = subtree
tree.add_branch(edge=value, child=subtree)
# return tree
return tree
if __name__ == "__main__":
# Preparations START
#examples = np.loadtxt("data/data_same_class.txt", dtype=str, comments="#")
examples = np.loadtxt("data/data_real.txt", dtype=str, comments="#")
attributes = ["outlook", "windy", "avalance_risk"]
print("Examples peak (head-5)\n{}".format(examples[:5]))
# Preparations END
# Run the algorithm START
decisionTree = decisionTree(examples, attributes, parent_examples=[])
# Run the algorithm END
# Print results Start
print(decisionTree)
# print results END |
16b43527ab2281d2820b9419682eeb320c2ebc4a | ntrinquier/Euler | /pb47/pb.py | 1,034 | 3.578125 | 4 | import math
# Implementing Eratosthene
def primes_below(n):
primes = [True] * (n + 1)
primes[0], primes[1] = False, False
i = 2
while i <= n:
j = i*2
while j <= n:
primes[j] = False
j += i
i += 1
while i <= n and primes[i] == False:
i += 1
result = []
for number, is_prime in enumerate(primes):
if is_prime == True:
result.append(number)
return result
def has_4_prime_factors(n, primes):
nb = 0
i = 0
m = n
for prime in primes:
if prime ** 2 > n: # There's only one prime factor left
if nb == 3:
return True
else:
return False
if m % prime == 0: # Counting another prime factor
nb += 1
if nb > 4:
return False
while m % prime == 0:
m = (m / prime)
if m == 1:
return nb == 4
def solution():
primes = primes_below(200000)
n = 644
(a, b, c, d) = (False, False, False, False)
while a == False or b == False or c == False or d == False:
n += 1
(a, b, c, d) = (b, c, d, has_4_prime_factors(n, primes))
return (n - 3)
print solution()
|
26ee150e8e182fa36e18a01cb559be83d63be8a9 | steven-halla/pythonworksheet | /reversestring.py | 133 | 3.8125 | 4 | def reverseString(string):
print( string)
reversedString = string[::-1]
print(reversedString)
reverseString("nintendo") |
f4043521b3e4d9880331a90480090f8384bdda52 | peternortonuk/reference | /python/class/class2.py | 1,338 | 4.09375 | 4 |
'''
https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python
'''
class A(object):
def foo(self,x):
print("executing foo(%s,%s)"%(self,x))
@classmethod
def class_foo(cls,x):
print("executing class_foo(%s,%s)"%(cls,x))
@staticmethod
def static_foo(x):
print("executing static_foo(%s)"%x)
a=A()
'''
classmethods:
the class of the object instance is implicitly passed as the first argument instead of self.
'''
a.class_foo(1)
A.class_foo(1)
'''
staticmethods:
neither self (the object instance) nor cls (the class) is implicitly passed as the first argument.
They behave like plain functions except that you can call them from an instance or the class:
A staticmethod isn't useless - it's a way of putting a function into a class (because it logically belongs there),
while indicating that it does not require access to the class
'''
a.static_foo(1)
A.static_foo('hi')
'''
methods:
foo is just a function, but when you call a.foo you don't just get the function, you get a "partially applied" version
of the function with the object instance a bound as the first argument to the function.
foo expects 2 arguments, while a.foo only expects 1 argument; a is bound to foo.
'''
print(a.foo)
print(a.class_foo)
print(a.static_foo) |
9d65c9e1e04307b286c22fce473b3a7172e45c08 | emmanuelepp/design-patterns-examples | /Creational-Patterns/factory.py | 602 | 4.21875 | 4 | # Factory:
# Provides an interface for creating objects in a superclass,
# but allows subclasses to alter the type of objects that will be created.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return "Woof"
class Cat:
def __init__(self, name):
self.name = name
def speak(self):
return "Meow"
#### Factory method ####
def get_animal(animal="dog"):
animals = dict(dog=Dog("Poki"), cat=Cat("Rudy"))
return animals[animal]
dog = get_animal("dog")
print(dog.speak())
cat = get_animal("cat")
print(cat.speak())
|
03b32f06015850ff1b0fc50870080a579e065797 | Morrowind1983/Python-for-Everybody-Specialization | /Chapter 05 - Iterations/exercise_05_01.py | 798 | 4.21875 | 4 | # Exercise 1: Write a program which repeatedly reads numbers until the user
# enters "done". Once "done" is entered, print out the total, count, and average
# of the numbers. If the user enters anything other than a number, detect their
# mistake using try and except and print an error message and skip to the next
# number.
#
# Enter a number: 4
# Enter a number: 5
# Enter a number: bad data
# Invalid input
# Enter a number: 7
# Enter a number: done
# 16 3 5.333333333333333
total = 0
count = 0
while True:
raw_string = input("Enter a number: ")
if raw_string == "done":
break
try:
num = int(raw_string)
except:
print("Invalid input")
continue
total = total + num
count = count + 1
average = total / count
print(total, count, average)
|
a6d267ef26138676b46af24c94e91149bcbb46ee | NoeCruzMW/zpy-flask-msc | /zpy/api/validator.py | 1,291 | 3.59375 | 4 |
from abc import abstractmethod
__author__ = "Noé Cruz | contactozurckz@gmail.com"
__copyright__ = "Copyright 2021, Small APi Project"
__credits__ = ["Noé Cruz", "Zurck'z"]
__license__ = "MIT"
__version__ = "0.0.1"
__maintainer__ = "Noé Cruz"
__email__ = "contactozurckz@gmail.com"
__status__ = "Dev"
class Validation():
field: str = None
rule: str = None
message: str = None
def __init__(self,field:str ,rule: str,error_messgae: str) -> None:
self.field = field
self.rule = rule
self.message = error_messgae
def json(self) -> dict:
try:
return vars(self)
except:
return self.__dict__
@abstractmethod
def validate(self) -> bool:
return False
if __name__ == '__main__':
validations = [
Validation(
'name',
"required",
"El nombre es requerido"
),
Validation(
'address',
"required",
"El nombre es requerido"
),
Validation(
'age',
"required|number|max:40,min:21",
"El nombre es requerido"
)
]
v = Validation(
'age',
"required|number|max:40,min:21",
"El nombre es requerido"
).json()
print(v)
|
43bd9e4306c3e31a78795005e12a57bb63e06751 | JakeBednard/CodeInterviewPractice | /7-1_MergeTwoSortedLinkedList.py | 1,311 | 4.09375 | 4 | """Merge 2 prior sorted linked list into linked list"""
class node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_linked_list(head):
temp = []
while True:
temp.append(head.value)
head = head.next
if head is None:
break
print(temp)
def merge_two_lists(l1, l2):
head = node(-1, None)
point = head
while l1 or l2:
if l1 and l2:
if l1.value <= l2.value:
point.next = node(l1.value)
point = point.next
l1 = l1.next
elif l1.value > l2.value:
point.next = node(l2.value)
point = point.next
l2 = l2.next
elif l1 and not l2:
point.next = node(l1.value)
point = point.next
l1 = l1.next
else:
point.next = node(l2.value)
point = point.next
l2 = l2.next
return head.next
# Linked List 1
list1 = node(0)
point = list1
for i in [3,5,7,9,11,13,15,17]:
point.next = node(i)
point = point.next
# Linked List 2
list2 = node(1)
point = list2
for i in [2,2,3,4,5]:
point.next = node(i)
point = point.next
list3 = merge_two_lists(list1, list2)
print_linked_list(list3)
|
ccddb4c5e1bf0bc2a715525e700b278bd0bca140 | fagan2888/leetcode_solutions | /accepted/Longest_Substring_Without_Repeating_Characters.py | 1,585 | 3.875 | 4 | ## https://leetcode.com/problems/longest-substring-without-repeating-characters/
## find the length of the longest substring in s that doesn't have any repeating
## characters.
## pretty simple brute-force solution, but it's only O(n^2) at worst, so still not
## too bad. loop over the string once, checking each character to see if it's in
## the current batch of characters we're processing. if it is, we check if that
## batch is longer than our current longest batch, then reset to drop all characters
## before and including the character that we're now adding that is a repeat.
## comes in at nearly 96th percentile in terms of speed, though only 17th in
## terms of memory because we keep a copy of the current set of characters --
## could solve it without that by keeping track of a starting and ending index
## instead
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not len(s):
return 0
max_length = 0
current_length = 1
current_string = s[0]
for ii in range(1, len(s)):
## this is our slowest step, but we still say below O(n^2)
last_index = current_string.find(s[ii])
if last_index >= 0:
## found this character in the current string -- reset from that instance on
max_length = max([len(current_string), max_length])
current_string = current_string[last_index+1:] + s[ii]
else:
current_string += s[ii]
return max([max_length, len(current_string)]) |
de154983f440a2d00ab3a831ed4ccf00783f8d76 | Turtle-Hwan/Python-class | /8강/1104 (05).py | 108 | 3.671875 | 4 | #실습 5
def square(a):
return pow(a, 2)
n = int(input("정수 입력: "))
print(square(n))
|
39c4fa099b30b4d1173ce8ff4b48c72d9ccfce68 | ieee-saocarlos/ia-2019 | /exercicios-membros/Eric/Lista2/4.py | 1,574 | 4.03125 | 4 | """
Faça um programa que pegue a lista [ 15 , 9 , -3 , 7 , 99 , -3 , 0 , -5 , 8 , 15 , -6 , -3 , 99 , 15 , 0 , 15 ]
e imprima:
*Uma lista de forma crescente (sem utilizar comandos).
*Uma lista de forma decrescente e sem números repetidos.
*Duas listas, sendo uma delas com números pares e a outra com números ímpares,
de forma crescente e sem números repetidos.
*Quantas vezes cada número aparece na lista.
"""
from collections import Counter
def sort_list(mylist):
sorted_list = []
for number in mylist:
i = 0
if not sorted_list:
sorted_list.append(number)
i = len(sorted_list)
j = 0
while len(sorted_list) > i:
if sorted_list[i] >= number:
j = 1
sorted_list.insert(i, number)
break
else:
i += 1
if j == 0:
sorted_list.append(number)
return sorted_list
def main():
my_list = [15, 9, -3, 7, 99, -3, 0, -5, 8, 15, -6, -3, 99, 15, 0, 15]
my_list_2 = list(dict.fromkeys(my_list))
sorted_list = sort_list(my_list)
list_2 = (sort_list(my_list_2))
sorted_reverse_nr = list_2[::-1]
even_list = [i for i in my_list_2 if i % 2 == 0]
sorted_even_list = sort_list(even_list)
odd_list = [j for j in my_list_2 if j % 2 == 1]
sorted_odd_list = sort_list(odd_list)
print(sorted_list)
print(sorted_reverse_nr)
print(sorted_even_list)
print(sorted_odd_list)
print(Counter(my_list).most_common(16))
if __name__ == '__main__':
main()
|
7c6ce7a7dfc71730e0ea4b314569950868fe0e3c | huanghaibin333/LeetCode | /9_palindrome_number.py | 884 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File Name: 9_palindrome_number.py
# Author: Haibin Huang
# Version: 1.0
# Create Date: 15-1-15
def bits_of_number(num):
n = 0
while num:
n += 1
num /= 10
return n
def isPalindrome(x):
if x < 0:
return False
else:
bits = 0
num = x
while num:
bits += 1
num /= 10
count = bits / 2
for i in range(count):
last = x % 10
first= x // (10**(bits - i*2 - 1))
if first != last:
return False
x = x / 10 % (10**(bits - i*2 -2))
return True
if __name__ == '__main__':
print bits_of_number(1234)
print isPalindrome(10)
print isPalindrome(121)
print isPalindrome(123321)
print isPalindrome(1236321)
print isPalindrome(1232321)
print 10 ** 2 |
fa898c9ae9e85fb9e2197a81b33f6ab541485179 | RajaaBoulassouak/02-simple-python-data | /test.py | 2,464 | 3.75 | 4 | import simple_python_data
def test_calculate_rectancle_area():
"""
Check that running your code should calculate a rectangle's area"
"""
assert simple_python_data.calculate_rectangle_area(0, 0) == 0, "Your calculate_rectangle_area func should be able to handle zero values"
assert simple_python_data.calculate_rectangle_area(5, 0) == 0, "Your calculate_rectangle_area func should be able to handle zero values"
assert simple_python_data.calculate_rectangle_area(0, 5) == 0, "Your calculate_rectangle_area func should be able to handle zero values"
assert simple_python_data.calculate_rectangle_area(5, 2) == 10, "Your calculate_rectangle_area func should be able to handle positive values"
def test_calculate_area_of_square():
"""
Check that running your code should calculate a square's area"
"""
assert simple_python_data.calculate_area_of_square(0) == 0, "Your calculate_area_of_square func should be able to handle zero values"
assert simple_python_data.calculate_area_of_square(5) == 25, "Your calculate_area_of_square func should be able to handle positive values"
def test_calculate_total_plus_tip_per_person():
"""
Check that running your code should calculate a total plus tip per person"
"""
assert simple_python_data.calculate_total_plus_tip_per_person(100, 20, 4) == 30, "Your calculate_total_plus_tip_per_person func should return correct value"
def test_fahrenheit_to_celcius():
"""
Check that running your code should calculate fahrenheit to celcius"
"""
assert simple_python_data.fahrenheit_to_celcius(32) == 0, "Your fahrenheit_to_celcius func should return correct value"
assert simple_python_data.fahrenheit_to_celcius(50) == 10, "Your fahrenheit_to_celcius func should return correct value"
def test_calculate_the_remainder():
"""
Check that running your code should return a correct remainder"
"""
assert simple_python_data.calculate_the_remainder(5, 2) == 1, "Your calculate_the_remainder func should return correct value"
assert simple_python_data.calculate_the_remainder(13, 4) == 1, "Your calculate_the_remainder func should return correct value"
assert simple_python_data.calculate_the_remainder(100, 50) == 0, "Your calculate_the_remainder func should return correct value"
assert simple_python_data.calculate_the_remainder(9, 5) == 4, "Your calculate_the_remainder func should return correct value"
|
19bffa3d6836d70fd38970ad4ed421429032a871 | emanueln/umarete | /src/names.py | 981 | 3.53125 | 4 | # Name list (40 of each)
from random import seed
from random import randint
seed(1)
boy_names = ["Noah","Liam","William","Mason","James","Benjamin","Jacob","Michael","Elijah","Ethan","Alexander","Oliver","Daniel","Lucas","Matthew","Aiden","Jackson","Logan","David","Joseph","Samuel","Henry","Owen","Sebastian","Gabriel","Carter","Jayden","John","Luke","Anthony","Isaac","Dylan","Wyatt","Andrew","Joshua","Christopher","Grayson","Jack","Julian","Ryan"]
girl_names = ["Emma","Olivia","Ava","Sophia","Isabella","Mia","Charlotte","Abigail","Emily","Harper","Amelia","Evelyn","Elizabeth","Sofia","Madison","Avery","Ella","Scarlett","Grace","Chloe","Victoria","Riley","Aria","Lily","Aubrey","Zoey","Penelope","Lillian","Addison","Layla","Natalie","Camila","Hannah","Brooklyn","Zoe","Nora","Leah","Savannah","Audrey","Claire"]
def random_boy_name():
index = randint(0, 39)
return boy_names[index]
def random_girl_name():
index = randint(0, 39)
return girl_names[index]
|
c7c2047fc9efaf472cca5bfa0925443baa46b554 | HumayraFerdous/Python_Functions_FIles_Dictionaries | /sentiment_classifier.py | 3,181 | 4.5 | 4 | # To start, define a function called strip_punctuation which takes one parameter,
# a string which represents a word, and removes characters considered punctuation from everywhere in the word.
# (Hint: remember the .replace() method for strings.)
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
def strip_punctuation(word):
for ch in punctuation_chars:
word = word.replace(ch,"")
return word
# Next, copy in your strip_punctuation function and define a function called get_pos which takes one parameter,
# a string which represents one or more sentences, and calculates how many words in the string are considered positive words.
# Use the list, positive_words to determine what words will count as positive.
# The function should return a positive integer - how many occurrences there are of positive words in the text.
# Note that all of the words in positive_words are lower cased, so you’ll need to convert all the words in the input string to lower case as well.
# list of positive words to use
positive_words = []
with open("positive_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
positive_words.append(lin.strip())
def get_pos(sentence):
counter=0
sent1 = sentence.lower()
sent2 = strip_punctuation(sent1)
sent3 = sent2.split()
for s in sent3:
for word in positive_words:
if s == word:
counter+=1
return counter
#sen = "I am better bliss benefit champ tasnu!"
#print(get_pos(sen))
# Next, copy in your strip_punctuation function and define a function called get_neg which takes one parameter,
# a string which represents one or more sentences, and calculates how many words in the string are considered negative words.
# Use the list, negative_words to determine what words will count as negative. The function should return a positive integer -
# how many occurrences there are of negative words in the text. Note that all of the words in negative_words are lower cased,
# so you’ll need to convert all the words in the input string to lower case as well.
negative_words = []
with open("negative_words.txt") as pos_f:
for lin in pos_f:
if lin[0] != ';' and lin[0] != '\n':
negative_words.append(lin.strip())
def get_neg(sentence):
counter=0
sent1 = sentence.lower()
sent2 = strip_punctuation(sent1)
sent3 = sent2.split()
for s in sent3:
for word in negative_words:
if s == word:
counter+=1
return counter
#sen = "He is Dull, Dump, Dusty and Dying!"
#print(get_neg(sen))
twitter_data = open('project_twitter_data.csv','r')
result_data = open('resulting_data.csv','w')
result_data.write("Number of Retweets, Number of Replies, Positive Score, Negative Score, Net Score")
result_data.write("\n")
lines = twitter_data.readlines()
first_out = lines.pop(0)
for ln in lines:
lst = ln.strip().split(',')
result_data.write("{}, {}, {}, {}, {}".format(lst[1], lst[2], get_pos(lst[0]), get_neg(lst[0]), (get_pos(lst[0])-get_neg(lst[0]))))
result_data.write("\n")
twitter_data.close()
result_data.close()
|
7680b3af75dbc0f87d44b21e9ef0459e097cd339 | ssalinasr/Programacion | /Python/history.py | 7,411 | 3.59375 | 4 | text = input("Horas empleadas por actividad: ")
d[lab[j]] = int(text)
names.append(name)
info.append(d)
d ={}
print(info)
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
res = algorithm.find_matching(g, matching_type = 'min', return_type = 'list' )
g = dict(zip(names, info))
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
print()
for i in res:
for act in i:
if isinstance(act, tuple):
print("A "+str(act[0])+" le corresponde la actividad "+str(act[1])+".")
print()
else:
print("En la que invierte "+str(act)+" minutos.")
print("Con un pago de $"+str(act*p)+'.')
print()
print('La empresa pagarÃa, según esta asignación, ' + str(cost) + ' minutos.')
print()
p = int(input("pago por minuto:"))
p = float(input("pago por minuto:"))
print()
for i in res:
for act in i:
if isinstance(act, tuple):
print("A "+str(act[0])+" le corresponde la actividad "+str(act[1])+".")
print()
else:
print("En la que invierte "+str(act)+" minutos.")
print("Con un pago de $"+str(act*p)+'.')
print()
print('La empresa pagarÃa, según esta asignación, ' + str(cost) + ' minutos.')
print()
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
print('Con un gasto total de $'+str(cost*p)+'.')
print()
%varexp --hist info
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Mon Feb 1 13:32:30 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Tue Feb 9 15:45:20 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Sin título0.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runcell(0, 'C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Tue Feb 9 17:26:48 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
print(lista[0])
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Tue Feb 9 20:06:15 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Prueba tkinter.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Wed Feb 10 06:24:40 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Wed Feb 17 12:58:38 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Inv.-de-Operaciones-1-main/IG_Ejercicio de Aplicación.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Inv.-de-Operaciones-1-main')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/IG_Ejercicio de Aplicación_correct.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
## ---(Mon Feb 22 11:30:18 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO/Sin título0.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/IO')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
runcell(0, 'C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
## ---(Mon Feb 22 12:44:40 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
## ---(Mon Feb 22 12:50:31 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
runcell(0, 'C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
runcell(0, 'C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
## ---(Tue Feb 23 10:53:51 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
## ---(Thu Feb 25 12:06:09 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística Final.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística Final.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
## ---(Thu Feb 25 16:13:30 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Programa Estadística Final.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD')
## ---(Fri Feb 26 08:42:47 2021)---
runfile('C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Prog.Est/Programa_Estadística_Final.py', wdir='C:/Users/FliaSalinasRodriguez/Documents/casas/otros/UD/Prog.Est') |
690be864deff1e7341580032166226798f91019e | shuaiqixiaopingge/leetcode | /29_divideTwoIntegers.py | 1,299 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 11:36:44 2019
@author: LiuZiping
"""
def devision(divided, divisor):
"""
:param int divided
:param int divisor
:return int result
"""
if divisor == 0:
return ZeroDivisionError
sign = (divided >= 0) == (divisor > 0)
absDivided = abs(divided)
absDivisor = abs(divisor)
result = 0
"""
此题本质上是有序数组求值
利用二分查找的思想
"""
while absDivisor <= absDivided:
r, absDivided = absDivision(absDivided, absDivisor)
result += r
result = result if sign else -result
return max(-2**31+1, min(2**31, result))
def absDivision(absDivided, absDivisor):
"""
翻倍除法,如果可以被除,则下一步除数翻倍,直至除数大于被除数;
返回商加总的结果和被除数的剩余值
:param int absDivided
:param int abdDivisor
:return tuple, left_absDivided
"""
timeCount = 1
result = 0
while absDivisor <= absDivided:
absDivided -= absDivisor
result += timeCount
absDivisor += absDivisor
timeCount += timeCount
return result, absDivided
#if __name__ == "__main__":
# divided = 10
# divisor = -3
# result = devision(divided, divisor)
|
face3a28eaf2b10c323e5e6e7c5e84081173c5d0 | fmfmfmfmfmfmfm/Panisara-CS01 | /CS01-12.py | 74 | 3.5 | 4 | Me=["Panisara","Mungmek","43244"]
for i in range(3):
print(Me[i])
|
721e21ac35aba12dd966cb394ebb955ed5585460 | yashlamba/Chaotic-Encryption | /Lorenz encryption/sustitutionLorenz.py | 1,754 | 4.15625 | 4 | """
Encrypting an image through substitution algorithm
using pseudo-random numbers generated from
Lorenz system of differential equations
"""
# Importing all the necessary libraries
import matplotlib.image as img
import matplotlib.pyplot as plt
import numpy as np
import lorenzSystem as key
# Accepting Image using it's path
path = str(input('Enter path of the image\n'))
image = img.imread(path)
# Displaying original image
plt.imshow(image)
plt.show()
# Storing the size of image in variables
height = image.shape[0]
width = image.shape[1]
# Using lorenz_key function to generate a key for every pixel
x, y, keys = key.lorenz_key(0.01, 0.02, 0.03, height*width)
l = 0
# Initializing an empty image to store the encrypted image
encryptedImage = np.zeros(shape=[height, width, 3], dtype=np.uint8)
# XORing each pixel with a pseudo-random number generated above/ Performing the
# substitution algorithm
for i in range(height):
for j in range(width):
# Converting the pseudo-random nuber generated into a number between 0 and 255
zk = (int((keys[l]*pow(10, 5))%256))
# Performing the XOR operation
encryptedImage[i, j] = image[i, j]^zk
l += 1
# Displaying the encrypted image
plt.imshow(encryptedImage)
plt.show()
# Initializing an empty image to store the decrypted image
decryptedImage = np.zeros(shape=[height, width, 3], dtype=np.uint8)
# XORing each pixel with the same number it was XORed above above/
# Performing the reverse substitution algorithm
l = 0
for i in range(height):
for j in range(width):
zk = (int((keys[l]*pow(10, 5))%256))
decryptedImage[i, j] = encryptedImage[i, j]^zk
l += 1
# Displaying the decrypted image
plt.imshow(decryptedImage)
plt.show() |
2ca885dc7068a0392aa811fb608981113873fdeb | smartpraveen/python-programming | /natural numbers.py | 125 | 3.90625 | 4 | a=5
if a<0:
print("enter the number")
else:
g=0
while(a>0):
g+=a
a=a-1
print("the sum is",g)
|
b2840b77e36f75f0a6dee05418b84cda2eb10cb8 | Pentagon03/competitive-programming | /yukicoder/36.py | 706 | 3.671875 | 4 | def is_prime(n):
if n <= 1: return False
if n <= 3: return True
if n % 2 == 0: return False
u = [2, 3, 5, 7, 325, 9375, 28178, 450775, 9780504, 1795265022]
e, c = n - 1, 0
while e % 2 == 0:
e >>= 1
c += 1
for p in u:
if n <= p: return True
a = pow(p, e, n)
if a == 1:
continue
j = 1
while a != n - 1:
if j == c: return False
a = a * a % n
j += 1
return True
def valid(n):
if n == 1 or is_prime(n):
return False
i = 2
while i ** 3 <= n:
if n % i == 0:
n //= i
if n == 1 or is_prime(n):
return False
else:
return True
i += 1
return False
print('YES' if valid(int(input())) else 'NO')
|
ea504f3089231bce79a834b19ee096f320b3191a | JaeGyu/PythonEx_1 | /ThreadEx2.py | 761 | 3.84375 | 4 | import threading
"""
아래는 threading.Thread 클래스를 상속 받는 클래스에 원하는 내용을 정의 하여
사용한다.
run()은 오버라이딩 해준다.
"""
class Worker(threading.Thread):
def __init__(self, args, name=""):
#현재 클래스에 init를 만들면 상위 클래스의 init를 호출해야 한다.
threading.Thread.__init__(self)
self.args = args
#threading.Thread 클래스의 run 메서드를 오버라이딩 한다.
def run(self):
print("name : %s, argument : %s" % (threading.currentThread().getName(), self.args[0]))
def main():
for i in range(50):
t = Worker(name="thread %i" % i, args=(i,))
t.start()
if __name__ == "__main__":
main()
|
ea9a7f3b2211ff0abe24ddd58706fc2c0e002e8d | kurniawanajisaputro/2ND-QUIZ-REPORT-DESIGN-AND-ANALYSIS-OF-ALGORITHM | /QUIZ2 PAAF.py | 1,828 | 4.21875 | 4 | # Simulate (or actually play) Guess the Number
# The number lies in a given range. Choose the number in the middle.
# If guess was too high, choose number in middle of lower half,
# if guess was too low, choose number in middle of upper half.
# Halve the appropriate range and repeat unti the number is correct.
binary=False # set this to True or False
lonum,hinum=1,128 # range for the number
import random as r
the_num=r.randint(lonum,hinum) # computer chooses a number randomly
print("I'm thinking of a number between",lonum,"and",hinum)
lo=1
hi=hinum
guesses=0
for i in range(lonum,hinum): # repeat this until guess is correct:
# note the int!
# guess=int(input ("What is your guess: ")) # if you want to play 2 players, just uncomment this
if binary: guess=lo+(hi-lo)//2 # integer division
else: guess=r.randint(lo,hi)
guesses+=1 # add 1 to count of guesses
Input1 = input ("Enter your number")
print("Guess:",guess)
Number = int(Input1)
# check the guessed number
if guess > the_num:
hi=guess
# bring down the upper bound
elif guess < the_num:
lo=guess # push up the lower bound
elif guess == the_num:
print("That took",guesses,"guesses,You lose!!!" )
break
else : guess == guess+1 # yay!
if Number > the_num:
print("Lower!")
elif Number< the_num:
print("Higher!")
elif Number== the_num:
print("That took",guesses,"guesses,You win!!!" )
break
# else: break
#print("That took {0} guesses".format(guesses)) # alternative to previous line
|
ad625da7c9f612bbabe96dc4e376339d8dc288dc | s3cret/py-basic | /Coursera/grep.py | 466 | 3.71875 | 4 | # Search for lines that start with From and have an at sign
import re
hand = open('mbox.txt')
rex = input('Enter a regular expression: ')
count = 0
results = list()
for line in hand:
line = line.rstrip()
if re.search(rex, line):
count = count + 1
results.append(line)
print('mbox.txt had', count, 'lines that matched', rex)
print()
printout = input('Check them out? (y/n)\n')
if printout == 'y':
for each in results:
print(each)
|
badaba27e8770df517c7d30e9b0429f779b47d36 | Tech-Puzzles/etc | /permute.py | 1,971 | 3.59375 | 4 | def permute(A):
print('calling,process',A)
if len(A) == 1:
print('returning',A)
return A
#else:
#permute(A[0:-2])
#permute(A[-1])
print('setting result to empty')
res = []
for permutation in permute(A[1:]):
print('step1',permutation)
for i in range(len(A)):
print('append', permutation[:i] ,'+', A[0:1] , '+', permutation[i:])
#res.append(permutation[:i] + A[0:1] + permutation[i:])
res.append(permutation[:i] + A[0] + permutation[i:])
# for permutation in permute(A[0:-2]):
# print('step1',permutation)
# for i in range(len(A)):
# print('append', permutation[:i] ,'+', A[-2:-1] , '+', permutation[i:])
# res.append(permutation[:i] + A[-2:-1] + permutation[i:])
print('returning',res)
return res
# print(permute([1,2]))
# print(permute('AB'))
# print(permute('ABC'))
# print(permute('ABC'*10))
def permutations(string_input, array, fixed_value=""):
print('calling',string_input)
for ch in string_input:
permutations(string_input.replace(ch, ""), array, fixed_value + ch)
if not string_input:
array.append(fixed_value)
array = []
# permutations("cat", array)
# print(array)
def permutelist(A,list,rest=[]):
print('calling',A)
if len(A)==1:
return A
for i in A:
permutelist(A[i:],list,A[:i])
if len(A)==0:
list.append(rest)
list = []
# permutelist([1,2,3], list)
# print(list)
def permutex(a, l, r):
print('calling',a,'left',l,'right',r)
#if l==r:
if l==len(a)-1:
print('answer',a)
else:
#for i in range(l,r+1):
for i in range(l,len(a)):
print('swapping',i,l)
a[l], a[i] = a[i], a[l]
#permutex(a, l+1, r)
permutex(a, l+1, len(a)-1)
a[l], a[i] = a[i], a[l] # backtrack
# A=[1,2,3,4]
# A=[1,2]
A=[1,2,3]
permutex(A, 0, len(A)-1)
|
1a41960ad89ef1b52c10bb8e85155f820d96f4af | iara/potter | /a.py | 12,042 | 3.578125 | 4 | #!/usr/bin/env python
"""Porter Stemming Algorithm
This is the Porter stemming algorithm, ported to Python from the
version coded up in ANSI C by the author. It may be be regarded
as canonical, in that it follows the algorithm presented in
Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
no. 3, pp 130-137,
only differing from it at the points maked --DEPARTURE-- below.
See also http://www.tartarus.org/~martin/PorterStemmer
The algorithm as described in the paper could be exactly replicated
by adjusting the points of DEPARTURE, but this is barely necessary,
because (a) the points of DEPARTURE are definitely improvements, and
(b) no encoding of the Porter stemmer I have seen is anything like
as exact as this version, even with the points of DEPARTURE!
Vivake Gupta (v@nano.com)
Release 1: January 2001
Further adjustments by Santiago Bruno (bananabruno@gmail.com)
to allow word input not restricted to one word per line, leading
to:
release 2: July 2008
"""
import sys
def __init__():
"""The main part of the stemming algorithm starts here.
b is a buffer holding a word to be stemmed. The letters are in b[k0],
b[k0+1] ... ending at b[k]. In fact k0 = 0 in this demo program. k is
readjusted downwards as the stemming progresses. Zero termination is
not in fact used in the algorithm.
Note that only lower case sequences are stemmed. Forcing to lower case
should be done before stem(...) is called.
"""
word = "" # buffer for word to be stemmed
k = 0
k0 = 0
offset = 0 # j is a general offset into the string
def cons(i, word, k0):
"""cons(i) is TRUE <=> b[i] is a consonant."""
if word[i] == 'a' or word[i] == 'e' or word[i] == 'i' or word[i] == 'o' or word[i] == 'u':
return 0
if word[i] == 'y':
if i == k0:
return 1
else:
return (not cons(i - 1))
return 1
def m(k0, offset):
"""m() measures the number of consonant sequences between k0 and j.
if c is a consonant sequence and v a vowel sequence, and <..>
indicates arbitrary presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
"""
n = 0
i = k0
while 1:
if i > offset:
return n
if not cons(i):
break
i = i + 1
i = i + 1
while 1:
while 1:
if i > offset:
return n
if cons(i):
break
i = i + 1
i = i + 1
n = n + 1
while 1:
if i > offset:
return n
if not cons(i):
break
i = i + 1
i = i + 1
def vowelinstem(k0):
"""vowelinstem() is TRUE <=> k0,...j contains a vowel"""
for i in range(k0, offset + 1):
if not cons(i):
return 1
return 0
def doublec(j, word, k0):
"""doublec(j) is TRUE <=> j,(j-1) contain a double consonant."""
if j < (k0 + 1):
return 0
if (word[j] != word[j-1]):
return 0
return cons(j)
def cvc(i, word, k0):
"""cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
"""
if i < (k0 + 2) or not cons(i) or cons(i-1) or not cons(i-2):
return 0
ch = word[i]
if ch == 'w' or ch == 'x' or ch == 'y':
return 0
return 1
def ends(s, word, k, k0, offset):
"""ends(s) is TRUE <=> k0,...k ends with the string s."""
length = len(s)
if s[length - 1] != word[k]: # tiny speed-up
return 0
if length > (k - k0 + 1):
return 0
if word[k - length+1:k+1] != s:
return 0
offset = k - length
return 1
def setto(s, word, k, offset):
"""setto(s) sets (j+1),...k to the characters in the string s, readjusting k."""
length = len(s)
word = word[:offset+1] + s + word[offset+length+1:]
k = offset + length
def r(s, word, k, offset):
"""r(s) is used further down."""
if m() > 0:
setto(s, word, k, offset)
def step1ab(word, k):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
"""
if word[k] == 's':
if ends("sses", word, k, k0, offset):
k = k - 2
elif ends("ies", word, k, k0, offset):
setto("i", word, k, offset)
elif word[k - 1] != 's':
k = k - 1
if ends("eed", word, k, k0, offset):
if m(k0, offset) > 0:
k = k - 1
elif (ends("ed", word, k, k0, offset) or ends("ing", word, k, k0, offset)) and vowelinstem():
k = offset
if ends("at", word, k, k0, offset): setto("ate", word, k, offset)
elif ends("bl", word, k, k0, offset): setto("ble", word, k, offset)
elif ends("iz", word, k, k0, offset): setto("ize", word, k, offset)
elif doublec(k):
k = k - 1
ch = word[k]
if ch == 'l' or ch == 's' or ch == 'z':
k = k + 1
elif (m(k0, offset) == 1 and cvc(k)):
setto("e", word, k, offset)
def step1c(word, k):
"""step1c() turns terminal y to i when there is another vowel in the stem."""
if (ends("y", word, k, k0, offset) and vowelinstem()):
word = word[:k] + 'i' + word[k+1:]
def step2(word, k):
"""step2() maps double suffices to single ones.
so -ization ( = -ize plus -ation) maps to -ize etc. note that the
string before the suffix must give m() > 0.
"""
if word[k - 1] == 'a':
if ends("ational", word, k, k0, offset): r("ate", word, k, offset)
elif ends("tional", word, k, k0, offset): r("tion", word, k, offset)
elif word[k - 1] == 'c':
if ends("enci", word, k, k0, offset): r("ence", word, k, offset)
elif ends("anci", word, k, k0, offset): r("ance", word, k, offset)
elif word[k - 1] == 'e':
if ends("izer", word, k, k0, offset): r("ize", word, k, offset)
elif word[k - 1] == 'l':
if ends("bli", word, k, k0, offset): r("ble", word, k, offset)
# To match the published algorithm, replace this phrase with
# if ends("abli"): r("able")
elif ends("alli", word, k, k0, offset): r("al", word, k, offset)
elif ends("entli", word, k, k0, offset): r("ent", word, k, offset)
elif ends("eli", word, k, k0, offset): r("e", word, k, offset)
elif ends("ousli", word, k, k0, offset): r("ous", word, k, offset)
elif word[k - 1] == 'o':
if ends("ization", word, k, k0, offset): r("ize", word, k, offset)
elif ends("ation", word, k, k0, offset): r("ate", word, k, offset)
elif ends("ator", word, k, k0, offset): r("ate", word, k, offset)
elif word[k - 1] == 's':
if ends("alism", word, k, k0, offset): r("al", word, k, offset)
elif ends("iveness", word, k, k0, offset): r("ive", word, k, offset)
elif ends("fulness", word, k, k0, offset): r("ful", word, k, offset)
elif ends("ousness", word, k, k0, offset): r("ous", word, k, offset)
elif word[k - 1] == 't':
if ends("aliti", word, k, k0, offset): r("al", word, k, offset)
elif ends("iviti", word, k, k0, offset): r("ive", word, k, offset)
elif ends("biliti", word, k, k0, offset): r("ble", word, k, offset)
elif word[k - 1] == 'g': # --DEPARTURE--
if ends("logi", word, k, k0, offset): r("log", word, k, offset)
# To match the published algorithm, delete this phrase
def step3(word, k):
"""step3() dels with -ic-, -full, -ness etc. similar strategy to step2."""
if word[k] == 'e':
if ends("icate", word, k, k0, offset): r("ic", word, k, offset)
elif ends("ative", word, k, k0, offset): r("", word, k, offset)
elif ends("alize", word, k, k0, offset): r("al", word, k, offset)
elif word[k] == 'i':
if ends("iciti", word, k, k0, offset): r("ic", word, k, offset)
elif word[k] == 'l':
if ends("ical", word, k, k0, offset): r("ic", word, k, offset)
elif ends("ful", word, k, k0, offset): r("", word, k, offset)
elif word[k] == 's':
if ends("ness", word, k, k0, offset): r("", word, k, offset)
def step4(word, k, offset):
"""step4() takes off -ant, -ence etc., in context <c>vcvc<v>."""
if word[k - 1] == 'a':
if ends("al", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'c':
if ends("ance", word, k, k0, offset): pass
elif ends("ence", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'e':
if ends("er", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'i':
if ends("ic", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'l':
if ends("able", word, k, k0, offset): pass
elif ends("ible", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'n':
if ends("ant", word, k, k0, offset): pass
elif ends("ement", word, k, k0, offset): pass
elif ends("ment", word, k, k0, offset): pass
elif ends("ent", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'o':
if ends("ion", word, k, k0, offset) and (word[offset] == 's' or word[offset] == 't'): pass
elif ends("ou", word, k, k0, offset): pass
# takes care of -ous
else: return
elif word[k - 1] == 's':
if ends("ism", word, k, k0, offset): pass
else: return
elif word[k - 1] == 't':
if ends("ate", word, k, k0, offset): pass
elif ends("iti", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'u':
if ends("ous", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'v':
if ends("ive", word, k, k0, offset): pass
else: return
elif word[k - 1] == 'z':
if ends("ize", word, k, k0, offset): pass
else: return
else:
return
if m(k0, offset) > 1:
k = offset
def step5(word, k, offset):
"""step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1.
"""
offset = k
if word[k] == 'e':
a = m(k0, offset)
if a > 1 or (a == 1 and not cvc(k-1)):
k = k - 1
if word[k] == 'l' and doublec(k) and m(k0, offset) > 1:
k = k -1
def stem(p, i, j, word, k, k0, offset):
"""In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns the new
end-point of the string, k. Stemming never increases word length, so
i <= k <= j. To turn the stemmer into a module, declare 'stem' as
extern, and delete the remainder of this file.
"""
# copy the parameters into statics
word = p
k = offset
k0 = i
if k <= k0 + 1:
return word # --DEPARTURE--
# With this line, strings of length 1 or 2 don't go through the
# stemming process, although no mention is made of this in the
# published algorithm. Remove the line to match the published
# algorithm.
step1ab(word, k)
step1c(word, k)
step2(word, k)
step3(word, k)
step4(word, k)
step5(word, k)
return word[k0:k+1]
if __name__ == '__main__':
#p = PorterStemmer()
#word = "created"
word = "processing"
q = stem(word, 0, len(word)-1)
print(q)
|
778793baf5b29f0869fba2dd67817be8ee9ab645 | Mschikay/leetcode | /60Permutation.py | 1,100 | 3.546875 | 4 | import math
import pprint
class Solution:
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
if k > math.factorial(n) or n <= 0:
return None
numbers = []
for i in range(1, n + 1):
numbers.append(i)
# perm = [[1]]
# for i in range(1, len(nums)):
# n = nums[i]
# new_perm = []
# for p in perm:
# l_perm = len(p)
# for j in range(l_perm+1):
# new_perm.append(p[:j] + [n] + p[j:l_perm])
# perm = new_perm
# pprint.pprint(perm)
permutation = ''
k -= 1
while n > 0:
n -= 1
f = math.factorial(n)
# get the index of current digit
index, k = k // f, k % f
permutation += str(numbers[index])
# remove handled number
del numbers[index]
return permutation
if __name__ == '__main__':
s = Solution()
print(s.getPermutation(4, 3))
|
3a41c69136baa22a0cb0866158d5929b05464117 | xenapom/xenapom.github.io | /python/src/unpackaged/abm/model.py | 2,233 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 14 07:57:28 2017
Displays agents in a coordinate system and calculates the
distance between them according to the Pythagorean theorem
@author: paula
"""
import matplotlib.pyplot
import agentframework
import csv
import matplotlib.animation
import random
num_of_agents = 50
num_of_iterations = 100
neighbourhood = 20
environment = []
agents = []
fig = matplotlib.pyplot.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1])
# Loop csv raster data
# new rowlist before each row
# add the row values into the rowlist, make sure they are integers
csv_file = open('in.csv')
reader = csv.reader(csv_file)
for row in reader:
rowlist = []
for values in row:
rowlist.append(int(values))
# add the row to the environment list
environment.append(rowlist)
# Setup variables in a 100x100 grid
# Create x and y agents in the coordinate system
for i in range(num_of_agents):
agents.append(agentframework.Agent(environment, agents))
carry_on = True
def update(frame_number):
fig.clear()
global carry_on
# Walk the agents in the coordinate system
for j in range(num_of_iterations):
for k in range(num_of_agents):
agents[k].move()
agents[k].eat()
agents[k].share_with_neighbours(neighbourhood)
if random.random() < 0.1:
carry_on = False
print("stopping condition")
for i in range(num_of_agents):
matplotlib.pyplot.scatter(agents[i].x, agents[i].y)
def gen_function(b = [0]):
a = 0
global carry_on #Not actually needed as we're not assigning, but clearer
while (a < 10) & (carry_on) :
yield a # Returns control and waits next call.
a = a + 1
# save the animation as an html file in order to display the animation on a web page
# tested to work on a macbook. Commented out for assignment submission
animation = matplotlib.animation.FuncAnimation(fig, update, frames=gen_function, repeat=False)
#animation.save('abm.html', fps=30, extra_args=['-vcodec','libx264'])
#matplotlib.pyplot.show()
# shows the output of the agents in the csv pixel data environment
matplotlib.pyplot.imshow(environment)
|
0858fb97a9a1b57f07f6c500dbf7c46f60688dd9 | feliperod0519/python101 | /python15-oo1.py | 2,561 | 4.0625 | 4 | import argparse
class Sample():
pass
class Dog():
species = 'Mammal'
def __init__(self,mybreed, myname, spots):
self.breed = mybreed
self.name = myname
self.spots = spots
def bark(self,n):
print("Woof! {} {}".format(self.name,n))
class Circle():
pi = 3.1416
def __init__(self,radius=1):
self.radius = radius
self.area = radius * radius * self.pi
self.area = radius * radius * Circle.pi
def get_circunference(self):
return self.radius * self.pi * 2
class Animal():
def __init__(self):
print('Animal Created')
def who_am_i(self):
print("I am an animal")
def eat(self):
print('I am eating')
def bark(self):
print("Woof!")
class Doggie(Animal):
def __init__(self):
Animal.__init__(self)
print("Doggie created")
def who_am_i(self):
print("I'm doggie")
class Perro():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says woof!"
class Cat():
def __init__(self,name):
self.name = name
def speak(self):
return self.name + " says meow!"
class Book():
def __init__(self,title,author,pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"{self.title} by {self.author}"
def __len__(self):
return self.pages
def __del__(self):
print('Book deleted')
def get_args():
parser = argparse.ArgumentParser(description='Bottles of beer song',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n','--num',metavar='number',type=int,default=10,help='How many bottles')
args = parser.parse_args()
if args.num < 1:
parser.error(f'--num "{args.num}" must be greater than 0')
return args
def main():
print('OO1')
my_sample = Sample()
print(type(my_sample))
my_dog = Dog(mybreed='Huskie',myname='Manchitas',spots=False)
print(type(my_dog))
print(my_dog.breed)
print(my_dog.species)
my_dog.bark(100)
my_circle = Circle(30)
print(my_circle.get_circunference())
print(my_circle.area)
my_doggie = Doggie()
my_doggie.eat()
my_doggie.who_am_i()
my_doggie.bark()
niko = Perro("niko")
felix = Cat("felix")
print(niko.speak())
print(felix.speak())
b = Book('Hello','Felipe',100)
print(str(b))
print(len(b))
del b
if __name__ == '__main__':
main()
|
a8a666bd5268c1aa59e637c40198b33ecdcb51df | rritec/Trainings | /01 DS ML DL NLP and AI With Python Lab Copy/02 Lab Data/Python/Py29_5_Generators_expression_to_read_items.py | 335 | 4 | 4 | # Create generator object: result
result = (num for num in range(10))
print("***** 01 First 5 values of generator ***** ")
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print(next(result))
print("***** 02 Print the rest of the values using for Loop *****")
for value in result:
print(value)
|
939a70f6ca497b8dec81ff5161f28fd52a736bf7 | ericjwhitney/pyavia | /examples/solve/dqnm_example.py | 1,169 | 4.3125 | 4 | #!usr/bin/env python3
# Examples of the solution of systems of equations.
# Last updated: 21 December 2022 by Eric J. Whitney
import numpy as np
from pyavia.solve.dqnm import solve_dqnm
def linear_system_example(x):
"""A simple linear system of equations."""
n = len(x)
res = [0] * n
for i in range(n):
for j in range(n):
res[i] += (1 + i * j) * x[j]
return res
def std_problem_1(x):
"""Standard start point x0 = (0.87, 0.87, ...)"""
return [np.cos(x_i) - 1 for x_i in x]
def std_problem_3(x):
"""Standard start point x0 = (0.5, 0.5, ...)"""
n = len(x)
f = [0.0] * n
for i in range(n - 1):
f[i] = x[i] * x[i + 1] - 1
f[n - 1] = x[n - 1] * x[0] - 1
return f
# Solve one of the above problems at a given size.
ndim = 500
x0 = [0.5] * ndim
bounds = ([-1] * ndim, [+np.inf] * ndim)
x_result = solve_dqnm(std_problem_1, x0=x0, ftol=1e-5, xtol=1e-6,
bounds=bounds, maxits=50, order=2, verbose=True)
print("\nResult x = " +
np.array2string(np.asarray(x_result), precision=6, suppress_small=True,
separator=', ', sign=' ', floatmode='fixed'))
|
4c201991af9f384d49c8b847b902d1d2d19b0b46 | MoisesMondragon/RECURSIVIDAD | /decimal_binario.py | 298 | 3.5625 | 4 | __autor__= 'Moises Mondragon Mondragon'
class convertidor:
numero = int(22)
def decimalabinario(decimal):
binario=''
while decimal//2 !=0:
binario= str(decimal%2)+ binario
decimal= decimal//2
return str(decimal)+ binario
print( decimalabinario(numero)) |
b4f73a5e0991490a98347cc73b06806030352d64 | hoang-ng/LeetCode | /Tree/559.py | 1,276 | 3.828125 | 4 | # 559. Maximum Depth of N-ary Tree
# Given a n-ary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
# Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
# Example 1:
# Input: root = [1,null,3,2,4,null,5,6]
# Output: 3
# Example 2:
# Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
# Output: 5
# Constraints:
# The depth of the n-ary tree is less than or equal to 1000.
# The total number of nodes is between [0, 10^4].
class Solution(object):
def maxDepth(self, root):
if not root:
return 0
dept = 0
queue = [root]
while len(queue) > 0:
dept += 1
size = len(queue)
for _ in range(size):
node = queue.pop(0)
for child in node.children:
queue.append(child)
return dept
def maxDepth2(self, root):
if not root:
return 0
dept = 0
for child in root.children:
dept = max(dept, self.maxDepth(child))
return 1 + dept |
9d0f40935000f5d43da9850958b078937ad0415b | mehulthakral/logic_detector | /backend/dataset/levelOrder/levelorder_12.py | 1,090 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
traversal_queue = [ root ] if root else []
path = []
while traversal_queue:
cur_level_path, next_level_queue = [], []
for node in traversal_queue:
# update current level traversal path
cur_level_path.append( node.val )
if node.left:
next_level_queue.append( node.left )
if node.right:
next_level_queue.append( node.right )
# add current level path into path collection
path.append( cur_level_path )
# update next_level_queue as traversal_queu
traversal_queue = next_level_queue
return path
|
0864757377a5392b23fb07e73498537b95ab5bf4 | calin-juganaru/ic | /tema/tema1.py | 5,522 | 3.515625 | 4 | #!/usr/bin/env python
import random
import sys
from Crypto.Cipher import AES
from math import ceil
BLOCK_SIZE = 16
IV = b'This is easy HW!'
###############################################################################
def blockify(text, block_size=BLOCK_SIZE):
"""
Cuts the bytestream into equal sized blocks.
Args:
text should be a bytestring (i.e. b'text', bytes('text') or bytearray('text'))
block_size should be a number
Return:
A list that contains bytestrings of maximum block_size bytes
Example:
[b'ex', b'am', b'pl', b'e'] = blockify(b'example', 2)
[b'01000001', b'01000010'] = blockify(b'0100000101000010', 8)
"""
nr_blocks = ceil(len(text) / block_size)
return [bytearray(text[block_size * i : block_size * (i + 1)]) for i in range(nr_blocks)]
###############################################################################
def validate_padding(padded_text):
"""
Verifies if the bytestream ends with a suffix of X times 'X' (eg. '333' or '22')
Args:
padded_text should be a bytestring
Return:
Boolean value True if the padded is correct, otherwise returns False
"""
value = padded_text[-1]
index = len(padded_text) - 2
count = 1
while padded_text[index] == value:
index = index - 1
count = count + 1
if index < 0:
break
return value == count
###############################################################################
def pkcs7_pad(text, block_size=BLOCK_SIZE):
"""
Appends padding (X times 'X') at the end of a text.
X depends on the size of the text.
All texts should be padded, no matter their size!
Args:
text should be a bytestring
Return:
The bytestring with padding
"""
nr_blocks = ceil(len(text) / block_size)
X = (nr_blocks * block_size) - len(text)
text = bytearray(text)
if X == 0:
for i in range(0, block_size):
text.append(block_size)
else:
for i in range(0, X):
text.append(X)
return bytes(text)
###############################################################################
def pkcs7_depad(text):
"""
Removes the padding of a text (only if it's valid).
Tip: use validate_padding
Args:
text should be a bytestring
Return:
The bytestring without the padding or None if invalid
"""
text = bytearray(text)
if validate_padding(text):
last = text.pop()
while text[-1] == last:
text.pop()
if len(text) == 0:
break
return bytes(text)
return None
###############################################################################
def aes_dec_cbc(k, c, iv):
"""
Decrypt a ciphertext c with a key k in CBC mode using AES as follows:
m = AES(k, c)
Args:
c should be a bytestring (i.e. a sequence of characters such as 'Hello...' or '\x02\x04...')
k should be a bytestring of length exactly 16 bytes.
iv should be a bytestring of length exactly 16 bytes.
Return:
The bytestring message m
"""
aes = AES.new(k, AES.MODE_CBC, iv)
m = aes.decrypt(c)
depad_m = pkcs7_depad(m)
return depad_m
###############################################################################
def check_cbcpad(c, iv):
"""
Oracle for checking if a given ciphertext has correct CBC-padding.
That is, it checks that the last n bytes all have the value n.
Args:
c is the ciphertext to be checked.
iv is the initialization vector for the ciphertext.
Note: the key is supposed to be known just by the oracle.
Return 1 if the pad is correct, 0 otherwise.
"""
key = b'za best key ever'
if aes_dec_cbc(key, c, iv) != None:
return 1
return 0
###############################################################################
def byte_xor(a, b):
return bytes([x ^ y for x, y in zip(a, b)])
###############################################################################
if __name__ == "__main__":
ctext = "918073498F88237C1DC7697ED381466719A2449EE48C83EABD5B944589ED66B77AC9FBD9EF98EEEDDD62F6B1B8F05A468E269F9C314C3ACBD8CC56D7C76AADE8484A1AE8FE0248465B9018D395D3846C36A4515B2277B1796F22B7F5B1FBE23EC1C342B9FD08F1A16F242A9AB1CD2DE51C32AC4F94FA1106562AE91A98B4480FDBFAA208E36678D7B5943C80DD0D78C755CC2C4D7408F14E4A32A3C4B61180084EAF0F8ECD5E08B3B9C5D6E952FF26E8A0499E1301D381C2B4C452FBEF5A85018F158949CC800E151AECCED07BC6C72EE084E00F38C64D989942423D959D953EA50FBA949B4F57D7A89EFFFE640620D626D6F531E0C48FAFC3CEF6C3BC4A98963579BACC3BD94AED62BF5318AB9453C7BAA5AC912183F374643DC7A5DFE3DBFCD9C6B61FD5FDF7FF91E421E9E6D9F633"
ciphertext = bytes.fromhex(ctext)
blocks = blockify(ciphertext, BLOCK_SIZE)
msg = ""
for block in blocks:
r = bytearray(b'0' * 16)
for i in range(0, 16):
X = bytearray(b'0' * (15 - i))
for k in range(0, i + 1):
X.append(i + 1)
char = -1
for j in range(1, 256):
r[15 - i] = j
aux = byte_xor(IV, r)
aux = byte_xor(aux, X)
if check_cbcpad(block, aux):
if char == -1:
char = j
else:
IV_test = bytearray(IV)
IV_test[-2] = (IV_test[-2] + 123) % 256
aux2 = byte_xor(IV_test, r)
aux2 = byte_xor(aux2, X)
if check_cbcpad(block, aux2):
char = j
r[15 - i] = char
IV = block
msg += r.decode()
print(msg)
############################################################################### |
1c41d07623b2fe5b98691317cdec47a02b6d3eec | surajwate/57-python-exercises | /exercises/exercise11.py | 352 | 4.1875 | 4 | def currency_conversion(euros, rate):
dollars = euros * (rate/100)
return f"""{euros} euros at an exchange rate of {rate} is
{dollars:.2f} U.S. dollars."""
if __name__ == '__main__':
euros = int(input("How many euros are you exchanging? "))
rate = float(input("What is the exchange rate? "))
print(currency_conversion(euros, rate)) |
7ffecd7f1db44cc04ec394a5aa97cfd5fec07c64 | RosemaryDavy/Python-Code-Samples | /Problem3MultiplyList.py | 305 | 4.34375 | 4 | #Rosemary Davy
#February 25, 2021
#Problem 3: Write a Python function to
#multiply all the numbers in a list.
#Use list [5, 2, 7, -1].
def multiplyList(numbers): #define how to mulitply a list of numbers
total = 1
for x in numbers:
total *= x
return total
print(multiplyList((5, 2, 7, -1)))
|
6fc7467f2935ad1fec180e60d3b29ea9c5b911af | Lynijahhhhhhhhh/ciphers | /rotational_cipher.py | 3,152 | 4.5 | 4 | # author:
# date:
# difficulty: medium
# Wikipedia: https://en.wikipedia.org/wiki/Caesar_cipher
# Read this for a better understanding of the cipher.
# Introduction
#
# Create an implementation of the rotational cipher, also sometimes called the Caesar cipher.
#
# The Caesar cipher is a simple shift cipher that relies on transposing all the letters in the alphabet using
# an integer key between 0 and 26. Using a key of 0 or 26 will always yield the same output due to modular
# arithmetic. The letter is shifted for as many values as the value of the key.
#
# The general notation for rotational ciphers is ROT + <key>. The most commonly used rotational cipher is ROT13.
#
# A ROT13 on the Latin alphabet would be as follows:
#
# Plain: abcdefghijklmnopqrstuvwxyz
# Cipher: nopqrstuvwxyzabcdefghijklm
#
# It is stronger than the Atbash cipher because it has 27 possible keys, and 25 usable keys.
#
# Ciphertext is written out in the same formatting as the input including spaces and punctuation.
# Examples
#
# ROT5 omg gives trl
# ROT0 c gives c
# ROT26 Cool gives Cool
# ROT13 The quick brown fox jumps over the lazy dog. gives Gur dhvpx oebja sbk whzcf bire gur ynml qbt.
# ROT13 Gur dhvpx oebja sbk whzcf bire gur ynml qbt. gives The quick brown fox jumps over the lazy dog.
#
# Instructions
# 1 - The program should accept input in the form of a string, which will be the plain text. This is the text
# to be encrypted.
# 2 - The program should also accept a key from the user, which will be the shift for the rotational cipher.
# 2 - Convert the plain text into cipher text using the rotational cipher, shifting by the amount specified
# by the user.
# 3 - Print the result to the user.
#
# WRITE CODE BELOW #
users_letters=input(">>>Letters: ")
users_skip= int(input(">>Rotate: "))
def ceasar_projecttttt(mainText, step):
# symbols = ['`','~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '[', '}', ']', '/','|', ':', ';', '"', '\'\ ', '<', ',', '>', '.', '?', '/']
lowercase = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]
uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
outText = []
cryptText = []
for eachLetter in mainText:
if eachLetter in uppercase:
index = uppercase.index(eachLetter)
crypting = (index + step) % 26
cryptText.append(crypting)
newLetter = uppercase[crypting]
outText.append(newLetter)
elif eachLetter in lowercase:
index = lowercase.index(eachLetter)
crypting = (index + step) % 26
cryptText.append(crypting)
newLetter = lowercase[crypting]
outText.append(newLetter)
elif eachLetter in symbols:
index = symbols.index(eachLetter)
cryptText.append(crypting)
newLetter = symbols[crypting]
outText.append(newLetter)
return outText
mahChallenge = ceasar_projecttttt(users_letters, users_skip)
print()
print(mahChallenge)
print()
|
05e9e288d2e1736bf3e173c64b58b478b164c438 | OliviaFortuneUCD/Python211021 | /Program7.py | 228 | 3.609375 | 4 | # import pandas
import pandas as pd
# Read the data using csv
data=pd.read_csv('EmployeeDataframe.csv')
# Filter columns
data.filter(['name', 'department','grade','age'])
print(data.filter(['name', 'department','grade','age'])) |
cb5bf0dc83496bd5a577453efbcc4465d763b368 | kuswahashish/learningPaython | /condition.py | 172 | 4.25 | 4 | temp = int(input("Enter the temprature : "))
if temp >=30 :
print("It's a HoT Day !")
elif temp<=0:
print("It's a Cold day!")
else:
print("Its a normal Day :)") |
ed06a41b79570eb8c77a3674a7dcd9db14f88a2d | ZehCoque/SPH_ZUT | /hashing.py | 3,422 | 3.625 | 4 | import math
from numpy import array,seterr
import time
seterr(all='raise')
# Function that returns True if n
# is prime else returns False
def isPrime(n):
# Corner cases
if(n <= 1):
return False
if(n <= 3):
return True
# This is checked so that we can skip
# middle five numbers in below loop
if(n % 2 == 0 or n % 3 == 0):
return False
for i in range(5,int(math.sqrt(n) + 1), 6):
if(n % i == 0 or n % (i + 2) == 0):
return False
return True
# Function to return the smallest
# prime number greater than N
def nextPrime(N):
# Base case
if (N <= 1):
return 2
prime = N
found = False
# Loop continuously until isPrime returns
# True for a number greater than n
while(not found):
prime = prime + 1
if(isPrime(prime) == True):
found = True
return prime
class Hashing:
def __init__(self,cell_size,N,d={}):
self.d = d
self.cell_size = cell_size
self.table_size = N
self.p1 = 73856093
self.p2 = 19349669
self.p3 = 83492791
def r_c(self,point):
return [math.floor(point[0]/self.cell_size),
math.floor(point[1]/self.cell_size),
math.floor(point[2]/self.cell_size)]
def _hash(self,point):
r = array([point[0]*self.p1,
point[1]*self.p2,
point[2]*self.p3])
return (r[0]^r[1]^r[2]) % self.table_size
def _add(self,point,obj):
r_c = self.r_c(point)
hh = self._hash(r_c)
if hh not in self.d.keys():
self.d[hh] = list()
if obj not in self.d[hh]:
self.d[hh].append(obj)
for i in self.d:
if obj in self.d[i] and i!=hh:
for j in self.d[i]:
if j == obj:
ind = self.d[i].index(j)
del self.d[i][ind]
return
#self._del(point,obj)
def _del(self,point,obj):
i = self.d.get(self._hash(point))
for j in i:
if j == obj:
del i[j]
def possible_neighbors(self,point):
point = array(point)
L = []
min_point = point - self.cell_size
max_point = point + self.cell_size
BBmin = self.r_c(min_point)
BBmax = self.r_c(max_point)
x_count = BBmin[0]
while x_count <= BBmax[0]:
y_count = BBmin[1]
while y_count <= BBmax[1]:
z_count = BBmin[2]
while z_count <= BBmax[2]:
new_point = [x_count,y_count,z_count]
i = self.d.get(self._hash(new_point))
if i != None:
for j in i:
L.append(j)
z_count += 1
y_count += 1
x_count += 1
return L
# h = 10
# N = 1000
# #Hashing(h,N)._add([10,11,32])
# start = time.time()
# print(Hashing(h,N)._add([10,25,32],88))
# print(Hashing(h,N)._add([10,11,32],68))
# print(Hashing(h,N)._add([10,11,32],67))
# print(Hashing(h,N)._add([10,14,48],65))
# x = Hashing(h,N).possible_neighbors([10,24,32])
# print(x)
# print(len(x))
# print(start-time.time()) |
7ae7da0a2e62358bbe49065e2ca39476f702a4a7 | dlx24x7/py3_data_rep | /week1_practice_ds.py | 4,254 | 4.1875 | 4 | """
week1_practice
This is the week one practice for data structures
"""
string1 = "It's just a flesh wound"
string2 = "It's just a flesh wound"
string3 = "It's just a flesh wound"
string4 = """It's just a flesh wound"""
print("Example 1")
print(string1)
print(string2)
print(string3)
print(string4)
print(" ")
# Create a string formed by selecting the first and last letters of example_string
print("Example 2")
example_string = "It's just a flesh wound"
print(example_string)
solution_string = example_string[0] + example_string[-1]
print(solution_string)
print(" ")
# Output should be
#It's just a flesh wound
#Id
# Create a string formed by selecting all but the first and last letters of example_string
print("Example 3")
example_string = "It's just a flesh wound"
print(example_string)
solution_string = example_string[1:-1]
print(solution_string)
# Output should be
#It's just a flesh wound
#t's just a flesh woun
print("Example 4")
# Create a string formed by selecting the first three characters of example_string
# plus the last three characters of example_string
example_string = "It's just a flesh wound"
print(example_string)
#solution_string = example_string[0:3] + example_string[-3:-1] + example_string[-1]
solution_string = example_string[:3] + example_string[-3:]
print(solution_string)
# Output should be
#It's just a flesh wound
#It'und
print("Example 5")
def echo(call, repeats):
"""
Echo the string call to the console repeats number of time
Each echo should be on a separate line
"""
print((call + "\n") * repeats)
return
# Tests
echo("Hello", 5)
echo("Goodbye", 3)
# Output
#Hello
#Hello
#Hello
#Hello
#Hello
#Goodbye
#Goodbye
#Goodbye
print("Example 6")
def is_substring(example_string, test_string):
"""
Function that returns True if test_string
is a substring of example_string and False otherwise
"""
# enter one line of code for substring test here
if (example_string.find(test_string) >= 0):
return True
else:
return False
# Tests
example_string = "It's just a flesh wound."
print(is_substring(example_string, "just"))
print(is_substring(example_string, "flesh wound"))
print(is_substring(example_string, "piddog"))
print(is_substring(example_string, "it's"))
print(is_substring(example_string, "It's"))
# Output
#True
#True
#False
#False
#True
print("Example 7")
def make_nametag(first_name, topic):
"""
Given two strings first_name and topic,
return a string of the form ""Hi! My name
is XXX. This lecture covers YYY." where
XXX and YYY are first_name and topic.
"""
name = first_name
area = topic
sentence = "Hi! My is {0}. This lecture covers {1}.".format(name,area)
return sentence
# Tests
print(make_nametag("Scott", "Python"))
print(make_nametag("Joe", "games"))
print(make_nametag("John", "programming tips"))
# Output
#Hi! My name is Scott. This lecture covers Python.
#Hi! My name is Joe. This lecture covers games.
#Hi! My name is John. This lecture covers programming tips.
print("Example 8")
def make_int(int_string):
"""
Given the string int_string, return the associated integer if all
digits are decimal digits. Other return -1.
"""
# enter code here
if (int_string.isdigit()):
number = int(int_string)
else:
number = -1
return number
# Tests
print(make_int("123"))
print(make_int("00123"))
print(make_int("1.23"))
print(make_int("-123"))
# Output
#123
#123
#-1
#-1
print("Exercise 9")
def name_swap(name_string):
"""
Given the string name string of the form "first last", return
the string "Last First" where both names are now capitalized
"""
# Enter code here
length = len(name_string)
#print(length)
first_space = name_string.find(" ")
first_name = name_string[:first_space]
cap_first = first_name.capitalize()
#print(cap_first)
last_name = name_string[first_space+1:]
cap_last = last_name.capitalize()
#print(cap_last)
name_tag = cap_last + " " + cap_first
return name_tag
# Tests
print(name_swap("joe warren"))
print(name_swap("scott rixner"))
print(name_swap("john greiner"))
# Output
#Warren Joe
#Rixner Scott
#Greiner John |
a923688965286be0a3b761091f8d4db3e72da3d7 | JosiahDub/collatz | /Collatz.py | 9,466 | 3.5625 | 4 | from math import ceil, floor
from EvenSteps import EvenSteps
from Remainder import Remainder
from RemainderPair import RemainderPair
from CollatzContainer import CollatzContainer
# TODO: write a script to calculate the average shifted length for increasing m
class Collatz:
"""
This class handles building a list of EvenSteps and Remainder objects
based on the equation num = multiple*2^even_20 + remainder.
There are two algorithms to generate numbers:
loop_and_add: Pass in a generic shifted. Checks if a number has been
calculated. If not, adds them.
add_from_incomplete_list: generates a list of unknown numbers and adds
them that way. This algorithm is much faster, especially using small
batches.
"""
# Total percent of all numbers covered
total_percent = 0.0
evens = {}
def __init__(self, container: CollatzContainer, last_number=3, step_size=4, batch_value=10000,
add_trivial=True):
self.container = container
# last_number = 3 skips trivial 1 and 2.
self.last_number = last_number
# step_size = 4 safely skips 75% of trivial numbers
self.step_size = step_size
# Number of numbers to calculate since last number.
self.batch_value = batch_value
# Adds trivial even steps, their remainders and sequences
if add_trivial:
# even steps = 1
self.add_even(1, 0)
self.add_remainder(1, 0, '0')
# even steps = 2
self.add_even(2, 1)
self.add_remainder(2, 1, '10')
@classmethod
def container_init(cls, container: CollatzContainer, step_size=4, batch_value=10000):
collatz = cls(container, step_size=step_size, batch_value=batch_value,
add_trivial=False)
stats_doc = collatz.container.get_stats()
collatz.total_percent = stats_doc["percent_complete"]
collatz.last_number = stats_doc["last_number"]
for even in collatz.container.get_even_list():
collatz.evens[even] = collatz.container.get_even_remainders(even)
return collatz
def add_even(self, even, odd):
"""
Creates a EvenSteps object and stores it in MongoDB.
:param even:
:param odd:
:return:
"""
self.evens[even] = []
even_obj = EvenSteps(even, odd)
self.container.add_even(even_obj)
return even_obj
def add_remainder(self, even, remainder, sequence):
self.evens[even].append(remainder)
rem_obj = Remainder(remainder, sequence)
self.container.add_remainder(even, rem_obj)
lesser_rem = (remainder - 1) / 2
if lesser_rem in self.evens[even]:
lesser_rem = int(lesser_rem)
lesser_seq = self.container.get_sequence(lesser_rem)
remainder_pair = RemainderPair(lesser_rem, remainder,
lesser_seq, sequence)
self.container.add_remainder_pair(even, remainder_pair)
def add_from_incomplete_list(self, incomplete_sequence):
"""
This algorithm takes in a list of incomplete numbers and add them.
Use self.generate_incomplete_numbers() to get a shifted.
If a new remainder is discovered, it checks if any numbers related
to that remainder is in the list and removes it if so.
:param incomplete_sequence:
:return:
"""
if incomplete_sequence:
last_num = incomplete_sequence[-1]
# The shifted might shorten, so this acts as a shrinking for loop
index = 0
while index < len(incomplete_sequence):
_, sequence, even, rem = calc_verbose(incomplete_sequence[index])
# even already found
if even not in self.evens:
odd = sequence.count('1')
self.add_even(even, odd)
self.add_remainder(even, rem, sequence)
# Checks if there's at least one now known number in the shifted
if rem + even < last_num:
# First multiple corresponds to remainder, equals 0.
last_multiple = floor((last_num - rem) / 2 ** even)
# The next multiple will be 1, so start there.
multiples = range(1, int(last_multiple + 1))
# Remove all now known numbers from the shifted
for multi in multiples:
incomplete_sequence.remove(multi * 2 ** even + rem)
index += 1
self.container.update_last_number(self.last_number)
self.container.update_percent_complete(self.calculate_number_percentage())
def add_incomplete_batch(self):
"""
Adds a batch using the "incomplete" algorithm.
First generates a list of incomplete numbers, then adds them, then
checks for even steps completeness.
This method works best when adding small batches.
:return:
"""
target_num = self.last_number + self.batch_value
sequence = [self.last_number]
while self.last_number < target_num:
self.last_number += self.step_size
sequence.append(self.last_number)
# Generates incomplete numbers
incomplete_nums = self.generate_incomplete_numbers(sequence)
# Adds the batch
self.add_from_incomplete_list(incomplete_nums)
# After the batch, check if any new even steps has been completed
self.check_for_even_steps_completeness()
def calculate_number_percentage(self):
"""
Calculates how many numbers are covered by the current dictionary.
The percent that a even steps covers is num_remainders/2**even steps.
Sum them to get a total percentage of numbers covered.
:return:
"""
self.total_percent = 0
for even, remainders in self.evens.items():
# Needs to be a float or python rounds
num_remainders = float(len(remainders))
# Adds the percentage for that even steps.
self.total_percent += num_remainders / 2 ** even
return self.total_percent
def check_for_even_steps_completeness(self):
"""
Checks if the last num has exceeded the even steps. Sets complete
if so.
:return:
"""
incomplete = self.container.get_complete_evens(False)
for even in incomplete:
if self.last_number >= 2 ** even:
self.container.set_even_completeness(even, True)
def generate_incomplete_numbers(self, sequence):
"""
Generates incomplete numbers based on even steps and remainders.
Use this shifted in self.add_from_incomplete_list()
The algorithm solves for multi in num=multi*2^even_20+remainder
and generates the first and last multiple based on the shifted.
Then it loops through those multiple and removes them from the list.
:param sequence:
:return:
"""
for even, remainders in self.evens.items():
if even in [1, 2]:
continue
for rem in remainders:
# Find the first multiple such that multi*2^even+remainder
# is greater than the first multiple. Same with last multiple
# except less than last number.
first_multiple = ceil((sequence[0] - rem) / 2**even)
last_multiple = floor((sequence[-1] - rem) / 2**even)
multiples = range(first_multiple, last_multiple + 1)
# Add these number to our known list
for multi in multiples:
known_number = multi * 2**even + rem
# Remove this number from our shifted
sequence.remove(known_number)
return sequence
def calc_verbose(number):
"""
Calculates the collatz shifted, parity shifted, even steps,
and the remainder to the next lowest number.
:param number:
:return:
"""
first = number
collatz_sequence = [number]
parity_sequence = ''
# loops while number is less than first
while number >= first:
parity = int(number % 2)
# Odd step
if parity:
number = (3 * number + 1) / 2
# Even step
else:
number /= 2
collatz_sequence.append(int(number))
parity_sequence += str(parity)
# Get even steps and remainder
# Just the length of the string since a 1 carries an implicit 0
even_steps = len(parity_sequence)
remainder = first % (2 ** even_steps)
return collatz_sequence, parity_sequence, even_steps, remainder
def calc_short(num, step):
"""
Performs the Collatz sequence to the desired step number and returns that number.
"""
for _ in range(step):
# Odd step
if num % 2:
num = (3 * num + 1) / 2
# Even step
else:
num /= 2
return num
def calc(num):
"""
Good ol' Collatz. Returns the collatz sequence for any number.
:param num:
:return:
"""
seq = []
while num >= 1:
parity = int(num % 2)
# Odd step
if parity:
num = (3 * num + 1) / 2
# Even step
else:
num /= 2
seq.append(int(num))
return seq
|
531f30dd55c26e7b642f5d39fb7cf9b2acd6b173 | jedzej/tietopythontraining-basic | /students/karbowniczyn_tomasz/lesson_01_basics/next_prev.py | 298 | 3.578125 | 4 | # by tk, next and prev number from number
# prev and next
liczba = int(input())
#print ('you wrote: ' + str((liczba)))
print ('The next number for the number '+ str(int((liczba))) +' is ' + str((liczba)+1))
print ('The prev number for the number '+ str(int((liczba))) + ' is ' + str((liczba)-1))
|
9a935bcb3454154e69c2c9d8b64078674e3e556f | Poonam-Singh-Bagh/python-question | /Function/factorial.py | 213 | 4.34375 | 4 | '''Q 5. Write a Python function to calculate the factorial of a number.'''
def factorial(number):
fact = 1
for number in range(number,1,-1):
fact *= number
return fact
print (factorial(5)) |
611eaa2a05a7a1dac685ddf6ea3f4f8186cc5319 | EstaticShark/leet-code-solutions | /#11 Container With Most Water/#11 Container With Most Water.py | 442 | 3.625 | 4 | from typing import List
def maxArea(height: List[int]) -> int:
j,k = 0, height.__len__() - 1
max_area = 0
while j < k:
if (k - j)*(min(height[j], height[k])) > max_area:
max_area = (k - j)*(min(height[j], height[k]))
if height[j] < height[k]:
j += 1
else:
k -= 1
return max_area
if __name__ == '__main__':
print(maxArea([1,8,6,2,5,4,8,3,7]))
print("bye") |
6eb8806d8a46a685ad048966a05827257813200c | muklah/Kattis | /Problems' Solutions/lineup.py | 363 | 3.84375 | 4 | import sys
n = int(input())
result = []
for i in range(n):
m = input()
if(len(m) < 2 or len(m) > 12):
break
for j in m:
if(j.islower()):
sys.exit()
result.append(m)
if(sorted(result) == result):
print("INCREASING")
elif(sorted(result, reverse=True) == result):
print("DECREASING")
else:
print("NEITHER") |
7388b1edc0fe8c111ff5afb9a50f943faa505385 | yankee-kate/Coursera | /week4/rec_sum.py | 159 | 3.8125 | 4 | def sum_rec(a, b):
if b != 0:
return sum_rec(a, b - 1) + 1
else:
return a
a = float(input())
b = float(input())
print(sum_rec(a, b))
|
40711d0a69f8c41bbaec29b3866fe23cfd9a13f9 | DavorKandic/numpy_practice_and_reference | /adv_indexing_practice.py | 1,113 | 4.03125 | 4 | import numpy as np
def space():
print()
print('#' * 30)
print()
# create array with arange(start,end,step) method
array_a = np.arange(0,100,5)
print(array_a)
print(array_a.size)
space()
# reshaping array with reshape(rows, columns) method
array_a_reshape = array_a.reshape(4,5) # 4 rows, 5 columns
print(array_a_reshape)
space()
# neg indexing
# Task: get last element(column) in every row
print(array_a_reshape[:,-1])
space()
# let's revise matrix transposition
array_a_reshape_t = array_a_reshape.T
print(array_a_reshape_t)
space()
# boolean indexing, all on same line!
# So with condition we are creating boolean matrix and than use it to filter
array_a_above_50 = array_a_reshape[array_a_reshape > 50]
print(array_a_above_50)
space()
# python slice
print(array_a_above_50[0:len(array_a_above_50):2])
space()
# slice of (every) row
print(array_a_reshape[:, 0:5:2])
space()
# another example using where(condition, True, False)
print(np.where(array_a_reshape>50, array_a_reshape, -1))
space()
# same, but multiply all values by 2
print(np.where(array_a_reshape>50, array_a_reshape*2, -1))
|
eccca6b1bf3b56933786c0c8e8619ad734dc1b05 | helios2k6/python3_interview_questions | /isTreeBalanced.py | 1,289 | 3.984375 | 4 | class BSTNode:
def __init__(self, value):
self.value = value
self.l = None
self.r = None
def insert(self, e):
if e.value <= self.value:
if not self.l:
self.l = e
else:
self.l.insert(e)
else:
if not self.r:
self.r = e
else:
self.r.insert(e)
def getHeight(tree: BSTNode):
if not tree:
return 0
lh = getHeight(tree.l)
rh = getHeight(tree.r)
return max(lh, rh) + 1
def isBalanced(tree: BSTNode):
if not tree:
return True
lh = getHeight(tree.l)
rh = getHeight(tree.r)
if abs(lh - rh) <= 1:
return isBalanced(tree.l) and isBalanced(tree.r)
return False
def test():
e = BSTNode("e")
c = BSTNode("c")
d = BSTNode("d")
a = BSTNode("a")
f = BSTNode("f")
b = BSTNode("b")
a.l = d
a.r = f
d.l = c
c.l = e
a.r = f
f.r = b
print(f"Is balanced: {isBalanced(a)}")
def test2():
e = BSTNode("e")
c = BSTNode("c")
d = BSTNode("d")
a = BSTNode("a")
f = BSTNode("f")
b = BSTNode("b")
e.l = c
e.r = d
c.l = a
d.l = f
d.r = b
print(f"Is balanced: {isBalanced(a)}")
test()
test2() |
cd3ae66ec8f755de00ee64e4374cf8b44e84619a | MAGomes95/Xray_classification | /src/utils/weights.py | 655 | 3.765625 | 4 | import pandas as pd
def class_weights(
target_column: pd.Series
) -> dict:
"""Calculate weight of each class in training
The weights are calculated through the count of
each instance in each class, in order to, weight
the loss function
Args:
target_column: Column containing the target
Returns:
Weight for each class
"""
target_column = target_column.astype(int)
frequencies = target_column.value_counts() / target_column.shape[0]
output = {
0: float(frequencies.loc[frequencies.index == 1]),
1: float(frequencies.loc[frequencies.index == 0])
}
return output
|
af7158500dca8aee234af2a7449ba8d082e9fba9 | KaterynaT/Tests | /progs/check_file.py | 895 | 4 | 4 | """
We have the list like ["Marun-001-002", "Merin 002-002", etc].
Create a function (check_files(seek_file_names, folder="./", name_prefix=None))to check if the file exists
in the directory. Name_prefix is not required. If it is defined, we are into only the names,
that start with this prefix.
"""
# -*- coding: utf-8 -*-
import os
def check_files(seek_file_names, folder="./", name_prefix=None):
# type: (object, object, object) -> object
"""
:param seek_file_names: the list with potential file names
:param folder: wanted folder for seeking the file
"""
list = []
list2 = []
for name in seek_file_names:
a = os.path.join(folder, name)
if os.path.exists(a):
list.append(a)
else:
list2.append(a)
print list
return list
if __name__ == "__main__":
check_files(["check_file.py","ttttt","ppopopo"])
|
c771174b6d394161e56886643c5fa76b8212f4df | pavankanjula/wallbreakers | /Week2/SortCharsByFrequency.py | 1,112 | 3.875 | 4 | import collections
class Solution:
def frequencySort(self, s: str) -> str:
#Time - worstcase(nlogn) to sort the frequncies when there is no repetitions in characters.
#Space - O(n) To store the multisets and list of frequencies.
multiset = collections.Counter(s) # multiset with no. of occurances of characters.
freq_to_key = {} #hashmap stores frequencies as keys and list of characters with that frequency as values.
freq_list = [] # List of all frequencies.
for key,value in multiset.items():
if value in freq_to_key:
freq_to_key[value].append(key)
else:
freq_to_key[value] = [key]
for key in freq_to_key.keys():
freq_list.append(key)
freq_list.sort(reverse = True) #Sorts the frequencies in reverse order.
output = "" #output string
for freq in freq_list:
for char in freq_to_key[freq]:
output += char*freq #for each frequeny, we check in freq_to_key multiset and appends the chars multiplied by frequency.
return output |
c7b92c255ee30872f57f292e50532a57c412eb27 | sarari0318/leetcode | /Tree/binary_tree_level_order_26.py | 963 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root):
'''
Parameters
------------------------
root: TreeNode
Returns
------------------------
res: List[List[int]]
'''
res = []
if not root:
return res
deque_node = collections.deque([root])
while deque_node:
level_nodes = []
for i in range(len(deque_node)):
curNode = deque_node.popleft()
level_nodes.append(curNode.val)
if curNode.left:
deque_node.append(curNode.left)
if curNode.right:
deque_node.append(curNode.right)
res.append(level_nodes)
return res
|
9601b1ff2e6a059fb2e40968d92524512e110dde | mizm/TIL | /algorithm/Day16/D16ex3.py | 600 | 3.59375 | 4 | class Node :
def __init__(self,data,link=None):
self.data = data
self.link = link
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node1.link=node2
node2.link=node3
node3.link=node4
node4.link=node5
head = None
def Enqueue(item) :
global head
newNode = Node(item)
if head == None :
head = newNode
else :
p = head
while p.link :
if p.link.data > item :
newNode.link = p.link
p.link = newNode
return
p = p.link
p.link = newNode
Enqueue(1)
Enqueue(5)
Enqueue(2)
Enqueue(4)
Enqueue(3)
p = head
while p :
print(p.data)
p = p.link
|
1b5fc0c07d731cdffe9e15aadf4f6c2347e0ea02 | lammyp/ref-man | /medlinex.py | 8,489 | 3.890625 | 4 | """This is a prototype program designed to read lines from a Medline .txt file,
determine where the records start, and assign the data for each record to an
entry in a dictionary (MLRef).
It includes a feature to determine which references are non-English and remove
the square brackets from around them; at the same time, square-bracketed
phrases within a title are left alone, while appended comments (which don't
appear for the same reference in all databases) are removed."""
def squ_bracket_check(ti_str):
"""A function that scans titles for square brackets and determines
whether they belong to a non-English language reference, or are a part of
the title. Removes square brackets from around non-English references, and
any square-bracketed comments from the end of titles."""
ti_clean = ''
# Check to see whether the first character of the Title is a "[", which
# indicates a non-English publication. If it is not found, append
# characters to the string "ti_clean". Keep adding characters until a "["
# is found, which signals the start of a comment if there is a "." in the
# preceding 2 positions, but otherwise is a part of the title:
# Alternative coding (from 3rd line of next block):
# if char == "[":
# if "." in ti[ti.index("[") - 2:ti.index("[")]:
# break
# else:
# ti_clean = ti_clean + char
if ti_str[0] != "[":
for char in ti_str:
if char != "[":
ti_clean = ti_clean + char
elif "." not in ti_str[ti_str.index("[") - 2:ti_str.index("[")]:
ti_clean = ti_clean + char
else:
break
# If the Title starts with a "[", then it is a non-English publication.
# Remove the initial "[" and loop through the input string, adding
# characters until a "]" is found. If it is found, determine whether it is
# the terminal character of the reference title (in which case the loop
# exits and we go looking for the next reference title), or whether it is
# closing a pair of square brackets within the title itself (in which case
# we continue along the current line):
else:
sqbracket_level = 1
ti_str = ti_str[1:-1] # Having found the initial "[", remove it.
while sqbracket_level > 0:
for char in ti_str:
if char != "]":
ti_clean = ti_clean + char
if char == "[":
sqbracket_level = sqbracket_level + 1
else:
pass
else:
sqbracket_level = sqbracket_level - 1
if sqbracket_level > 0:
ti_clean = ti_clean + char
else:
break
ti_clean.strip(".").strip()
return(ti_clean)
def split_medline_source(so_field):
"""This function takes the complete field under "Source" from the
Medline file and splits it into its component parts, returning these as a
dictionary."""
(journal, numbers) = so_field.split(".", 1)
journal = journal.strip()
(vol_issue, pages_date) = numbers.split(":")
vol_issue = vol_issue.strip(")")
(volume, issue) = vol_issue.split("(")
(pages, date) = pages_date.split(",", 1)
(start_page, endpg) = pages.split("-")
date_items = date.split(' ')
# Search for the year in a date field of inconsistent formatting:
for term in date_items:
term = term.strip()
if term[0:4].isdigit() == True:
year = term[0:4]
else:
continue
source_parts = {"journal":journal, "volume":volume, "issue":issue,
"pages":pages, "start_page":start_page, "year":year}
return source_parts
from sys import argv
import sqlite3
script, input_file = argv
x = str(input("Type a name for the database:" ))
print(x)
# Create a connection object to the database, ref1.db:
con1 = sqlite3.connect(x+'.db')
# Create a cursor object:
c1 = con1.cursor()
# Create a table to accept the reference data, unless it already exists:
try:
c1.execute('''CREATE TABLE ml1(id INT(3) NOT NULL, Authors TEXT NOT NULL,
Year INT NOT NULL)''')
except sqlite3.OperationalError:
print("Using existing table.")
pass
try:
with open(input_file) as f:
# Find the first occurrence of "<" and remove it to allow future
# occurrences to function as flags to a loop that determines the start
# of each new reference. Set the reference index, ref_count, to 0:
for line in f:
if line.startswith("<") == True:
line = line[1:-1]
ref_count = 0
break
# Now iterate through the lines in the file, looking for the terms
# "Author", "Title" and "Source". The actual data for each of these
# terms starts on the next line, so use "readline()" to find them. The
# "Source" field is split up into its components and the year (a four-
# digit item) is retrieved.
# Each reference is temporarily stored in the dictionary, "current_ref".
# current_ref starts with an index value, then follows with a list of
# authors, the title of the paper, and the source data including the year,
# volume, issue, start page and finish page.
current_ref = {}
for line in f:
line = line.strip()
# Find the Authors field, set the Index value for the current
# reference, and remove the punctuation before returning the author
# names as a list:
if line.startswith("Authors") == True:
current_ref["Index"] = ref_count
au = f.readline().strip().strip(".")
author_list = au.split(".")
# Currently it is necessary to pass the author list to sqlite3
# as a string; this should be modified to pass the list just
# created. The following 4 lines form the string:
author_string = ''
for item in author_list:
author_string = author_string +' '+ item.strip()
current_ref["Authors"] = author_string
# Return the title as a string, with external square brackets removed
# in the case of foreign language references:
elif line.startswith("Title") == True:
ti = f.readline().strip()
ti_clean = squ_bracket_check(ti)
current_ref["Title"] = ti_clean
# Return the components of the source data:
elif line.startswith("Source") == True:
source = f.readline()
current_ref["Source"] = source
current_ref["pubdata"] = split_medline_source(source)
current_ref["Journal"] = current_ref["pubdata"]["journal"]
current_ref["Year"] = current_ref["pubdata"]["year"]
current_ref["Volume"] = current_ref["pubdata"]["volume"]
# Presently the best (least worst) way of signalling the end of a
# reference is by finding the "Link" reference to the url, which is
# the last field in each reference. The "<" character that leads
# the next reference could be used, but then there would be nothing
# to signal the program to output the results from the last record,
# as there is no "<" at the very end of the file. This portion of
# the code may change when I find a better solution:
elif line.startswith("Link") == True:
#print(current_ref, "\n")
ref_data = (current_ref["Index"], current_ref["Authors"],
current_ref["Journal"], current_ref["Year"], current_ref["Title"])
print(ref_data)
short_data = (ref_count, current_ref["Authors"], int(current_ref["Year"]),)
# print(short_data)
c1.execute('INSERT INTO ml1 VALUES (?, ?, ?)', short_data)
con1.commit()
elif line.startswith("<") == True:
ref_count = ref_count + 1
else:
pass
except IOError as ioerr:
print("Unable to read file: "+str(ioerr))
print("\n\n")
con1.close()
|
ba965f5a1d2bec9384a07653eee5a6eb68329a7f | zhoulinyuan/Python- | /Python_Projects/game/String_exercise.py | 905 | 4.09375 | 4 | # -------------------字符串和编码--------------------
print('中文和english'); #python编码为Unicode,支持多种语言
print(ord('A'));#获取字符的整数表示
print(chr(65));#将编码转换成相应的字符
print('abc'.encode('ascii'));#encode()将字符串转换成byte
print('中文'.encode('utf-8'));
print('中文'.encode('ascii'));#中文编码超过ascii编码范围
'hello,%s'%'kk' #%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。
# -----------练习-----------------
# 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出'xx.x%',只保留小数点后1位:
score1 = 72;
score2 = 85;
ratio = score2 / score1 - 1
print('%.1f' % ratio);
|
145b487c49172ba43c23df398d7a48a6676b5245 | NobuyukiInoue/LeetCode | /Problems/1100_1199/1185_Day_of_the_Week/Project_Python3/Day_of_the_Week.py | 1,614 | 3.75 | 4 | # coding: utf-8
import calendar
import datetime
from datetime import date
import os
import sys
import time
class Solution:
# def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
def dayOfTheWeek(self, day, month, year):
# 24-36ms
return date(year, month, day).strftime("%A")
def dayOfTheWeek2(self, day, month, year):
# 40ms
return calendar.day_name[datetime.date(year, month, day).weekday()]
def main():
argv = sys.argv
argc = len(argv)
if argc < 2:
print("Usage: python {0} <testdata.txt>".format(argv[0]))
exit(0)
if not os.path.exists(argv[1]):
print("{0} not found...".format(argv[1]))
exit(0)
testDataFile = open(argv[1], "r")
lines = testDataFile.readlines()
for temp in lines:
temp = temp.strip()
if temp == "":
continue
print("args = {0}".format(temp))
loop_main(temp)
# print("Hit Return to continue...")
# input()
def loop_main(temp):
flds = temp.replace("[","").replace("]","").replace("\"","").replace(" ","").rstrip().split(",")
if len(flds) != 3:
print("Not 3 argument...")
return
day = int(flds[0])
month = int(flds[1])
year = int(flds[2])
print("day = {0:d}, month = {1:d}, year = {2:d}".format(day, month, year))
sl = Solution()
time0 = time.time()
result = sl.dayOfTheWeek(day, month, year)
time1 = time.time()
print("result = {0}".format(result))
print("Execute time ... : {0:f}[s]\n".format(time1 - time0))
if __name__ == "__main__":
main()
|
fc069d6d503ee88e3cb2d6390e370eefe47e54ac | kyuing/python_syntax | /loop.py | 158 | 3.921875 | 4 | #for statement
for value in ['a', 'b', 'c']:
#suite
print(value)
# for loop
print('------range-----------')
for value in range(10):
print(value)
|
491e6b102fee6f6084b1f56715d284b0e6d33782 | FawneLu/leetcode | /189/Solution.py | 1,147 | 4.3125 | 4 | ```python
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
index=1
while k:
nums.insert(0,nums[-1])
nums.pop(-1)
#index+=1
k-=1
return nums
```
```python
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
mod=k%len(nums)
res=[]
for i in range(mod):
res.append(nums[len(nums)-mod+i])
nums.pop(len(nums)-mod+i)
for i in range (len(res)):
nums.insert(i,res[i])
return nums
```
```python
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = nums[:]#深拷贝
#l=nums#浅拷贝
for i in range(len(nums)):
nums[(i+k)%len(nums)] = l[i]
return nums
``` |
53f95d5d9fe7f1a9ea39ceb07c89338f26adba6a | IIInvokeII/1st_sem_python | /Codes/15 - Cos function.py | 277 | 3.6875 | 4 | import f1
x=int(input("Enter the angle for x: "))
n=int(input("Enter the no. of terms: "))
c=0
sign=1
cos=0
for i in range(n):
prev=cos
cos=cos+sign*((x**c)/f1.fact(c))
c+=2
sign*=-1
if((cos-prev)<0.0005):
break
print("Cos",x,"=",cos)
|
739bec178266b7914e6ff40480c206ac866aad60 | mattfredericksen/CSCE-4350-Lego-Project | /menus/browse_menu.py | 673 | 3.671875 | 4 | """This menu is shown when customers select "Browse Bricks & Sets"."""
from consolemenu import ConsoleMenu
from consolemenu.items import FunctionItem
from menufunctions.browse import browse
from menufunctions.search import search
from sql import LegoDB
def browse_menu(database: LegoDB):
menu = ConsoleMenu('Browse & Search LEGO Products',
exit_option_text='Return to Main Menu')
for item in (FunctionItem('Browse Bricks', browse, [database, False]),
FunctionItem('Browse Sets', browse, [database, True]),
FunctionItem('Search All', search, [database])):
menu.append_item(item)
menu.show()
|
02c2f78cf78060b05656e18eeb1687e815e8d7bd | Daniel-W-Innes/SYSC1005-L4 | /Lab 4 Prelab/lab_4_prelab.py | 3,403 | 4.03125 | 4 | """ SYSC 1005 A Fall 2017 Lab 4 Prelab
"""
from Cimpl import *
# maximize_red is used in Part 1, Exercise 1
def maximize_red(image):
""" (Cimpl.Image) -> None
Maximize the red component of every pixel in image,
leaving the green and blue components unchanged.
>>> image = load_image(choose_file())
>>> maximize_red(image)
>>> show(image)
"""
# The for loop "visits" each pixel in image, row-by-row, starting with the
# pixel in the upper-left corner and finishing with the pixel in the
# lower-right corner. For each pixel, we unpack its x and y coordinates
# and its red, green and blue components, binding them to variables
# x, y, r, g, and b, respectively.
# After a pixel's components are unpacked, the body of the for
# loop is executed. A new Color object is created, using the original
# green and blue components, but with with the red component set to its
# maximum value (255). The pixel's colour is changed to this new colour.
# The for loop then visits the next pixel in the sequence, and the unpacking
# and modify-colour steps are repeated for that pixel.
for x, y, (r, g, b) in image:
new_color = create_color(255, g, b)
set_color(image, x, y, new_color)
# reduce_red_50 is used in Part 1, Exercise 2
def reduce_red_50(image):
""" (Cimpl.Image) -> None
Reduce the red component of every pixel in image to 50%
of its current value.
>>> image = load_image(choose_file())
>>> reduce_red_50(image)
>>> show(image)
"""
for x, y, (r, g, b) in image:
# decrease red component by 50%
new_color = create_color(r * 0.5, g, b)
set_color(image, x, y, new_color)
# Some functions to test the filters
def test_maximize_red():
image = load_image(choose_file())
show(image) # display the unmodified image
maximize_red(image)
show(image) # display the modified image
def test_reduce_red_50():
image = load_image(choose_file())
show(image) # display the unmodified image
reduce_red_50(image)
show(image) # display the modified image
def test_r_to_g():
image = load_image(choose_file())
show(image) # display the unmodified image
r_to_g(image)
show(image) # display the modified image
#-----------------------------------------------
# Put your solutions to Exercises 3 and 4 here.
def maximize_green(image):
for x, y, (r, g, b) in image:
new_color = create_color(r, 255, b)
set_color(image, x, y, new_color)
def maximize_blue(image):
for x, y, (r, g, b) in image:
new_color = create_color(r, g, 255)
set_color(image, x, y, new_color)
def reduce_green_50(image):
for x, y, (r, g, b) in image:
new_color = create_color(r, g * 0.5, b)
set_color(image, x, y, new_color)
def reduce_blue_50(image):
for x, y, (r, g, b) in image:
new_color = create_color(r, g, b * 0.5)
set_color(image, x, y, new_color)
def r_to_g(image):
""" (Cimpl.Image) -> None
Maximize the red component of every pixel in image,
leaving the green and blue components unchanged.
>>> image = load_image(choose_file())
>>> r_to_g(image)
>>> show(image)
"""
for x, y, (r, g, b) in image:
new_color = create_color(r, r,r)
set_color(image, x, y, new_color) |
2c7c92906a7c841203db1a9a20140c063633d02e | gabriellaec/desoft-analise-exercicios | /backup/user_196/ch89_2020_05_06_12_11_56_285468.py | 304 | 3.578125 | 4 | class Circulo:
def __init__(self, centro, raio):
self.centro = centro
self.raio = raio
def contem(self, ponto):
x = self.centro
y = self.centro
a = self.ponto
b = self.ponto
if (x - a)**2 +(y - b)**2 <= raio**2:
return True |
cae899e3be0a02377f64111cc37d5f1d87c97597 | hanabeast/CIT590-homework | /HW2/numberTheory.py | 3,138 | 3.859375 | 4 | #numberTheory.py
import math
import string
def isPrime(x):
'''check whether number x is prime'''
if x==1:
return False
for i in range(2,int(x)):
if x%i==0:
return False
return True
def isComposite(x):
'''check whether number x is composite'''
if x==1:
return False
elif isPrime(x):
return False
return True
def factorsSum(x):
'''find the sum of all x's factors'''
sum_of_factors=0
for i in range(1,int(x)):
if x%i==0:
sum_of_factors=sum_of_factors+i
return sum_of_factors
def isPerfect(x):
'''check whether number x is perfect'''
return factorsSum(x)==x
def isAbundant(x):
'''check whether number x is abundant'''
return factorsSum(x)>x
def isInt(x):
'''check if x is an integer or not'''
return x==int(x) and x>0
def checkSolution(a,b,c):
'''check if a*x^2+b*x+c=0 has integer solutions'''
if b**2-4*a*c<0:
return False
else:
delta=math.sqrt(b**2-4*a*c)
solution_a=(-b+delta)/(2*a)
solution_b=(-b-delta)/(2*a)
return isInt(solution_a) or isInt(solution_b)
def isTriangular(x):
'''check if x is triangular'''
return checkSolution(0.5,0.5,-x)
def isPentagonal(x):
'''check if x is pentagonal'''
return checkSolution(1.5,-0.5,-x)
def isHexagonal(x):
'''check if x is hexagonal'''
return checkSolution(2,-1,-x)
def finalprint(x):
''' get the finalprint '''
if isPrime(x):
finalprint=str(x)+' is prime,'
else:
finalprint=str(x)+' is not prime,'
if isComposite(x):
finalprint=finalprint+' is composite,'
else:
finalprint=finalprint+' is not composite,'
if isPerfect(x):
finalprint=finalprint+' is perfect,'
else:
finalprint=finalprint+' is not perfect,'
if isAbundant(x):
finalprint=finalprint+' is abundant,'
else:
finalprint=finalprint+' is not abundant,'
if isTriangular(x):
finalprint=finalprint+' is triangular,'
else:
finalprint=finalprint+' is not triangular,'
if isPentagonal(x):
finalprint=finalprint+' is pentagonal,'
else:
finalprint=finalprint+' is not pentagonal,'
if isHexagonal(x):
finalprint=finalprint+' is hexagonal.'
else:
finalprint=finalprint+' is not hexagonal.'
print finalprint
def main():
condition=True
while condition==True:
x=input("Please write an integer number between 1 and 10000(if you want to quit,write-1)")
while (isInt(x)==False or x<0 or x>10000) and x!=-1: #while x!=1 and x doesn't fit the requirement, ask to enter x again
print "Error,please write an integer number between 1 and 10000(if you want to quit,write-1)"
x=input("Please write an integer number between 1 and 10000(if you want to quit,write-1)")
if x==-1: #check if x=-1 after the second loop
condition=False
else:
finalprint(x)
if __name__=="__main__":
main()
|
bfc50f30fa2af0558fa1fd4a69f52886cb3011f3 | lkbwhite/lkb | /KSW/phyton/05/267_up.py | 410 | 3.875 | 4 | class Calculator:
def __init__(self, numbers):
self.numbers = numbers
def sum(self):
result = 0
for num in self.numbers:
result += num
return result
def avg(self):
total = self.sum()
return total / len(self.numbers)
# return sum(self) / len(self.numbers)
cal1 = Calculator([1,2,3,4,5])
print(cal1.sum())
print(cal1.avg())
cal2 = Calculator([6,7,8,9,10])
print(cal2.sum())
print(cal2.avg()) |
f19e9455d4beeb530b4e1bb4720d12fcef50f740 | marcluettecke/unoGame | /Rules.py | 2,683 | 4.15625 | 4 | from Player import Player
from Board import Board
def is_valid(card: str, middle_card: str):
"""
Function to determine if a card to play is valid given a current middle card. it checks if either the suit,
the number are acceptable or if the card is a Jack, which can be played on any middle card
Args:
card: String of the current card
middle_card: String of the current middle card
Returns:
Boolean if the card is valid
"""
return card[1] == middle_card[1] or card[0] == middle_card[0] or card[0] == 'J'
def special_card_7(current_player: Player, current_board: Board):
"""
Function to describe the action for special card 7: draw two cards.
Args:
current_player: current_board Player object' turn
current_board: current_board board object
Assigns:
two extra cards to the player object'special hand.
"""
current_player.draw_card(remaining_cards=current_board.remaining_cards, seven=True)
current_player.draw_card(remaining_cards=current_board.remaining_cards, seven=True)
print(f"{current_player.name} draws 2 cards ({current_player.hand[-2]}, {current_player.hand[-1]}) for a 7 in the "
f"middle.")
def special_card_8(current_player: Player, current_board: Board):
"""
Function to describe the action for special card 8: sit out.
Args:
current_player: current_board Player object' turn
current_board: current_board board object
Assigns:
the played card to the list of eights played.
"""
print(f"{current_player.name} has to sit out for {current_board.middle_cards[0]} in the middle.")
current_board.list_of_eights.append(current_board.middle_cards[0][1])
return True
def check_specialty_card(current_player: Player, current_board: Board):
"""
Function to check if special card is (7 for 8) is_valid played and conducting the required action.
Args:
current_player: current_board Player object' turn
current_board: current_board board object
Assigns:
updated board and player objects and describe the Function special card 7 and 8
"""
if current_board.middle_cards[0][0] in current_board.special_cards:
# special card 7 - draw 2 cards
if current_board.middle_cards[0][0] == '7':
special_card_7(current_player=current_player, current_board=current_board)
# special card 8 - sit out
if current_board.middle_cards[0][0] == '8' and current_board.middle_cards[0][
1] not in current_board.list_of_eights:
return special_card_8(current_player=current_player, current_board=current_board)
|
0dafb70ce852cfab93c5980493ece6e126bcc0d3 | daryabobina/python | /if8.py | 85 | 3.671875 | 4 | A=float(input())
B=float(input())
if (A>B):
print(A,B)
else:
print(B,A)
|
29b28981909ace80186319849db5a4d4d443a869 | LuckyLi0n/prog_golius | /UML/3 маленькие программы/Mother.py | 254 | 3.578125 | 4 | class Mother:
def voice(self):
return "Не плачь!"
def print(self):
print(self.voice())
class Daughter(Mother):
def voice(self):
return "Хнык, хнык!"
d = Daughter()
d.print()
m = Mother()
m.print()
|
559e9ccafc143a7e562d280208b31924257a7f21 | LorenzoMaramotti/compiti-informatica | /pag.191/es.31.py | 598 | 3.625 | 4 | zone_italia = {
"Zona nord":0,
"Zona centro":0,
"Zona sud":0,
"Zona isole":0
}
totale_fatturato = 0
for i in zone_italia:
print("Inserisci il fatturato della" , i)
fatturato_parziale = int(input())
totale_fatturato += fatturato_parziale
zone_italia[i] = fatturato_parziale
percentuale_fatturato = {}
for e in zone_italia:
percentuale = (zone_italia[e]/totale_fatturato)*100
percentuale_fatturato[e] = percentuale
print("la suddivisione del fatturato è" , zone_italia , "quella delle percentuali è" , percentuale_fatturato)
|
61c489e1ede3705c6c7597be91d9a3a44a31d789 | sumittal/coding-practice | /python/interpret_valid_sequence.py | 1,542 | 4.21875 | 4 | """
Convert the input number to alphabet representation
Let 0 represent ‘A’, 1 represents ‘B’, etc. Given a digit sequence, count the number of possible decodings of the given digit
sequence.
Input: digits[] = "121" Output: 3 ( The possible decodings are "BCB", "BV", "MB" ) Similarly "200" can be interpreted as "caa"
or "ua" and "007" has one.
"""
def valid_two_digit_encoding(a, b):
if not a or not b:
return False
if a in ('1', '2') and b < '6':
return True
return False
def valid_sequences(input_num):
if len(input_num) <= 1:
return 1
encodings = 0
if valid_two_digit_encoding(input_num[0], input_num[1]):
encodings += valid_sequences(input_num[2:])
encodings += valid_sequences(input_num[1:])
return encodings
def countValidSequences(input_num):
return valid_sequences(input_num)
# Input "1" output 1
print("Count ",countValidSequences("1"))
# Input "121" output 3
print("Count ",countValidSequences("121"))
# Input "200" output 2
print("Count ",countValidSequences("200"))
# Input "007" output 1
print("Count ",countValidSequences("007"))
# Input "2563" output 2
print("Count ",countValidSequences("2563"))
# Input "123" output 3
print("Count ",countValidSequences("123"))
# Input "99" output 1
print("Count ",countValidSequences("99"))
# Input "100200300" output 4
print("Count ",countValidSequences("100200300"))
# Input "2222" output 5
print("Count ",countValidSequences("2222"))
# Input "312" output 2
print("Count ",countValidSequences("312"))
|
b8f623bf066befed697b2abda8951a83fa404fd5 | Manish5432/pythontest | /main.py | 262 | 4.09375 | 4 | name = 'Manish'
print('Hello %s' %name)
x=1
y=2
if x != y:
print('Not equal')
else:
print('Equal')
surname = 'Manis'
if name == surname:
print('Equal')
else:
print('Not Equal')
print("%s is equal to %s : %s" %(name, surname, (name == surname))) |
9c2c7729d63a6913ee083939f5cfbdf94eff20c8 | amit-kr-debug/CP | /RobinHood/tech_mahindra.py | 409 | 3.734375 | 4 | def loanEligibilityCal(empType: str, age: int, sal: int, loanTerm: int):
if empType.lower() == "salaried" or empType.lower() == "self-employed":
if 21 <= age <= 58 and loanTerm + age <= 58 and sal >= 10000 and 1<=loanTerm<=30:
print("Eligible")
else:
print("Not Eligible")
else:
print("Not Eligible")
loanEligibilityCal("self-employed", 43, 25000, 10) |
ee3d7b4fbaf91b5934aa15522f283230b4cca01f | tsupei/leetcode | /python/44.py | 2,856 | 3.59375 | 4 | # Failed
# import time
# class Solution(object):
# def isMatch(self, s, p):
# """
# :type s: str
# :type p: str
# :rtype: bool
# """
# print(s, p)
# time.sleep(1)
# if not p:
# if not s:
# return True
# else:
# return False
# if p and not s:
# # if p is '*' then True
# for c in p:
# if c != '*':
# return False
# else:
# return True
# # Check num of chars
# cnt = 0
# for c in p:
# if c != '*' and c != '?':
# cnt += 1
# if cnt > len(s):
# return False
# # Check Last
# if p[-1] != '*' and p[-1] != '?':
# if p[-1] != s[-1]:
# return False
# if p[-1] == '?':
# return self.isMatch(s[:-1],p[:-1])
# if p[0] == '*':
# rep = 0
# for i in range(len(p)):
# if p[i] == '*':
# rep = i
# else:
# break
# # * is at the end of pattern
# if rep == len(p)-1:
# return True
# if len(p) <= 1:
# return True
# flag = False
# for i in range(len(s)):
# if s[i] != p[rep+1] and p[rep+1] != '?':
# # Cutting
# continue
# flag = flag or self.isMatch(s[i:], p[rep+1:])
# return flag
# elif p[0] == '?':
# return self.isMatch(s[1:], p[1:])
# else:
# if s[0] != p[0]:
# return False
# else:
# rep = 1
# while rep < len(s) and rep < len(p) and s[rep] == p[rep]:
# rep += 1
# return self.isMatch(s[1:], p[1:])
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
dp = [[False for i in range(len(p)+1)] for j in range(len(s)+1)]
dp[0][0] = True
# *****a
for i in range(1,len(p)+1):
if p[i-1] == '*':
dp[0][i] = dp[0][i-1]
for i in range(1,len(s)+1):
for j in range(1,len(p)+1):
if p[j-1] == '*':
# dp[i-1][j] ==> Match (Match any sequence)
# dp[i][j-1] ==> Match (Don't match anything)
dp[i][j] = dp[i-1][j] or dp[i][j-1]
else:
if p[j-1] == s[i-1]:
dp[i][j] = dp[i-1][j-1]
elif p[j-1] == '?':
dp[i][j] = dp[i-1][j-1]
print(i,j,dp[i][j])
return dp[len(s)][len(p)]
if __name__ == "__main__":
sol = Solution()
print(sol.isMatch("aa"
,"a")) |
bd883d203f400117c3cc6ccdbfc3bc0f3a6de958 | vijayendraben10/mycode | /python/python codes/python1.py | 56 | 3.640625 | 4 | #while loops
#a = 5
#while a < 10:
#a += 2
#print(a) |
65c46fc8007513461fe39a110e947546972d2e70 | changlongG/Algorithms | /sort/Insertionsort.py | 335 | 4.125 | 4 | def Insertionsort(list):
for i in range(len(list)):
temp = list[i]
j = i - 1
while j >= 0 and temp < list[j]:
list[j+1] = list[j]
j = j - 1
list[j+1] = temp
return list
a = [3,4,2,0,8,9,1,7,6,5]
b = [5,2,4,6,5,7,3,1,2,0]
print (Insertionsort(a))
print (Insertionsort(b)) |
01c57095cb2909d239d208a53d9c6c1810315296 | ChuckData/Coding_the_Matrix | /0528.py | 124 | 3.609375 | 4 | input_list = [2, 4, 6, 8, 10]
def nextInts(L):
output = [x+1 for x in L]
return output
print(nextInts(input_list)) |
9880366fb6c61d2ade10aa004812793a80b9764a | xueyingchen/Codewar-Solution | /sierpinski's_gasket.py | 425 | 3.5625 | 4 | def sierpinski(n):
"""
Returns a string containing the nth iteration of the Sierpinski Gasket
fractal
"""
if n == 0:
return 'L'
prev = sierpinski(n-1).split('\n')
n = len(prev[-1])
return '\n'.join(prev + [s.ljust(n + 1) + s for s in prev])
assert(sierpinski(0) == 'L')
assert(sierpinski(1) == 'L\nL L')
assert(sierpinski(2) == 'L\nL L\nL L\nL L L L'.strip())
print("tests passed")
|
109ff54107708cb80b466d32ae71cf0926b8a6a6 | Lipi99/python_projects | /sum_n_numbers.py | 409 | 4 | 4 | # python program to find sum of n numbers
n = int (input ("enter a nnumber")) # with n = 5
sum = 0
total = 0
for i in range (n+1):
sum = sum + n
print (sum)
# this for loop gives output 30 right? ye
# while loop to give the same output
# first make an index variable
i=0
while (i<n+1): # sry, n+1 hoga, because for loop mai bhi n+1 kiya tha
total+=n
i+=1
print(total)
# ok, |
eccc709084b62a37cf8c024e5db5a6eecdaeaf71 | Glebsan/GeekBrains_Python | /Lesson1/task1.py | 196 | 4.09375 | 4 | string_ = 'Privet'
float_ = 3.14
int_num = int(input('Enter number:'))
print('You entered:', int_num)
str_input = input('Enter string:')
print('You entered:', str_input)
print(string_, float_)
|
a46231ea156c704d7344029ef1b4c4052bdd55c7 | TheKinshu/100-Days-Python | /Day29/main.py | 4,324 | 3.65625 | 4 | from tkinter import *
from tkinter import messagebox
from random import choice, shuffle, randint
import pyperclip
import json
def find_password():
website = webInput.get()
if len(website) == 0:
messagebox.showinfo(title="Oops", message="Please enter a website name!")
else:
try:
with open('./Day29/data.json', mode='r') as file:
# Reading old data
data = json.load(file)
email = data[website]['email']
password = data[website]['password']
except FileNotFoundError:
messagebox.showinfo(title='Error', message="No Data File Found.")
except KeyError:
messagebox.showinfo(title='Error', message="There is no data for that website")
else:
messagebox.showinfo(title=website, message=f"Email: {email} \nPassword: {password}")
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def generate_pass():
passwordInput.delete(0,'end')
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
nr_letters = randint(8, 10)
nr_symbols = randint(2, 4)
nr_numbers = randint(2, 4)
password_letters = [choice(letters) for char in range(nr_letters)]
password_symbols = [choice(symbols) for char in range(nr_symbols)]
password_numbers = [choice(numbers) for char in range(nr_numbers)]
password_list = password_letters + password_symbols + password_numbers
shuffle(password_list)
password = "".join(password_list)
passwordInput.insert(0,password)
pyperclip.copy(password)
# ---------------------------- SAVE PASSWORD ------------------------------- #
def add_information():
website = webInput.get()
username = usernameInput.get()
password = passwordInput.get()
new_data = {
website:{
"email": username,
"password": password
}
}
if len(website) == 0 or len(password) == 0:
messagebox.showinfo(title="Oops", message="Please don't leave any fields empty!")
else:
try:
with open('./Day29/data.json', mode='r') as file:
# Reading old data
data = json.load(file)
except FileNotFoundError:
with open('./Day29/data.json', mode='w') as file:
json.dump(new_data, file, indent=4)
else:
# Updating old data
data.update(new_data)
with open('./Day29/data.json', mode='w') as file:
# Saving updated data
json.dump(data, file, indent=4)
finally:
webInput.delete(0,'end')
passwordInput.delete(0,'end')
# ---------------------------- UI SETUP ------------------------------- #
# padding 20
# width 200 height 200
window = Tk()
window.title('Password Manager')
window.config(pady=20, padx=20)
canvas = Canvas(width=200, height=200)
lock = PhotoImage(file='./Day29/logo.png')
canvas.create_image(100,100, image=lock)
canvas.grid(column=1, row=0)
# Labels
webLabel = Label(text='Website:')
webLabel.grid(column=0, row=1)
usernameLabel = Label(text='Email/Username:')
usernameLabel.grid(column=0, row=2)
passwordLabel = Label(text='Password:')
passwordLabel.grid(column=0, row=3)
# Entry
webInput = Entry(width=36)
webInput.grid(column=1, row=1)
usernameInput = Entry(width=53)
usernameInput.insert(0, 'kelvc.app@gmail.com')
usernameInput.grid(column=1, row=2, columnspan=2)
passwordInput = Entry(width=36)
passwordInput.grid(column=1, row=3)
# Button
searchBtn = Button(text='Search', width=13, command=find_password)
searchBtn.grid(column=2,row=1)
passGenerate = Button(text='Generate Password',width=13, command=generate_pass)
passGenerate.grid(column=2, row=3)
addButton = Button(text='Add', width=36, command=add_information)
addButton.grid(column=1, row=4, columnspan=2)
window.mainloop()
|
97a5a9dfcf865819bc2fe668a29219d4180ad6ac | krishnajaV/luminarPythonpgm- | /oops/inheritance/person.py | 580 | 3.5625 | 4 | # single inharitance
class Person:
def details(self, name, id, gender):#base class,super class,parent class
self.name = name
self.id = id
self.gender = gender
print(self.name)
print(self.id)
print(self.gender)
class Student(Person):#derived class,sub class,child class
def printval(self,dept,college):
self.dept=dept
self.college=college
print(self.dept)
print(self.college)
ob=Person()
ob.details("anju", 1, "Female")
st=Student()
st.printval("CSE","Luminar")
st.details("anu",2,"female")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.